PageRenderTime 69ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/test/test_re.py

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