PageRenderTime 93ms CodeModel.GetById 37ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/test/test_re.py

https://bitbucket.org/arigo/cpython-withatomic/
Python | 991 lines | 945 code | 30 blank | 16 comment | 2 complexity | b4f60573628827736cc5c57567689506 MD5 | raw file
Possible License(s): 0BSD
  1. from test.support import verbose, run_unittest, gc_collect
  2. import io
  3. import re
  4. from re import Scanner
  5. import sys
  6. import string
  7. import traceback
  8. from weakref import proxy
  9. # Misc tests from Tim Peters' re.doc
  10. # WARNING: Don't change details in these tests if you don't know
  11. # what you're doing. Some of these tests were carefully modeled to
  12. # cover most of the code.
  13. import unittest
  14. class ReTests(unittest.TestCase):
  15. def test_keep_buffer(self):
  16. # See bug 14212
  17. b = bytearray(b'x')
  18. it = re.finditer(b'a', b)
  19. with self.assertRaises(BufferError):
  20. b.extend(b'x'*400)
  21. list(it)
  22. del it
  23. gc_collect()
  24. b.extend(b'x'*400)
  25. def test_weakref(self):
  26. s = 'QabbbcR'
  27. x = re.compile('ab+c')
  28. y = proxy(x)
  29. self.assertEqual(x.findall('QabbbcR'), y.findall('QabbbcR'))
  30. def test_search_star_plus(self):
  31. self.assertEqual(re.search('x*', 'axx').span(0), (0, 0))
  32. self.assertEqual(re.search('x*', 'axx').span(), (0, 0))
  33. self.assertEqual(re.search('x+', 'axx').span(0), (1, 3))
  34. self.assertEqual(re.search('x+', 'axx').span(), (1, 3))
  35. self.assertEqual(re.search('x', 'aaa'), None)
  36. self.assertEqual(re.match('a*', 'xxx').span(0), (0, 0))
  37. self.assertEqual(re.match('a*', 'xxx').span(), (0, 0))
  38. self.assertEqual(re.match('x*', 'xxxa').span(0), (0, 3))
  39. self.assertEqual(re.match('x*', 'xxxa').span(), (0, 3))
  40. self.assertEqual(re.match('a+', 'xxx'), None)
  41. def bump_num(self, matchobj):
  42. int_value = int(matchobj.group(0))
  43. return str(int_value + 1)
  44. def test_basic_re_sub(self):
  45. self.assertEqual(re.sub("(?i)b+", "x", "bbbb BBBB"), 'x x')
  46. self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y'),
  47. '9.3 -3 24x100y')
  48. self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', 3),
  49. '9.3 -3 23x99y')
  50. self.assertEqual(re.sub('.', lambda m: r"\n", 'x'), '\\n')
  51. self.assertEqual(re.sub('.', r"\n", 'x'), '\n')
  52. s = r"\1\1"
  53. self.assertEqual(re.sub('(.)', s, 'x'), 'xx')
  54. self.assertEqual(re.sub('(.)', re.escape(s), 'x'), s)
  55. self.assertEqual(re.sub('(.)', lambda m: s, 'x'), s)
  56. self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<a>', 'xx'), 'xxxx')
  57. self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<1>', 'xx'), 'xxxx')
  58. self.assertEqual(re.sub('(?P<unk>x)', '\g<unk>\g<unk>', 'xx'), 'xxxx')
  59. self.assertEqual(re.sub('(?P<unk>x)', '\g<1>\g<1>', 'xx'), 'xxxx')
  60. self.assertEqual(re.sub('a',r'\t\n\v\r\f\a\b\B\Z\a\A\w\W\s\S\d\D','a'),
  61. '\t\n\v\r\f\a\b\\B\\Z\a\\A\\w\\W\\s\\S\\d\\D')
  62. self.assertEqual(re.sub('a', '\t\n\v\r\f\a', 'a'), '\t\n\v\r\f\a')
  63. self.assertEqual(re.sub('a', '\t\n\v\r\f\a', 'a'),
  64. (chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7)))
  65. self.assertEqual(re.sub('^\s*', 'X', 'test'), 'Xtest')
  66. def test_bug_449964(self):
  67. # fails for group followed by other escape
  68. self.assertEqual(re.sub(r'(?P<unk>x)', '\g<1>\g<1>\\b', 'xx'),
  69. 'xx\bxx\b')
  70. def test_bug_449000(self):
  71. # Test for sub() on escaped characters
  72. self.assertEqual(re.sub(r'\r\n', r'\n', 'abc\r\ndef\r\n'),
  73. 'abc\ndef\n')
  74. self.assertEqual(re.sub('\r\n', r'\n', 'abc\r\ndef\r\n'),
  75. 'abc\ndef\n')
  76. self.assertEqual(re.sub(r'\r\n', '\n', 'abc\r\ndef\r\n'),
  77. 'abc\ndef\n')
  78. self.assertEqual(re.sub('\r\n', '\n', 'abc\r\ndef\r\n'),
  79. 'abc\ndef\n')
  80. def test_bug_1661(self):
  81. # Verify that flags do not get silently ignored with compiled patterns
  82. pattern = re.compile('.')
  83. self.assertRaises(ValueError, re.match, pattern, 'A', re.I)
  84. self.assertRaises(ValueError, re.search, pattern, 'A', re.I)
  85. self.assertRaises(ValueError, re.findall, pattern, 'A', re.I)
  86. self.assertRaises(ValueError, re.compile, pattern, re.I)
  87. def test_bug_3629(self):
  88. # A regex that triggered a bug in the sre-code validator
  89. re.compile("(?P<quote>)(?(quote))")
  90. def test_sub_template_numeric_escape(self):
  91. # bug 776311 and friends
  92. self.assertEqual(re.sub('x', r'\0', 'x'), '\0')
  93. self.assertEqual(re.sub('x', r'\000', 'x'), '\000')
  94. self.assertEqual(re.sub('x', r'\001', 'x'), '\001')
  95. self.assertEqual(re.sub('x', r'\008', 'x'), '\0' + '8')
  96. self.assertEqual(re.sub('x', r'\009', 'x'), '\0' + '9')
  97. self.assertEqual(re.sub('x', r'\111', 'x'), '\111')
  98. self.assertEqual(re.sub('x', r'\117', 'x'), '\117')
  99. self.assertEqual(re.sub('x', r'\1111', 'x'), '\1111')
  100. self.assertEqual(re.sub('x', r'\1111', 'x'), '\111' + '1')
  101. self.assertEqual(re.sub('x', r'\00', 'x'), '\x00')
  102. self.assertEqual(re.sub('x', r'\07', 'x'), '\x07')
  103. self.assertEqual(re.sub('x', r'\08', 'x'), '\0' + '8')
  104. self.assertEqual(re.sub('x', r'\09', 'x'), '\0' + '9')
  105. self.assertEqual(re.sub('x', r'\0a', 'x'), '\0' + 'a')
  106. self.assertEqual(re.sub('x', r'\400', 'x'), '\0')
  107. self.assertEqual(re.sub('x', r'\777', 'x'), '\377')
  108. self.assertRaises(re.error, re.sub, 'x', r'\1', 'x')
  109. self.assertRaises(re.error, re.sub, 'x', r'\8', 'x')
  110. self.assertRaises(re.error, re.sub, 'x', r'\9', 'x')
  111. self.assertRaises(re.error, re.sub, 'x', r'\11', 'x')
  112. self.assertRaises(re.error, re.sub, 'x', r'\18', 'x')
  113. self.assertRaises(re.error, re.sub, 'x', r'\1a', 'x')
  114. self.assertRaises(re.error, re.sub, 'x', r'\90', 'x')
  115. self.assertRaises(re.error, re.sub, 'x', r'\99', 'x')
  116. self.assertRaises(re.error, re.sub, 'x', r'\118', 'x') # r'\11' + '8'
  117. self.assertRaises(re.error, re.sub, 'x', r'\11a', 'x')
  118. self.assertRaises(re.error, re.sub, 'x', r'\181', 'x') # r'\18' + '1'
  119. self.assertRaises(re.error, re.sub, 'x', r'\800', 'x') # r'\80' + '0'
  120. # in python2.3 (etc), these loop endlessly in sre_parser.py
  121. self.assertEqual(re.sub('(((((((((((x)))))))))))', r'\11', 'x'), 'x')
  122. self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\118', 'xyz'),
  123. 'xz8')
  124. self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\11a', 'xyz'),
  125. 'xza')
  126. def test_qualified_re_sub(self):
  127. self.assertEqual(re.sub('a', 'b', 'aaaaa'), 'bbbbb')
  128. self.assertEqual(re.sub('a', 'b', 'aaaaa', 1), 'baaaa')
  129. def test_bug_114660(self):
  130. self.assertEqual(re.sub(r'(\S)\s+(\S)', r'\1 \2', 'hello there'),
  131. 'hello there')
  132. def test_bug_462270(self):
  133. # Test for empty sub() behaviour, see SF bug #462270
  134. self.assertEqual(re.sub('x*', '-', 'abxd'), '-a-b-d-')
  135. self.assertEqual(re.sub('x+', '-', 'abxd'), 'ab-d')
  136. def test_symbolic_refs(self):
  137. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a', 'xx')
  138. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<', 'xx')
  139. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g', 'xx')
  140. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a a>', 'xx')
  141. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<1a1>', 'xx')
  142. self.assertRaises(IndexError, re.sub, '(?P<a>x)', '\g<ab>', 'xx')
  143. self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\g<b>', 'xx')
  144. self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\\2', 'xx')
  145. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<-1>', 'xx')
  146. def test_re_subn(self):
  147. self.assertEqual(re.subn("(?i)b+", "x", "bbbb BBBB"), ('x x', 2))
  148. self.assertEqual(re.subn("b+", "x", "bbbb BBBB"), ('x BBBB', 1))
  149. self.assertEqual(re.subn("b+", "x", "xyz"), ('xyz', 0))
  150. self.assertEqual(re.subn("b*", "x", "xyz"), ('xxxyxzx', 4))
  151. self.assertEqual(re.subn("b*", "x", "xyz", 2), ('xxxyz', 2))
  152. def test_re_split(self):
  153. self.assertEqual(re.split(":", ":a:b::c"), ['', 'a', 'b', '', 'c'])
  154. self.assertEqual(re.split(":*", ":a:b::c"), ['', 'a', 'b', 'c'])
  155. self.assertEqual(re.split("(:*)", ":a:b::c"),
  156. ['', ':', 'a', ':', 'b', '::', 'c'])
  157. self.assertEqual(re.split("(?::*)", ":a:b::c"), ['', 'a', 'b', 'c'])
  158. self.assertEqual(re.split("(:)*", ":a:b::c"),
  159. ['', ':', 'a', ':', 'b', ':', 'c'])
  160. self.assertEqual(re.split("([b:]+)", ":a:b::c"),
  161. ['', ':', 'a', ':b::', 'c'])
  162. self.assertEqual(re.split("(b)|(:+)", ":a:b::c"),
  163. ['', None, ':', 'a', None, ':', '', 'b', None, '',
  164. None, '::', 'c'])
  165. self.assertEqual(re.split("(?:b)|(?::+)", ":a:b::c"),
  166. ['', 'a', '', '', 'c'])
  167. def test_qualified_re_split(self):
  168. self.assertEqual(re.split(":", ":a:b::c", 2), ['', 'a', 'b::c'])
  169. self.assertEqual(re.split(':', 'a:b:c:d', 2), ['a', 'b', 'c:d'])
  170. self.assertEqual(re.split("(:)", ":a:b::c", 2),
  171. ['', ':', 'a', ':', 'b::c'])
  172. self.assertEqual(re.split("(:*)", ":a:b::c", 2),
  173. ['', ':', 'a', ':', 'b::c'])
  174. def test_re_findall(self):
  175. self.assertEqual(re.findall(":+", "abc"), [])
  176. self.assertEqual(re.findall(":+", "a:b::c:::d"), [":", "::", ":::"])
  177. self.assertEqual(re.findall("(:+)", "a:b::c:::d"), [":", "::", ":::"])
  178. self.assertEqual(re.findall("(:)(:*)", "a:b::c:::d"), [(":", ""),
  179. (":", ":"),
  180. (":", "::")])
  181. def test_bug_117612(self):
  182. self.assertEqual(re.findall(r"(a|(b))", "aba"),
  183. [("a", ""),("b", "b"),("a", "")])
  184. def test_re_match(self):
  185. self.assertEqual(re.match('a', 'a').groups(), ())
  186. self.assertEqual(re.match('(a)', 'a').groups(), ('a',))
  187. self.assertEqual(re.match(r'(a)', 'a').group(0), 'a')
  188. self.assertEqual(re.match(r'(a)', 'a').group(1), 'a')
  189. self.assertEqual(re.match(r'(a)', 'a').group(1, 1), ('a', 'a'))
  190. pat = re.compile('((a)|(b))(c)?')
  191. self.assertEqual(pat.match('a').groups(), ('a', 'a', None, None))
  192. self.assertEqual(pat.match('b').groups(), ('b', None, 'b', None))
  193. self.assertEqual(pat.match('ac').groups(), ('a', 'a', None, 'c'))
  194. self.assertEqual(pat.match('bc').groups(), ('b', None, 'b', 'c'))
  195. self.assertEqual(pat.match('bc').groups(""), ('b', "", 'b', 'c'))
  196. # A single group
  197. m = re.match('(a)', 'a')
  198. self.assertEqual(m.group(0), 'a')
  199. self.assertEqual(m.group(0), 'a')
  200. self.assertEqual(m.group(1), 'a')
  201. self.assertEqual(m.group(1, 1), ('a', 'a'))
  202. pat = re.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
  203. self.assertEqual(pat.match('a').group(1, 2, 3), ('a', None, None))
  204. self.assertEqual(pat.match('b').group('a1', 'b2', 'c3'),
  205. (None, 'b', None))
  206. self.assertEqual(pat.match('ac').group(1, 'b2', 3), ('a', None, 'c'))
  207. def test_re_groupref_exists(self):
  208. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', '(a)').groups(),
  209. ('(', 'a'))
  210. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', 'a').groups(),
  211. (None, 'a'))
  212. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', 'a)'), None)
  213. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', '(a'), None)
  214. self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'ab').groups(),
  215. ('a', 'b'))
  216. self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'cd').groups(),
  217. (None, 'd'))
  218. self.assertEqual(re.match('^(?:(a)|c)((?(1)|d))$', 'cd').groups(),
  219. (None, 'd'))
  220. self.assertEqual(re.match('^(?:(a)|c)((?(1)|d))$', 'a').groups(),
  221. ('a', ''))
  222. # Tests for bug #1177831: exercise groups other than the first group
  223. p = re.compile('(?P<g1>a)(?P<g2>b)?((?(g2)c|d))')
  224. self.assertEqual(p.match('abc').groups(),
  225. ('a', 'b', 'c'))
  226. self.assertEqual(p.match('ad').groups(),
  227. ('a', None, 'd'))
  228. self.assertEqual(p.match('abd'), None)
  229. self.assertEqual(p.match('ac'), None)
  230. def test_re_groupref(self):
  231. self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', '|a|').groups(),
  232. ('|', 'a'))
  233. self.assertEqual(re.match(r'^(\|)?([^()]+)\1?$', 'a').groups(),
  234. (None, 'a'))
  235. self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', 'a|'), None)
  236. self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', '|a'), None)
  237. self.assertEqual(re.match(r'^(?:(a)|c)(\1)$', 'aa').groups(),
  238. ('a', 'a'))
  239. self.assertEqual(re.match(r'^(?:(a)|c)(\1)?$', 'c').groups(),
  240. (None, None))
  241. def test_groupdict(self):
  242. self.assertEqual(re.match('(?P<first>first) (?P<second>second)',
  243. 'first second').groupdict(),
  244. {'first':'first', 'second':'second'})
  245. def test_expand(self):
  246. self.assertEqual(re.match("(?P<first>first) (?P<second>second)",
  247. "first second")
  248. .expand(r"\2 \1 \g<second> \g<first>"),
  249. "second first second first")
  250. def test_repeat_minmax(self):
  251. self.assertEqual(re.match("^(\w){1}$", "abc"), None)
  252. self.assertEqual(re.match("^(\w){1}?$", "abc"), None)
  253. self.assertEqual(re.match("^(\w){1,2}$", "abc"), None)
  254. self.assertEqual(re.match("^(\w){1,2}?$", "abc"), None)
  255. self.assertEqual(re.match("^(\w){3}$", "abc").group(1), "c")
  256. self.assertEqual(re.match("^(\w){1,3}$", "abc").group(1), "c")
  257. self.assertEqual(re.match("^(\w){1,4}$", "abc").group(1), "c")
  258. self.assertEqual(re.match("^(\w){3,4}?$", "abc").group(1), "c")
  259. self.assertEqual(re.match("^(\w){3}?$", "abc").group(1), "c")
  260. self.assertEqual(re.match("^(\w){1,3}?$", "abc").group(1), "c")
  261. self.assertEqual(re.match("^(\w){1,4}?$", "abc").group(1), "c")
  262. self.assertEqual(re.match("^(\w){3,4}?$", "abc").group(1), "c")
  263. self.assertEqual(re.match("^x{1}$", "xxx"), None)
  264. self.assertEqual(re.match("^x{1}?$", "xxx"), None)
  265. self.assertEqual(re.match("^x{1,2}$", "xxx"), None)
  266. self.assertEqual(re.match("^x{1,2}?$", "xxx"), None)
  267. self.assertNotEqual(re.match("^x{3}$", "xxx"), None)
  268. self.assertNotEqual(re.match("^x{1,3}$", "xxx"), None)
  269. self.assertNotEqual(re.match("^x{1,4}$", "xxx"), None)
  270. self.assertNotEqual(re.match("^x{3,4}?$", "xxx"), None)
  271. self.assertNotEqual(re.match("^x{3}?$", "xxx"), None)
  272. self.assertNotEqual(re.match("^x{1,3}?$", "xxx"), None)
  273. self.assertNotEqual(re.match("^x{1,4}?$", "xxx"), None)
  274. self.assertNotEqual(re.match("^x{3,4}?$", "xxx"), None)
  275. self.assertEqual(re.match("^x{}$", "xxx"), None)
  276. self.assertNotEqual(re.match("^x{}$", "x{}"), None)
  277. def test_getattr(self):
  278. self.assertEqual(re.compile("(?i)(a)(b)").pattern, "(?i)(a)(b)")
  279. self.assertEqual(re.compile("(?i)(a)(b)").flags, re.I | re.U)
  280. self.assertEqual(re.compile("(?i)(a)(b)").groups, 2)
  281. self.assertEqual(re.compile("(?i)(a)(b)").groupindex, {})
  282. self.assertEqual(re.compile("(?i)(?P<first>a)(?P<other>b)").groupindex,
  283. {'first': 1, 'other': 2})
  284. self.assertEqual(re.match("(a)", "a").pos, 0)
  285. self.assertEqual(re.match("(a)", "a").endpos, 1)
  286. self.assertEqual(re.match("(a)", "a").string, "a")
  287. self.assertEqual(re.match("(a)", "a").regs, ((0, 1), (0, 1)))
  288. self.assertNotEqual(re.match("(a)", "a").re, None)
  289. def test_special_escapes(self):
  290. self.assertEqual(re.search(r"\b(b.)\b",
  291. "abcd abc bcd bx").group(1), "bx")
  292. self.assertEqual(re.search(r"\B(b.)\B",
  293. "abc bcd bc abxd").group(1), "bx")
  294. self.assertEqual(re.search(r"\b(b.)\b",
  295. "abcd abc bcd bx", re.LOCALE).group(1), "bx")
  296. self.assertEqual(re.search(r"\B(b.)\B",
  297. "abc bcd bc abxd", re.LOCALE).group(1), "bx")
  298. self.assertEqual(re.search(r"\b(b.)\b",
  299. "abcd abc bcd bx", re.UNICODE).group(1), "bx")
  300. self.assertEqual(re.search(r"\B(b.)\B",
  301. "abc bcd bc abxd", re.UNICODE).group(1), "bx")
  302. self.assertEqual(re.search(r"^abc$", "\nabc\n", re.M).group(0), "abc")
  303. self.assertEqual(re.search(r"^\Aabc\Z$", "abc", re.M).group(0), "abc")
  304. self.assertEqual(re.search(r"^\Aabc\Z$", "\nabc\n", re.M), None)
  305. self.assertEqual(re.search(r"\b(b.)\b",
  306. "abcd abc bcd bx").group(1), "bx")
  307. self.assertEqual(re.search(r"\B(b.)\B",
  308. "abc bcd bc abxd").group(1), "bx")
  309. self.assertEqual(re.search(r"^abc$", "\nabc\n", re.M).group(0), "abc")
  310. self.assertEqual(re.search(r"^\Aabc\Z$", "abc", re.M).group(0), "abc")
  311. self.assertEqual(re.search(r"^\Aabc\Z$", "\nabc\n", re.M), None)
  312. self.assertEqual(re.search(r"\d\D\w\W\s\S",
  313. "1aa! a").group(0), "1aa! a")
  314. self.assertEqual(re.search(r"\d\D\w\W\s\S",
  315. "1aa! a", re.LOCALE).group(0), "1aa! a")
  316. self.assertEqual(re.search(r"\d\D\w\W\s\S",
  317. "1aa! a", re.UNICODE).group(0), "1aa! a")
  318. def test_string_boundaries(self):
  319. # See http://bugs.python.org/issue10713
  320. self.assertEqual(re.search(r"\b(abc)\b", "abc").group(1),
  321. "abc")
  322. # There's a word boundary at the start of a string.
  323. self.assertTrue(re.match(r"\b", "abc"))
  324. # A non-empty string includes a non-boundary zero-length match.
  325. self.assertTrue(re.search(r"\B", "abc"))
  326. # There is no non-boundary match at the start of a string.
  327. self.assertFalse(re.match(r"\B", "abc"))
  328. # However, an empty string contains no word boundaries, and also no
  329. # non-boundaries.
  330. self.assertEqual(re.search(r"\B", ""), None)
  331. # This one is questionable and different from the perlre behaviour,
  332. # but describes current behavior.
  333. self.assertEqual(re.search(r"\b", ""), None)
  334. # A single word-character string has two boundaries, but no
  335. # non-boundary gaps.
  336. self.assertEqual(len(re.findall(r"\b", "a")), 2)
  337. self.assertEqual(len(re.findall(r"\B", "a")), 0)
  338. # If there are no words, there are no boundaries
  339. self.assertEqual(len(re.findall(r"\b", " ")), 0)
  340. self.assertEqual(len(re.findall(r"\b", " ")), 0)
  341. # Can match around the whitespace.
  342. self.assertEqual(len(re.findall(r"\B", " ")), 2)
  343. def test_bigcharset(self):
  344. self.assertEqual(re.match("([\u2222\u2223])",
  345. "\u2222").group(1), "\u2222")
  346. self.assertEqual(re.match("([\u2222\u2223])",
  347. "\u2222", re.UNICODE).group(1), "\u2222")
  348. def test_anyall(self):
  349. self.assertEqual(re.match("a.b", "a\nb", re.DOTALL).group(0),
  350. "a\nb")
  351. self.assertEqual(re.match("a.*b", "a\n\nb", re.DOTALL).group(0),
  352. "a\n\nb")
  353. def test_non_consuming(self):
  354. self.assertEqual(re.match("(a(?=\s[^a]))", "a b").group(1), "a")
  355. self.assertEqual(re.match("(a(?=\s[^a]*))", "a b").group(1), "a")
  356. self.assertEqual(re.match("(a(?=\s[abc]))", "a b").group(1), "a")
  357. self.assertEqual(re.match("(a(?=\s[abc]*))", "a bc").group(1), "a")
  358. self.assertEqual(re.match(r"(a)(?=\s\1)", "a a").group(1), "a")
  359. self.assertEqual(re.match(r"(a)(?=\s\1*)", "a aa").group(1), "a")
  360. self.assertEqual(re.match(r"(a)(?=\s(abc|a))", "a a").group(1), "a")
  361. self.assertEqual(re.match(r"(a(?!\s[^a]))", "a a").group(1), "a")
  362. self.assertEqual(re.match(r"(a(?!\s[abc]))", "a d").group(1), "a")
  363. self.assertEqual(re.match(r"(a)(?!\s\1)", "a b").group(1), "a")
  364. self.assertEqual(re.match(r"(a)(?!\s(abc|a))", "a b").group(1), "a")
  365. def test_ignore_case(self):
  366. self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
  367. self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
  368. self.assertEqual(re.match(r"(a\s[^a])", "a b", re.I).group(1), "a b")
  369. self.assertEqual(re.match(r"(a\s[^a]*)", "a bb", re.I).group(1), "a bb")
  370. self.assertEqual(re.match(r"(a\s[abc])", "a b", re.I).group(1), "a b")
  371. self.assertEqual(re.match(r"(a\s[abc]*)", "a bb", re.I).group(1), "a bb")
  372. self.assertEqual(re.match(r"((a)\s\2)", "a a", re.I).group(1), "a a")
  373. self.assertEqual(re.match(r"((a)\s\2*)", "a aa", re.I).group(1), "a aa")
  374. self.assertEqual(re.match(r"((a)\s(abc|a))", "a a", re.I).group(1), "a a")
  375. self.assertEqual(re.match(r"((a)\s(abc|a)*)", "a aa", re.I).group(1), "a aa")
  376. def test_category(self):
  377. self.assertEqual(re.match(r"(\s)", " ").group(1), " ")
  378. def test_getlower(self):
  379. import _sre
  380. self.assertEqual(_sre.getlower(ord('A'), 0), ord('a'))
  381. self.assertEqual(_sre.getlower(ord('A'), re.LOCALE), ord('a'))
  382. self.assertEqual(_sre.getlower(ord('A'), re.UNICODE), ord('a'))
  383. self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
  384. self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
  385. def test_not_literal(self):
  386. self.assertEqual(re.search("\s([^a])", " b").group(1), "b")
  387. self.assertEqual(re.search("\s([^a]*)", " bb").group(1), "bb")
  388. def test_search_coverage(self):
  389. self.assertEqual(re.search("\s(b)", " b").group(1), "b")
  390. self.assertEqual(re.search("a\s", "a ").group(0), "a ")
  391. def assertMatch(self, pattern, text, match=None, span=None,
  392. matcher=re.match):
  393. if match is None and span is None:
  394. # the pattern matches the whole text
  395. match = text
  396. span = (0, len(text))
  397. elif match is None or span is None:
  398. raise ValueError('If match is not None, span should be specified '
  399. '(and vice versa).')
  400. m = matcher(pattern, text)
  401. self.assertTrue(m)
  402. self.assertEqual(m.group(), match)
  403. self.assertEqual(m.span(), span)
  404. def test_re_escape(self):
  405. alnum_chars = string.ascii_letters + string.digits + '_'
  406. p = ''.join(chr(i) for i in range(256))
  407. for c in p:
  408. if c in alnum_chars:
  409. self.assertEqual(re.escape(c), c)
  410. elif c == '\x00':
  411. self.assertEqual(re.escape(c), '\\000')
  412. else:
  413. self.assertEqual(re.escape(c), '\\' + c)
  414. self.assertMatch(re.escape(c), c)
  415. self.assertMatch(re.escape(p), p)
  416. def test_re_escape_byte(self):
  417. alnum_chars = (string.ascii_letters + string.digits + '_').encode('ascii')
  418. p = bytes(range(256))
  419. for i in p:
  420. b = bytes([i])
  421. if b in alnum_chars:
  422. self.assertEqual(re.escape(b), b)
  423. elif i == 0:
  424. self.assertEqual(re.escape(b), b'\\000')
  425. else:
  426. self.assertEqual(re.escape(b), b'\\' + b)
  427. self.assertMatch(re.escape(b), b)
  428. self.assertMatch(re.escape(p), p)
  429. def test_re_escape_non_ascii(self):
  430. s = 'xxx\u2620\u2620\u2620xxx'
  431. s_escaped = re.escape(s)
  432. self.assertEqual(s_escaped, 'xxx\\\u2620\\\u2620\\\u2620xxx')
  433. self.assertMatch(s_escaped, s)
  434. self.assertMatch('.%s+.' % re.escape('\u2620'), s,
  435. 'x\u2620\u2620\u2620x', (2, 7), re.search)
  436. def test_re_escape_non_ascii_bytes(self):
  437. b = 'y\u2620y\u2620y'.encode('utf-8')
  438. b_escaped = re.escape(b)
  439. self.assertEqual(b_escaped, b'y\\\xe2\\\x98\\\xa0y\\\xe2\\\x98\\\xa0y')
  440. self.assertMatch(b_escaped, b)
  441. res = re.findall(re.escape('\u2620'.encode('utf-8')), b)
  442. self.assertEqual(len(res), 2)
  443. def pickle_test(self, pickle):
  444. oldpat = re.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
  445. s = pickle.dumps(oldpat)
  446. newpat = pickle.loads(s)
  447. self.assertEqual(oldpat, newpat)
  448. def test_constants(self):
  449. self.assertEqual(re.I, re.IGNORECASE)
  450. self.assertEqual(re.L, re.LOCALE)
  451. self.assertEqual(re.M, re.MULTILINE)
  452. self.assertEqual(re.S, re.DOTALL)
  453. self.assertEqual(re.X, re.VERBOSE)
  454. def test_flags(self):
  455. for flag in [re.I, re.M, re.X, re.S, re.L]:
  456. self.assertNotEqual(re.compile('^pattern$', flag), None)
  457. def test_sre_character_literals(self):
  458. for i in [0, 8, 16, 32, 64, 127, 128, 255]:
  459. self.assertNotEqual(re.match(r"\%03o" % i, chr(i)), None)
  460. self.assertNotEqual(re.match(r"\%03o0" % i, chr(i)+"0"), None)
  461. self.assertNotEqual(re.match(r"\%03o8" % i, chr(i)+"8"), None)
  462. self.assertNotEqual(re.match(r"\x%02x" % i, chr(i)), None)
  463. self.assertNotEqual(re.match(r"\x%02x0" % i, chr(i)+"0"), None)
  464. self.assertNotEqual(re.match(r"\x%02xz" % i, chr(i)+"z"), None)
  465. self.assertRaises(re.error, re.match, "\911", "")
  466. def test_sre_character_class_literals(self):
  467. for i in [0, 8, 16, 32, 64, 127, 128, 255]:
  468. self.assertNotEqual(re.match(r"[\%03o]" % i, chr(i)), None)
  469. self.assertNotEqual(re.match(r"[\%03o0]" % i, chr(i)), None)
  470. self.assertNotEqual(re.match(r"[\%03o8]" % i, chr(i)), None)
  471. self.assertNotEqual(re.match(r"[\x%02x]" % i, chr(i)), None)
  472. self.assertNotEqual(re.match(r"[\x%02x0]" % i, chr(i)), None)
  473. self.assertNotEqual(re.match(r"[\x%02xz]" % i, chr(i)), None)
  474. self.assertRaises(re.error, re.match, "[\911]", "")
  475. def test_bug_113254(self):
  476. self.assertEqual(re.match(r'(a)|(b)', 'b').start(1), -1)
  477. self.assertEqual(re.match(r'(a)|(b)', 'b').end(1), -1)
  478. self.assertEqual(re.match(r'(a)|(b)', 'b').span(1), (-1, -1))
  479. def test_bug_527371(self):
  480. # bug described in patches 527371/672491
  481. self.assertEqual(re.match(r'(a)?a','a').lastindex, None)
  482. self.assertEqual(re.match(r'(a)(b)?b','ab').lastindex, 1)
  483. self.assertEqual(re.match(r'(?P<a>a)(?P<b>b)?b','ab').lastgroup, 'a')
  484. self.assertEqual(re.match("(?P<a>a(b))", "ab").lastgroup, 'a')
  485. self.assertEqual(re.match("((a))", "a").lastindex, 1)
  486. def test_bug_545855(self):
  487. # bug 545855 -- This pattern failed to cause a compile error as it
  488. # should, instead provoking a TypeError.
  489. self.assertRaises(re.error, re.compile, 'foo[a-')
  490. def test_bug_418626(self):
  491. # bugs 418626 at al. -- Testing Greg Chapman's addition of op code
  492. # SRE_OP_MIN_REPEAT_ONE for eliminating recursion on simple uses of
  493. # pattern '*?' on a long string.
  494. self.assertEqual(re.match('.*?c', 10000*'ab'+'cd').end(0), 20001)
  495. self.assertEqual(re.match('.*?cd', 5000*'ab'+'c'+5000*'ab'+'cde').end(0),
  496. 20003)
  497. self.assertEqual(re.match('.*?cd', 20000*'abc'+'de').end(0), 60001)
  498. # non-simple '*?' still used to hit the recursion limit, before the
  499. # non-recursive scheme was implemented.
  500. self.assertEqual(re.search('(a|b)*?c', 10000*'ab'+'cd').end(0), 20001)
  501. def test_bug_612074(self):
  502. pat="["+re.escape("\u2039")+"]"
  503. self.assertEqual(re.compile(pat) and 1, 1)
  504. def test_stack_overflow(self):
  505. # nasty cases that used to overflow the straightforward recursive
  506. # implementation of repeated groups.
  507. self.assertEqual(re.match('(x)*', 50000*'x').group(1), 'x')
  508. self.assertEqual(re.match('(x)*y', 50000*'x'+'y').group(1), 'x')
  509. self.assertEqual(re.match('(x)*?y', 50000*'x'+'y').group(1), 'x')
  510. def test_scanner(self):
  511. def s_ident(scanner, token): return token
  512. def s_operator(scanner, token): return "op%s" % token
  513. def s_float(scanner, token): return float(token)
  514. def s_int(scanner, token): return int(token)
  515. scanner = Scanner([
  516. (r"[a-zA-Z_]\w*", s_ident),
  517. (r"\d+\.\d*", s_float),
  518. (r"\d+", s_int),
  519. (r"=|\+|-|\*|/", s_operator),
  520. (r"\s+", None),
  521. ])
  522. self.assertNotEqual(scanner.scanner.scanner("").pattern, None)
  523. self.assertEqual(scanner.scan("sum = 3*foo + 312.50 + bar"),
  524. (['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5,
  525. 'op+', 'bar'], ''))
  526. def test_bug_448951(self):
  527. # bug 448951 (similar to 429357, but with single char match)
  528. # (Also test greedy matches.)
  529. for op in '','?','*':
  530. self.assertEqual(re.match(r'((.%s):)?z'%op, 'z').groups(),
  531. (None, None))
  532. self.assertEqual(re.match(r'((.%s):)?z'%op, 'a:z').groups(),
  533. ('a:', 'a'))
  534. def test_bug_725106(self):
  535. # capturing groups in alternatives in repeats
  536. self.assertEqual(re.match('^((a)|b)*', 'abc').groups(),
  537. ('b', 'a'))
  538. self.assertEqual(re.match('^(([ab])|c)*', 'abc').groups(),
  539. ('c', 'b'))
  540. self.assertEqual(re.match('^((d)|[ab])*', 'abc').groups(),
  541. ('b', None))
  542. self.assertEqual(re.match('^((a)c|[ab])*', 'abc').groups(),
  543. ('b', None))
  544. self.assertEqual(re.match('^((a)|b)*?c', 'abc').groups(),
  545. ('b', 'a'))
  546. self.assertEqual(re.match('^(([ab])|c)*?d', 'abcd').groups(),
  547. ('c', 'b'))
  548. self.assertEqual(re.match('^((d)|[ab])*?c', 'abc').groups(),
  549. ('b', None))
  550. self.assertEqual(re.match('^((a)c|[ab])*?c', 'abc').groups(),
  551. ('b', None))
  552. def test_bug_725149(self):
  553. # mark_stack_base restoring before restoring marks
  554. self.assertEqual(re.match('(a)(?:(?=(b)*)c)*', 'abb').groups(),
  555. ('a', None))
  556. self.assertEqual(re.match('(a)((?!(b)*))*', 'abb').groups(),
  557. ('a', None, None))
  558. def test_bug_764548(self):
  559. # bug 764548, re.compile() barfs on str/unicode subclasses
  560. class my_unicode(str): pass
  561. pat = re.compile(my_unicode("abc"))
  562. self.assertEqual(pat.match("xyz"), None)
  563. def test_finditer(self):
  564. iter = re.finditer(r":+", "a:b::c:::d")
  565. self.assertEqual([item.group(0) for item in iter],
  566. [":", "::", ":::"])
  567. pat = re.compile(r":+")
  568. iter = pat.finditer("a:b::c:::d", 1, 10)
  569. self.assertEqual([item.group(0) for item in iter],
  570. [":", "::", ":::"])
  571. pat = re.compile(r":+")
  572. iter = pat.finditer("a:b::c:::d", pos=1, endpos=10)
  573. self.assertEqual([item.group(0) for item in iter],
  574. [":", "::", ":::"])
  575. pat = re.compile(r":+")
  576. iter = pat.finditer("a:b::c:::d", endpos=10, pos=1)
  577. self.assertEqual([item.group(0) for item in iter],
  578. [":", "::", ":::"])
  579. pat = re.compile(r":+")
  580. iter = pat.finditer("a:b::c:::d", pos=3, endpos=8)
  581. self.assertEqual([item.group(0) for item in iter],
  582. ["::", "::"])
  583. def test_bug_926075(self):
  584. self.assertTrue(re.compile('bug_926075') is not
  585. re.compile(b'bug_926075'))
  586. def test_bug_931848(self):
  587. pattern = eval('"[\u002E\u3002\uFF0E\uFF61]"')
  588. self.assertEqual(re.compile(pattern).split("a.b.c"),
  589. ['a','b','c'])
  590. def test_bug_581080(self):
  591. iter = re.finditer(r"\s", "a b")
  592. self.assertEqual(next(iter).span(), (1,2))
  593. self.assertRaises(StopIteration, next, iter)
  594. scanner = re.compile(r"\s").scanner("a b")
  595. self.assertEqual(scanner.search().span(), (1, 2))
  596. self.assertEqual(scanner.search(), None)
  597. def test_bug_817234(self):
  598. iter = re.finditer(r".*", "asdf")
  599. self.assertEqual(next(iter).span(), (0, 4))
  600. self.assertEqual(next(iter).span(), (4, 4))
  601. self.assertRaises(StopIteration, next, iter)
  602. def test_bug_6561(self):
  603. # '\d' should match characters in Unicode category 'Nd'
  604. # (Number, Decimal Digit), but not those in 'Nl' (Number,
  605. # Letter) or 'No' (Number, Other).
  606. decimal_digits = [
  607. '\u0037', # '\N{DIGIT SEVEN}', category 'Nd'
  608. '\u0e58', # '\N{THAI DIGIT SIX}', category 'Nd'
  609. '\uff10', # '\N{FULLWIDTH DIGIT ZERO}', category 'Nd'
  610. ]
  611. for x in decimal_digits:
  612. self.assertEqual(re.match('^\d$', x).group(0), x)
  613. not_decimal_digits = [
  614. '\u2165', # '\N{ROMAN NUMERAL SIX}', category 'Nl'
  615. '\u3039', # '\N{HANGZHOU NUMERAL TWENTY}', category 'Nl'
  616. '\u2082', # '\N{SUBSCRIPT TWO}', category 'No'
  617. '\u32b4', # '\N{CIRCLED NUMBER THIRTY NINE}', category 'No'
  618. ]
  619. for x in not_decimal_digits:
  620. self.assertIsNone(re.match('^\d$', x))
  621. def test_empty_array(self):
  622. # SF buf 1647541
  623. import array
  624. for typecode in 'bBuhHiIlLfd':
  625. a = array.array(typecode)
  626. self.assertEqual(re.compile(b"bla").match(a), None)
  627. self.assertEqual(re.compile(b"").match(a).groups(), ())
  628. def test_inline_flags(self):
  629. # Bug #1700
  630. upper_char = chr(0x1ea0) # Latin Capital Letter A with Dot Bellow
  631. lower_char = chr(0x1ea1) # Latin Small Letter A with Dot Bellow
  632. p = re.compile(upper_char, re.I | re.U)
  633. q = p.match(lower_char)
  634. self.assertNotEqual(q, None)
  635. p = re.compile(lower_char, re.I | re.U)
  636. q = p.match(upper_char)
  637. self.assertNotEqual(q, None)
  638. p = re.compile('(?i)' + upper_char, re.U)
  639. q = p.match(lower_char)
  640. self.assertNotEqual(q, None)
  641. p = re.compile('(?i)' + lower_char, re.U)
  642. q = p.match(upper_char)
  643. self.assertNotEqual(q, None)
  644. p = re.compile('(?iu)' + upper_char)
  645. q = p.match(lower_char)
  646. self.assertNotEqual(q, None)
  647. p = re.compile('(?iu)' + lower_char)
  648. q = p.match(upper_char)
  649. self.assertNotEqual(q, None)
  650. def test_dollar_matches_twice(self):
  651. "$ matches the end of string, and just before the terminating \n"
  652. pattern = re.compile('$')
  653. self.assertEqual(pattern.sub('#', 'a\nb\n'), 'a\nb#\n#')
  654. self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a\nb\nc#')
  655. self.assertEqual(pattern.sub('#', '\n'), '#\n#')
  656. pattern = re.compile('$', re.MULTILINE)
  657. self.assertEqual(pattern.sub('#', 'a\nb\n' ), 'a#\nb#\n#' )
  658. self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a#\nb#\nc#')
  659. self.assertEqual(pattern.sub('#', '\n'), '#\n#')
  660. def test_bytes_str_mixing(self):
  661. # Mixing str and bytes is disallowed
  662. pat = re.compile('.')
  663. bpat = re.compile(b'.')
  664. self.assertRaises(TypeError, pat.match, b'b')
  665. self.assertRaises(TypeError, bpat.match, 'b')
  666. self.assertRaises(TypeError, pat.sub, b'b', 'c')
  667. self.assertRaises(TypeError, pat.sub, 'b', b'c')
  668. self.assertRaises(TypeError, pat.sub, b'b', b'c')
  669. self.assertRaises(TypeError, bpat.sub, b'b', 'c')
  670. self.assertRaises(TypeError, bpat.sub, 'b', b'c')
  671. self.assertRaises(TypeError, bpat.sub, 'b', 'c')
  672. def test_ascii_and_unicode_flag(self):
  673. # String patterns
  674. for flags in (0, re.UNICODE):
  675. pat = re.compile('\xc0', flags | re.IGNORECASE)
  676. self.assertNotEqual(pat.match('\xe0'), None)
  677. pat = re.compile('\w', flags)
  678. self.assertNotEqual(pat.match('\xe0'), None)
  679. pat = re.compile('\xc0', re.ASCII | re.IGNORECASE)
  680. self.assertEqual(pat.match('\xe0'), None)
  681. pat = re.compile('(?a)\xc0', re.IGNORECASE)
  682. self.assertEqual(pat.match('\xe0'), None)
  683. pat = re.compile('\w', re.ASCII)
  684. self.assertEqual(pat.match('\xe0'), None)
  685. pat = re.compile('(?a)\w')
  686. self.assertEqual(pat.match('\xe0'), None)
  687. # Bytes patterns
  688. for flags in (0, re.ASCII):
  689. pat = re.compile(b'\xc0', re.IGNORECASE)
  690. self.assertEqual(pat.match(b'\xe0'), None)
  691. pat = re.compile(b'\w')
  692. self.assertEqual(pat.match(b'\xe0'), None)
  693. # Incompatibilities
  694. self.assertRaises(ValueError, re.compile, b'\w', re.UNICODE)
  695. self.assertRaises(ValueError, re.compile, b'(?u)\w')
  696. self.assertRaises(ValueError, re.compile, '\w', re.UNICODE | re.ASCII)
  697. self.assertRaises(ValueError, re.compile, '(?u)\w', re.ASCII)
  698. self.assertRaises(ValueError, re.compile, '(?a)\w', re.UNICODE)
  699. self.assertRaises(ValueError, re.compile, '(?au)\w')
  700. def test_bug_6509(self):
  701. # Replacement strings of both types must parse properly.
  702. # all strings
  703. pat = re.compile('a(\w)')
  704. self.assertEqual(pat.sub('b\\1', 'ac'), 'bc')
  705. pat = re.compile('a(.)')
  706. self.assertEqual(pat.sub('b\\1', 'a\u1234'), 'b\u1234')
  707. pat = re.compile('..')
  708. self.assertEqual(pat.sub(lambda m: 'str', 'a5'), 'str')
  709. # all bytes
  710. pat = re.compile(b'a(\w)')
  711. self.assertEqual(pat.sub(b'b\\1', b'ac'), b'bc')
  712. pat = re.compile(b'a(.)')
  713. self.assertEqual(pat.sub(b'b\\1', b'a\xCD'), b'b\xCD')
  714. pat = re.compile(b'..')
  715. self.assertEqual(pat.sub(lambda m: b'bytes', b'a5'), b'bytes')
  716. def test_dealloc(self):
  717. # issue 3299: check for segfault in debug build
  718. import _sre
  719. # the overflow limit is different on wide and narrow builds and it
  720. # depends on the definition of SRE_CODE (see sre.h).
  721. # 2**128 should be big enough to overflow on both. For smaller values
  722. # a RuntimeError is raised instead of OverflowError.
  723. long_overflow = 2**128
  724. self.assertRaises(TypeError, re.finditer, "a", {})
  725. self.assertRaises(OverflowError, _sre.compile, "abc", 0, [long_overflow])
  726. self.assertRaises(TypeError, _sre.compile, {}, 0, [])
  727. def test_search_dot_unicode(self):
  728. self.assertIsNotNone(re.search("123.*-", '123abc-'))
  729. self.assertIsNotNone(re.search("123.*-", '123\xe9-'))
  730. self.assertIsNotNone(re.search("123.*-", '123\u20ac-'))
  731. self.assertIsNotNone(re.search("123.*-", '123\U0010ffff-'))
  732. self.assertIsNotNone(re.search("123.*-", '123\xe9\u20ac\U0010ffff-'))
  733. def test_compile(self):
  734. # Test return value when given string and pattern as parameter
  735. pattern = re.compile('random pattern')
  736. self.assertIsInstance(pattern, re._pattern_type)
  737. same_pattern = re.compile(pattern)
  738. self.assertIsInstance(same_pattern, re._pattern_type)
  739. self.assertIs(same_pattern, pattern)
  740. # Test behaviour when not given a string or pattern as parameter
  741. self.assertRaises(TypeError, re.compile, 0)
  742. def run_re_tests():
  743. from test.re_tests import tests, SUCCEED, FAIL, SYNTAX_ERROR
  744. if verbose:
  745. print('Running re_tests test suite')
  746. else:
  747. # To save time, only run the first and last 10 tests
  748. #tests = tests[:10] + tests[-10:]
  749. pass
  750. for t in tests:
  751. sys.stdout.flush()
  752. pattern = s = outcome = repl = expected = None
  753. if len(t) == 5:
  754. pattern, s, outcome, repl, expected = t
  755. elif len(t) == 3:
  756. pattern, s, outcome = t
  757. else:
  758. raise ValueError('Test tuples should have 3 or 5 fields', t)
  759. try:
  760. obj = re.compile(pattern)
  761. except re.error:
  762. if outcome == SYNTAX_ERROR: pass # Expected a syntax error
  763. else:
  764. print('=== Syntax error:', t)
  765. except KeyboardInterrupt: raise KeyboardInterrupt
  766. except:
  767. print('*** Unexpected error ***', t)
  768. if verbose:
  769. traceback.print_exc(file=sys.stdout)
  770. else:
  771. try:
  772. result = obj.search(s)
  773. except re.error as msg:
  774. print('=== Unexpected exception', t, repr(msg))
  775. if outcome == SYNTAX_ERROR:
  776. # This should have been a syntax error; forget it.
  777. pass
  778. elif outcome == FAIL:
  779. if result is None: pass # No match, as expected
  780. else: print('=== Succeeded incorrectly', t)
  781. elif outcome == SUCCEED:
  782. if result is not None:
  783. # Matched, as expected, so now we compute the
  784. # result string and compare it to our expected result.
  785. start, end = result.span(0)
  786. vardict={'found': result.group(0),
  787. 'groups': result.group(),
  788. 'flags': result.re.flags}
  789. for i in range(1, 100):
  790. try:
  791. gi = result.group(i)
  792. # Special hack because else the string concat fails:
  793. if gi is None:
  794. gi = "None"
  795. except IndexError:
  796. gi = "Error"
  797. vardict['g%d' % i] = gi
  798. for i in result.re.groupindex.keys():
  799. try:
  800. gi = result.group(i)
  801. if gi is None:
  802. gi = "None"
  803. except IndexError:
  804. gi = "Error"
  805. vardict[i] = gi
  806. repl = eval(repl, vardict)
  807. if repl != expected:
  808. print('=== grouping error', t, end=' ')
  809. print(repr(repl) + ' should be ' + repr(expected))
  810. else:
  811. print('=== Failed incorrectly', t)
  812. # Try the match with both pattern and string converted to
  813. # bytes, and check that it still succeeds.
  814. try:
  815. bpat = bytes(pattern, "ascii")
  816. bs = bytes(s, "ascii")
  817. except UnicodeEncodeError:
  818. # skip non-ascii tests
  819. pass
  820. else:
  821. try:
  822. bpat = re.compile(bpat)
  823. except Exception:
  824. print('=== Fails on bytes pattern compile', t)
  825. if verbose:
  826. traceback.print_exc(file=sys.stdout)
  827. else:
  828. bytes_result = bpat.search(bs)
  829. if bytes_result is None:
  830. print('=== Fails on bytes pattern match', t)
  831. # Try the match with the search area limited to the extent
  832. # of the match and see if it still succeeds. \B will
  833. # break (because it won't match at the end or start of a
  834. # string), so we'll ignore patterns that feature it.
  835. if pattern[:2] != '\\B' and pattern[-2:] != '\\B' \
  836. and result is not None:
  837. obj = re.compile(pattern)
  838. result = obj.search(s, result.start(0), result.end(0) + 1)
  839. if result is None:
  840. print('=== Failed on range-limited match', t)
  841. # Try the match with IGNORECASE enabled, and check that it
  842. # still succeeds.
  843. obj = re.compile(pattern, re.IGNORECASE)
  844. result = obj.search(s)
  845. if result is None:
  846. print('=== Fails on case-insensitive match', t)
  847. # Try the match with LOCALE enabled, and check that it
  848. # still succeeds.
  849. if '(?u)' not in pattern:
  850. obj = re.compile(pattern, re.LOCALE)
  851. result = obj.search(s)
  852. if result is None:
  853. print('=== Fails on locale-sensitive match', t)
  854. # Try the match with UNICODE locale enabled, and check
  855. # that it still succeeds.
  856. obj = re.compile(pattern, re.UNICODE)
  857. result = obj.search(s)
  858. if result is None:
  859. print('=== Fails on unicode-sensitive match', t)
  860. def test_main():
  861. run_unittest(ReTests)
  862. run_re_tests()
  863. if __name__ == "__main__":
  864. test_main()