PageRenderTime 52ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/test_re.py

http://github.com/axiak/pyre2
Python | 824 lines | 789 code | 22 blank | 13 comment | 6 complexity | b1bd8657172d0129aa7e10724a28b9ad MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from test.test_support import verbose, run_unittest, import_module
  2. import re2 as re
  3. from re import Scanner
  4. import sys, os, traceback
  5. from weakref import proxy
  6. # Misc tests from Tim Peters' re.doc
  7. # WARNING: Don't change details in these tests if you don't know
  8. # what you're doing. Some of these tests were carefuly modeled to
  9. # cover most of the code.
  10. import unittest
  11. class ReTests(unittest.TestCase):
  12. def test_weakref(self):
  13. s = 'QabbbcR'
  14. x = re.compile('ab+c')
  15. y = proxy(x)
  16. self.assertEqual(x.findall('QabbbcR'), y.findall('QabbbcR'))
  17. def test_search_star_plus(self):
  18. self.assertEqual(re.search('x*', 'axx').span(0), (0, 0))
  19. self.assertEqual(re.search('x*', 'axx').span(), (0, 0))
  20. self.assertEqual(re.search('x+', 'axx').span(0), (1, 3))
  21. self.assertEqual(re.search('x+', 'axx').span(), (1, 3))
  22. self.assertEqual(re.search('x', 'aaa'), None)
  23. self.assertEqual(re.match('a*', 'xxx').span(0), (0, 0))
  24. self.assertEqual(re.match('a*', 'xxx').span(), (0, 0))
  25. self.assertEqual(re.match('x*', 'xxxa').span(0), (0, 3))
  26. self.assertEqual(re.match('x*', 'xxxa').span(), (0, 3))
  27. self.assertEqual(re.match('a+', 'xxx'), None)
  28. def bump_num(self, matchobj):
  29. int_value = int(matchobj.group(0))
  30. return str(int_value + 1)
  31. def test_basic_re_sub(self):
  32. self.assertEqual(re.sub("(?i)b+", "x", "bbbb BBBB"), 'x x')
  33. self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y'),
  34. '9.3 -3 24x100y')
  35. self.assertEqual(re.sub(r'\d+', self.bump_num, '08.2 -2 23x99y', 3),
  36. '9.3 -3 23x99y')
  37. self.assertEqual(re.sub('.', lambda m: r"\n", 'x'), '\\n')
  38. self.assertEqual(re.sub('.', r"\n", 'x'), '\n')
  39. s = r"\1\1"
  40. self.assertEqual(re.sub('(.)', s, 'x'), 'xx')
  41. self.assertEqual(re.sub('(.)', re.escape(s), 'x'), s)
  42. self.assertEqual(re.sub('(.)', lambda m: s, 'x'), s)
  43. self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<a>', 'xx'), 'xxxx')
  44. self.assertEqual(re.sub('(?P<a>x)', '\g<a>\g<1>', 'xx'), 'xxxx')
  45. self.assertEqual(re.sub('(?P<unk>x)', '\g<unk>\g<unk>', 'xx'), 'xxxx')
  46. self.assertEqual(re.sub('(?P<unk>x)', '\g<1>\g<1>', 'xx'), 'xxxx')
  47. self.assertEqual(re.sub('a',r'\t\n\v\r\f\a\b\B\Z\a\A\w\W\s\S\d\D','a'),
  48. '\t\n\v\r\f\a\b\\B\\Z\a\\A\\w\\W\\s\\S\\d\\D')
  49. self.assertEqual(re.sub('a', '\t\n\v\r\f\a', 'a'), '\t\n\v\r\f\a')
  50. self.assertEqual(re.sub('a', '\t\n\v\r\f\a', 'a'),
  51. (chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7)))
  52. self.assertEqual(re.sub('^\s*', 'X', 'test'), 'Xtest')
  53. def test_bug_449964(self):
  54. # fails for group followed by other escape
  55. self.assertEqual(re.sub(r'(?P<unk>x)', '\g<1>\g<1>\\b', 'xx'),
  56. 'xx\bxx\b')
  57. def test_bug_449000(self):
  58. # Test for sub() on escaped characters
  59. self.assertEqual(re.sub(r'\r\n', r'\n', 'abc\r\ndef\r\n'),
  60. 'abc\ndef\n')
  61. self.assertEqual(re.sub('\r\n', r'\n', 'abc\r\ndef\r\n'),
  62. 'abc\ndef\n')
  63. self.assertEqual(re.sub(r'\r\n', '\n', 'abc\r\ndef\r\n'),
  64. 'abc\ndef\n')
  65. self.assertEqual(re.sub('\r\n', '\n', 'abc\r\ndef\r\n'),
  66. 'abc\ndef\n')
  67. def test_bug_1140(self):
  68. # re.sub(x, y, u'') should return u'', not '', and
  69. # re.sub(x, y, '') should return '', not u''.
  70. # Also:
  71. # re.sub(x, y, unicode(x)) should return unicode(y), and
  72. # re.sub(x, y, str(x)) should return
  73. # str(y) if isinstance(y, str) else unicode(y).
  74. for x in 'x', u'x':
  75. for y in 'y', u'y':
  76. z = re.sub(x, y, u'')
  77. self.assertEqual(z, u'')
  78. self.assertEqual(type(z), unicode)
  79. #
  80. z = re.sub(x, y, '')
  81. self.assertEqual(z, '')
  82. self.assertEqual(type(z), str)
  83. #
  84. z = re.sub(x, y, unicode(x))
  85. self.assertEqual(z, y)
  86. self.assertEqual(type(z), unicode)
  87. #
  88. z = re.sub(x, y, str(x))
  89. self.assertEqual(z, y)
  90. self.assertEqual(type(z), type(y))
  91. def test_bug_1661(self):
  92. # Verify that flags do not get silently ignored with compiled patterns
  93. pattern = re.compile('.')
  94. self.assertRaises(ValueError, re.match, pattern, 'A', re.I)
  95. self.assertRaises(ValueError, re.search, pattern, 'A', re.I)
  96. self.assertRaises(ValueError, re.findall, pattern, 'A', re.I)
  97. self.assertRaises(ValueError, re.compile, pattern, re.I)
  98. def test_bug_3629(self):
  99. # A regex that triggered a bug in the sre-code validator
  100. re.compile("(?P<quote>)(?(quote))")
  101. def test_sub_template_numeric_escape(self):
  102. # bug 776311 and friends
  103. self.assertEqual(re.sub('x', r'\0', 'x'), '\0')
  104. self.assertEqual(re.sub('x', r'\000', 'x'), '\000')
  105. self.assertEqual(re.sub('x', r'\001', 'x'), '\001')
  106. self.assertEqual(re.sub('x', r'\008', 'x'), '\0' + '8')
  107. self.assertEqual(re.sub('x', r'\009', 'x'), '\0' + '9')
  108. self.assertEqual(re.sub('x', r'\111', 'x'), '\111')
  109. self.assertEqual(re.sub('x', r'\117', 'x'), '\117')
  110. self.assertEqual(re.sub('x', r'\1111', 'x'), '\1111')
  111. self.assertEqual(re.sub('x', r'\1111', 'x'), '\111' + '1')
  112. self.assertEqual(re.sub('x', r'\00', 'x'), '\x00')
  113. self.assertEqual(re.sub('x', r'\07', 'x'), '\x07')
  114. self.assertEqual(re.sub('x', r'\08', 'x'), '\0' + '8')
  115. self.assertEqual(re.sub('x', r'\09', 'x'), '\0' + '9')
  116. self.assertEqual(re.sub('x', r'\0a', 'x'), '\0' + 'a')
  117. self.assertEqual(re.sub('x', r'\400', 'x'), '\0')
  118. self.assertEqual(re.sub('x', r'\777', 'x'), '\377')
  119. self.assertRaises(re.error, re.sub, 'x', r'\1', 'x')
  120. self.assertRaises(re.error, re.sub, 'x', r'\8', 'x')
  121. self.assertRaises(re.error, re.sub, 'x', r'\9', 'x')
  122. self.assertRaises(re.error, re.sub, 'x', r'\11', 'x')
  123. self.assertRaises(re.error, re.sub, 'x', r'\18', 'x')
  124. self.assertRaises(re.error, re.sub, 'x', r'\1a', 'x')
  125. self.assertRaises(re.error, re.sub, 'x', r'\90', 'x')
  126. self.assertRaises(re.error, re.sub, 'x', r'\99', 'x')
  127. self.assertRaises(re.error, re.sub, 'x', r'\118', 'x') # r'\11' + '8'
  128. self.assertRaises(re.error, re.sub, 'x', r'\11a', 'x')
  129. self.assertRaises(re.error, re.sub, 'x', r'\181', 'x') # r'\18' + '1'
  130. self.assertRaises(re.error, re.sub, 'x', r'\800', 'x') # r'\80' + '0'
  131. # in python2.3 (etc), these loop endlessly in sre_parser.py
  132. self.assertEqual(re.sub('(((((((((((x)))))))))))', r'\11', 'x'), 'x')
  133. self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\118', 'xyz'),
  134. 'xz8')
  135. self.assertEqual(re.sub('((((((((((y))))))))))(.)', r'\11a', 'xyz'),
  136. 'xza')
  137. def test_qualified_re_sub(self):
  138. self.assertEqual(re.sub('a', 'b', 'aaaaa'), 'bbbbb')
  139. self.assertEqual(re.sub('a', 'b', 'aaaaa', 1), 'baaaa')
  140. def test_bug_114660(self):
  141. self.assertEqual(re.sub(r'(\S)\s+(\S)', r'\1 \2', 'hello there'),
  142. 'hello there')
  143. def test_bug_462270(self):
  144. # Test for empty sub() behaviour, see SF bug #462270
  145. self.assertEqual(re.sub('x*', '-', 'abxd'), '-a-b-d-')
  146. self.assertEqual(re.sub('x+', '-', 'abxd'), 'ab-d')
  147. def test_symbolic_refs(self):
  148. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a', 'xx')
  149. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<', 'xx')
  150. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g', 'xx')
  151. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<a a>', 'xx')
  152. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<1a1>', 'xx')
  153. self.assertRaises(IndexError, re.sub, '(?P<a>x)', '\g<ab>', 'xx')
  154. self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\g<b>', 'xx')
  155. self.assertRaises(re.error, re.sub, '(?P<a>x)|(?P<b>y)', '\\2', 'xx')
  156. self.assertRaises(re.error, re.sub, '(?P<a>x)', '\g<-1>', 'xx')
  157. def test_re_subn(self):
  158. self.assertEqual(re.subn("(?i)b+", "x", "bbbb BBBB"), ('x x', 2))
  159. self.assertEqual(re.subn("b+", "x", "bbbb BBBB"), ('x BBBB', 1))
  160. self.assertEqual(re.subn("b+", "x", "xyz"), ('xyz', 0))
  161. self.assertEqual(re.subn("b*", "x", "xyz"), ('xxxyxzx', 4))
  162. self.assertEqual(re.subn("b*", "x", "xyz", 2), ('xxxyz', 2))
  163. def test_re_split(self):
  164. self.assertEqual(re.split(":", ":a:b::c"), ['', 'a', 'b', '', 'c'])
  165. self.assertEqual(re.split(":*", ":a:b::c"), ['', 'a', 'b', 'c'])
  166. self.assertEqual(re.split("(:*)", ":a:b::c"),
  167. ['', ':', 'a', ':', 'b', '::', 'c'])
  168. self.assertEqual(re.split("(?::*)", ":a:b::c"), ['', 'a', 'b', 'c'])
  169. self.assertEqual(re.split("(:)*", ":a:b::c"),
  170. ['', ':', 'a', ':', 'b', ':', 'c'])
  171. self.assertEqual(re.split("([b:]+)", ":a:b::c"),
  172. ['', ':', 'a', ':b::', 'c'])
  173. self.assertEqual(re.split("(b)|(:+)", ":a:b::c"),
  174. ['', None, ':', 'a', None, ':', '', 'b', None, '',
  175. None, '::', 'c'])
  176. self.assertEqual(re.split("(?:b)|(?::+)", ":a:b::c"),
  177. ['', 'a', '', '', 'c'])
  178. def test_qualified_re_split(self):
  179. self.assertEqual(re.split(":", ":a:b::c", 2), ['', 'a', 'b::c'])
  180. self.assertEqual(re.split(':', 'a:b:c:d', 2), ['a', 'b', 'c:d'])
  181. self.assertEqual(re.split("(:)", ":a:b::c", 2),
  182. ['', ':', 'a', ':', 'b::c'])
  183. self.assertEqual(re.split("(:*)", ":a:b::c", 2),
  184. ['', ':', 'a', ':', 'b::c'])
  185. def test_re_findall(self):
  186. self.assertEqual(re.findall(":+", "abc"), [])
  187. self.assertEqual(re.findall(":+", "a:b::c:::d"), [":", "::", ":::"])
  188. self.assertEqual(re.findall("(:+)", "a:b::c:::d"), [":", "::", ":::"])
  189. self.assertEqual(re.findall("(:)(:*)", "a:b::c:::d"), [(":", ""),
  190. (":", ":"),
  191. (":", "::")])
  192. def test_bug_117612(self):
  193. self.assertEqual(re.findall(r"(a|(b))", "aba"),
  194. [("a", ""),("b", "b"),("a", "")])
  195. def test_re_match(self):
  196. self.assertEqual(re.match('a', 'a').groups(), ())
  197. self.assertEqual(re.match('(a)', 'a').groups(), ('a',))
  198. self.assertEqual(re.match(r'(a)', 'a').group(0), 'a')
  199. self.assertEqual(re.match(r'(a)', 'a').group(1), 'a')
  200. self.assertEqual(re.match(r'(a)', 'a').group(1, 1), ('a', 'a'))
  201. pat = re.compile('((a)|(b))(c)?')
  202. self.assertEqual(pat.match('a').groups(), ('a', 'a', None, None))
  203. self.assertEqual(pat.match('b').groups(), ('b', None, 'b', None))
  204. self.assertEqual(pat.match('ac').groups(), ('a', 'a', None, 'c'))
  205. self.assertEqual(pat.match('bc').groups(), ('b', None, 'b', 'c'))
  206. self.assertEqual(pat.match('bc').groups(""), ('b', "", 'b', 'c'))
  207. # A single group
  208. m = re.match('(a)', 'a')
  209. self.assertEqual(m.group(0), 'a')
  210. self.assertEqual(m.group(0), 'a')
  211. self.assertEqual(m.group(1), 'a')
  212. self.assertEqual(m.group(1, 1), ('a', 'a'))
  213. pat = re.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
  214. self.assertEqual(pat.match('a').group(1, 2, 3), ('a', None, None))
  215. self.assertEqual(pat.match('b').group('a1', 'b2', 'c3'),
  216. (None, 'b', None))
  217. self.assertEqual(pat.match('ac').group(1, 'b2', 3), ('a', None, 'c'))
  218. def test_re_groupref_exists(self):
  219. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', '(a)').groups(),
  220. ('(', 'a'))
  221. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', 'a').groups(),
  222. (None, 'a'))
  223. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', 'a)'), None)
  224. self.assertEqual(re.match('^(\()?([^()]+)(?(1)\))$', '(a'), None)
  225. self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'ab').groups(),
  226. ('a', 'b'))
  227. self.assertEqual(re.match('^(?:(a)|c)((?(1)b|d))$', 'cd').groups(),
  228. (None, 'd'))
  229. self.assertEqual(re.match('^(?:(a)|c)((?(1)|d))$', 'cd').groups(),
  230. (None, 'd'))
  231. self.assertEqual(re.match('^(?:(a)|c)((?(1)|d))$', 'a').groups(),
  232. ('a', ''))
  233. # Tests for bug #1177831: exercise groups other than the first group
  234. p = re.compile('(?P<g1>a)(?P<g2>b)?((?(g2)c|d))')
  235. self.assertEqual(p.match('abc').groups(),
  236. ('a', 'b', 'c'))
  237. self.assertEqual(p.match('ad').groups(),
  238. ('a', None, 'd'))
  239. self.assertEqual(p.match('abd'), None)
  240. self.assertEqual(p.match('ac'), None)
  241. def test_re_groupref(self):
  242. self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', '|a|').groups(),
  243. ('|', 'a'))
  244. self.assertEqual(re.match(r'^(\|)?([^()]+)\1?$', 'a').groups(),
  245. (None, 'a'))
  246. self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', 'a|'), None)
  247. self.assertEqual(re.match(r'^(\|)?([^()]+)\1$', '|a'), None)
  248. self.assertEqual(re.match(r'^(?:(a)|c)(\1)$', 'aa').groups(),
  249. ('a', 'a'))
  250. self.assertEqual(re.match(r'^(?:(a)|c)(\1)?$', 'c').groups(),
  251. (None, None))
  252. def test_groupdict(self):
  253. self.assertEqual(re.match('(?P<first>first) (?P<second>second)',
  254. 'first second').groupdict(),
  255. {'first':'first', 'second':'second'})
  256. def test_expand(self):
  257. self.assertEqual(re.match("(?P<first>first) (?P<second>second)",
  258. "first second")
  259. .expand(r"\2 \1 \g<second> \g<first>"),
  260. "second first second first")
  261. def test_repeat_minmax(self):
  262. self.assertEqual(re.match("^(\w){1}$", "abc"), None)
  263. self.assertEqual(re.match("^(\w){1}?$", "abc"), None)
  264. self.assertEqual(re.match("^(\w){1,2}$", "abc"), None)
  265. self.assertEqual(re.match("^(\w){1,2}?$", "abc"), None)
  266. self.assertEqual(re.match("^(\w){3}$", "abc").group(1), "c")
  267. self.assertEqual(re.match("^(\w){1,3}$", "abc").group(1), "c")
  268. self.assertEqual(re.match("^(\w){1,4}$", "abc").group(1), "c")
  269. self.assertEqual(re.match("^(\w){3,4}?$", "abc").group(1), "c")
  270. self.assertEqual(re.match("^(\w){3}?$", "abc").group(1), "c")
  271. self.assertEqual(re.match("^(\w){1,3}?$", "abc").group(1), "c")
  272. self.assertEqual(re.match("^(\w){1,4}?$", "abc").group(1), "c")
  273. self.assertEqual(re.match("^(\w){3,4}?$", "abc").group(1), "c")
  274. self.assertEqual(re.match("^x{1}$", "xxx"), None)
  275. self.assertEqual(re.match("^x{1}?$", "xxx"), None)
  276. self.assertEqual(re.match("^x{1,2}$", "xxx"), None)
  277. self.assertEqual(re.match("^x{1,2}?$", "xxx"), None)
  278. self.assertNotEqual(re.match("^x{3}$", "xxx"), None)
  279. self.assertNotEqual(re.match("^x{1,3}$", "xxx"), None)
  280. self.assertNotEqual(re.match("^x{1,4}$", "xxx"), None)
  281. self.assertNotEqual(re.match("^x{3,4}?$", "xxx"), None)
  282. self.assertNotEqual(re.match("^x{3}?$", "xxx"), None)
  283. self.assertNotEqual(re.match("^x{1,3}?$", "xxx"), None)
  284. self.assertNotEqual(re.match("^x{1,4}?$", "xxx"), None)
  285. self.assertNotEqual(re.match("^x{3,4}?$", "xxx"), None)
  286. self.assertEqual(re.match("^x{}$", "xxx"), None)
  287. self.assertNotEqual(re.match("^x{}$", "x{}"), None)
  288. def test_getattr(self):
  289. self.assertEqual(re.match("(a)", "a").pos, 0)
  290. self.assertEqual(re.match("(a)", "a").endpos, 1)
  291. self.assertEqual(re.match("(a)", "a").string, "a")
  292. self.assertEqual(re.match("(a)", "a").regs, ((0, 1), (0, 1)))
  293. self.assertNotEqual(re.match("(a)", "a").re, None)
  294. def test_special_escapes(self):
  295. self.assertEqual(re.search(r"\b(b.)\b",
  296. "abcd abc bcd bx").group(1), "bx")
  297. self.assertEqual(re.search(r"\B(b.)\B",
  298. "abc bcd bc abxd").group(1), "bx")
  299. self.assertEqual(re.search(r"\b(b.)\b",
  300. "abcd abc bcd bx", re.LOCALE).group(1), "bx")
  301. self.assertEqual(re.search(r"\B(b.)\B",
  302. "abc bcd bc abxd", re.LOCALE).group(1), "bx")
  303. self.assertEqual(re.search(r"\b(b.)\b",
  304. "abcd abc bcd bx", re.UNICODE).group(1), "bx")
  305. self.assertEqual(re.search(r"\B(b.)\B",
  306. "abc bcd bc abxd", re.UNICODE).group(1), "bx")
  307. self.assertEqual(re.search(r"^abc$", "\nabc\n", re.M).group(0), "abc")
  308. self.assertEqual(re.search(r"^\Aabc\Z$", "abc", re.M).group(0), "abc")
  309. self.assertEqual(re.search(r"^\Aabc\Z$", "\nabc\n", re.M), None)
  310. self.assertEqual(re.search(r"\b(b.)\b",
  311. u"abcd abc bcd bx").group(1), "bx")
  312. self.assertEqual(re.search(r"\B(b.)\B",
  313. u"abc bcd bc abxd").group(1), "bx")
  314. self.assertEqual(re.search(r"^abc$", u"\nabc\n", re.M).group(0), "abc")
  315. self.assertEqual(re.search(r"^\Aabc\Z$", u"abc", re.M).group(0), "abc")
  316. self.assertEqual(re.search(r"^\Aabc\Z$", u"\nabc\n", re.M), None)
  317. self.assertEqual(re.search(r"\d\D\w\W\s\S",
  318. "1aa! a").group(0), "1aa! a")
  319. self.assertEqual(re.search(r"\d\D\w\W\s\S",
  320. "1aa! a", re.LOCALE).group(0), "1aa! a")
  321. self.assertEqual(re.search(r"\d\D\w\W\s\S",
  322. "1aa! a", re.UNICODE).group(0), "1aa! a")
  323. def test_bigcharset(self):
  324. self.assertEqual(re.match(u"([\u2222\u2223])",
  325. u"\u2222").group(1), u"\u2222")
  326. self.assertEqual(re.match(u"([\u2222\u2223])",
  327. u"\u2222", re.UNICODE).group(1), u"\u2222")
  328. def test_anyall(self):
  329. self.assertEqual(re.match("a.b", "a\nb", re.DOTALL).group(0),
  330. "a\nb")
  331. self.assertEqual(re.match("a.*b", "a\n\nb", re.DOTALL).group(0),
  332. "a\n\nb")
  333. def test_non_consuming(self):
  334. self.assertEqual(re.match("(a(?=\s[^a]))", "a b").group(1), "a")
  335. self.assertEqual(re.match("(a(?=\s[^a]*))", "a b").group(1), "a")
  336. self.assertEqual(re.match("(a(?=\s[abc]))", "a b").group(1), "a")
  337. self.assertEqual(re.match("(a(?=\s[abc]*))", "a bc").group(1), "a")
  338. self.assertEqual(re.match(r"(a)(?=\s\1)", "a a").group(1), "a")
  339. self.assertEqual(re.match(r"(a)(?=\s\1*)", "a aa").group(1), "a")
  340. self.assertEqual(re.match(r"(a)(?=\s(abc|a))", "a a").group(1), "a")
  341. self.assertEqual(re.match(r"(a(?!\s[^a]))", "a a").group(1), "a")
  342. self.assertEqual(re.match(r"(a(?!\s[abc]))", "a d").group(1), "a")
  343. self.assertEqual(re.match(r"(a)(?!\s\1)", "a b").group(1), "a")
  344. self.assertEqual(re.match(r"(a)(?!\s(abc|a))", "a b").group(1), "a")
  345. def test_ignore_case(self):
  346. self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
  347. self.assertEqual(re.match("abc", u"ABC", re.I).group(0), "ABC")
  348. self.assertEqual(re.match(r"(a\s[^a])", "a b", re.I).group(1), "a b")
  349. self.assertEqual(re.match(r"(a\s[^a]*)", "a bb", re.I).group(1), "a bb")
  350. self.assertEqual(re.match(r"(a\s[abc])", "a b", re.I).group(1), "a b")
  351. self.assertEqual(re.match(r"(a\s[abc]*)", "a bb", re.I).group(1), "a bb")
  352. self.assertEqual(re.match(r"((a)\s\2)", "a a", re.I).group(1), "a a")
  353. self.assertEqual(re.match(r"((a)\s\2*)", "a aa", re.I).group(1), "a aa")
  354. self.assertEqual(re.match(r"((a)\s(abc|a))", "a a", re.I).group(1), "a a")
  355. self.assertEqual(re.match(r"((a)\s(abc|a)*)", "a aa", re.I).group(1), "a aa")
  356. def test_category(self):
  357. self.assertEqual(re.match(r"(\s)", " ").group(1), " ")
  358. def test_getlower(self):
  359. import _sre
  360. self.assertEqual(_sre.getlower(ord('A'), 0), ord('a'))
  361. self.assertEqual(_sre.getlower(ord('A'), re.LOCALE), ord('a'))
  362. self.assertEqual(_sre.getlower(ord('A'), re.UNICODE), ord('a'))
  363. self.assertEqual(re.match("abc", "ABC", re.I).group(0), "ABC")
  364. self.assertEqual(re.match("abc", u"ABC", re.I).group(0), "ABC")
  365. def test_not_literal(self):
  366. self.assertEqual(re.search("\s([^a])", " b").group(1), "b")
  367. self.assertEqual(re.search("\s([^a]*)", " bb").group(1), "bb")
  368. def test_search_coverage(self):
  369. self.assertEqual(re.search("\s(b)", " b").group(1), "b")
  370. self.assertEqual(re.search("a\s", "a ").group(0), "a ")
  371. def test_re_escape(self):
  372. p=""
  373. # This had to change from the original test of range(0,256)
  374. # because we can't support non-ascii non-utf8 strings
  375. for i in range(0, 128):
  376. p = p + chr(i)
  377. self.assertEqual(re.match(re.escape(chr(i)), chr(i)) is not None,
  378. True)
  379. self.assertEqual(re.match(re.escape(chr(i)), chr(i)).span(), (0,1))
  380. pat=re.compile(re.escape(p))
  381. self.assertEqual(pat.match(p) is not None, True)
  382. self.assertEqual(pat.match(p).span(), (0,128))
  383. def test_pickling(self):
  384. import pickle
  385. self.pickle_test(pickle)
  386. import cPickle
  387. self.pickle_test(cPickle)
  388. # old pickles expect the _compile() reconstructor in sre module
  389. import_module("sre", deprecated=True)
  390. from sre import _compile
  391. def pickle_test(self, pickle):
  392. oldpat = re.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
  393. s = pickle.dumps(oldpat)
  394. newpat = pickle.loads(s)
  395. self.assertEqual(oldpat, newpat)
  396. def test_constants(self):
  397. self.assertEqual(re.I, re.IGNORECASE)
  398. self.assertEqual(re.L, re.LOCALE)
  399. self.assertEqual(re.M, re.MULTILINE)
  400. self.assertEqual(re.S, re.DOTALL)
  401. self.assertEqual(re.X, re.VERBOSE)
  402. def test_flags(self):
  403. for flag in [re.I, re.M, re.X, re.S, re.L]:
  404. self.assertNotEqual(re.compile('^pattern$', flag), None)
  405. def test_sre_character_literals(self):
  406. for i in [0, 8, 16, 32, 64, 127, 128, 255]:
  407. self.assertNotEqual(re.match(r"\%03o" % i, chr(i)), None)
  408. self.assertNotEqual(re.match(r"\%03o0" % i, chr(i)+"0"), None)
  409. self.assertNotEqual(re.match(r"\%03o8" % i, chr(i)+"8"), None)
  410. self.assertNotEqual(re.match(r"\x%02x" % i, chr(i)), None)
  411. self.assertNotEqual(re.match(r"\x%02x0" % i, chr(i)+"0"), None)
  412. self.assertNotEqual(re.match(r"\x%02xz" % i, chr(i)+"z"), None)
  413. self.assertRaises(re.error, re.match, "\911", "")
  414. def test_sre_character_class_literals(self):
  415. for i in [0, 8, 16, 32, 64, 127, 128, 255]:
  416. self.assertNotEqual(re.match(r"[\%03o]" % i, chr(i)), None)
  417. self.assertNotEqual(re.match(r"[\%03o0]" % i, chr(i)), None)
  418. self.assertNotEqual(re.match(r"[\%03o8]" % i, chr(i)), None)
  419. self.assertNotEqual(re.match(r"[\x%02x]" % i, chr(i)), None)
  420. self.assertNotEqual(re.match(r"[\x%02x0]" % i, chr(i)), None)
  421. self.assertNotEqual(re.match(r"[\x%02xz]" % i, chr(i)), None)
  422. self.assertRaises(re.error, re.match, "[\911]", "")
  423. def test_bug_113254(self):
  424. self.assertEqual(re.match(r'(a)|(b)', 'b').start(1), -1)
  425. self.assertEqual(re.match(r'(a)|(b)', 'b').end(1), -1)
  426. self.assertEqual(re.match(r'(a)|(b)', 'b').span(1), (-1, -1))
  427. def test_bug_527371(self):
  428. # bug described in patches 527371/672491
  429. self.assertEqual(re.match(r'(a)?a','a').lastindex, None)
  430. self.assertEqual(re.match(r'(a)(b)?b','ab').lastindex, 1)
  431. self.assertEqual(re.match(r'(?P<a>a)(?P<b>b)?b','ab').lastgroup, 'a')
  432. self.assertEqual(re.match("(?P<a>a(b))", "ab").lastgroup, 'a')
  433. self.assertEqual(re.match("((a))", "a").lastindex, 1)
  434. def test_bug_545855(self):
  435. # bug 545855 -- This pattern failed to cause a compile error as it
  436. # should, instead provoking a TypeError.
  437. self.assertRaises(re.error, re.compile, 'foo[a-')
  438. def test_bug_418626(self):
  439. # bugs 418626 at al. -- Testing Greg Chapman's addition of op code
  440. # SRE_OP_MIN_REPEAT_ONE for eliminating recursion on simple uses of
  441. # pattern '*?' on a long string.
  442. self.assertEqual(re.match('.*?c', 10000*'ab'+'cd').end(0), 20001)
  443. self.assertEqual(re.match('.*?cd', 5000*'ab'+'c'+5000*'ab'+'cde').end(0),
  444. 20003)
  445. self.assertEqual(re.match('.*?cd', 20000*'abc'+'de').end(0), 60001)
  446. # non-simple '*?' still used to hit the recursion limit, before the
  447. # non-recursive scheme was implemented.
  448. self.assertEqual(re.search('(a|b)*?c', 10000*'ab'+'cd').end(0), 20001)
  449. def test_bug_612074(self):
  450. pat=u"["+re.escape(u"\u2039")+u"]"
  451. self.assertEqual(re.compile(pat) and 1, 1)
  452. def test_stack_overflow(self):
  453. # nasty cases that used to overflow the straightforward recursive
  454. # implementation of repeated groups.
  455. self.assertEqual(re.match('(x)*', 50000*'x').group(1), 'x')
  456. self.assertEqual(re.match('(x)*y', 50000*'x'+'y').group(1), 'x')
  457. self.assertEqual(re.match('(x)*?y', 50000*'x'+'y').group(1), 'x')
  458. def test_scanner(self):
  459. def s_ident(scanner, token): return token
  460. def s_operator(scanner, token): return "op%s" % token
  461. def s_float(scanner, token): return float(token)
  462. def s_int(scanner, token): return int(token)
  463. scanner = Scanner([
  464. (r"[a-zA-Z_]\w*", s_ident),
  465. (r"\d+\.\d*", s_float),
  466. (r"\d+", s_int),
  467. (r"=|\+|-|\*|/", s_operator),
  468. (r"\s+", None),
  469. ])
  470. self.assertNotEqual(scanner.scanner.scanner("").pattern, None)
  471. self.assertEqual(scanner.scan("sum = 3*foo + 312.50 + bar"),
  472. (['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5,
  473. 'op+', 'bar'], ''))
  474. def test_bug_448951(self):
  475. # bug 448951 (similar to 429357, but with single char match)
  476. # (Also test greedy matches.)
  477. for op in '','?','*':
  478. self.assertEqual(re.match(r'((.%s):)?z'%op, 'z').groups(),
  479. (None, None))
  480. self.assertEqual(re.match(r'((.%s):)?z'%op, 'a:z').groups(),
  481. ('a:', 'a'))
  482. def test_bug_725106(self):
  483. # capturing groups in alternatives in repeats
  484. self.assertEqual(re.match('^((a)|b)*', 'abc').groups(),
  485. ('b', 'a'))
  486. self.assertEqual(re.match('^(([ab])|c)*', 'abc').groups(),
  487. ('c', 'b'))
  488. self.assertEqual(re.match('^((d)|[ab])*', 'abc').groups(),
  489. ('b', None))
  490. self.assertEqual(re.match('^((a)c|[ab])*', 'abc').groups(),
  491. ('b', None))
  492. self.assertEqual(re.match('^((a)|b)*?c', 'abc').groups(),
  493. ('b', 'a'))
  494. self.assertEqual(re.match('^(([ab])|c)*?d', 'abcd').groups(),
  495. ('c', 'b'))
  496. self.assertEqual(re.match('^((d)|[ab])*?c', 'abc').groups(),
  497. ('b', None))
  498. self.assertEqual(re.match('^((a)c|[ab])*?c', 'abc').groups(),
  499. ('b', None))
  500. def test_bug_725149(self):
  501. # mark_stack_base restoring before restoring marks
  502. self.assertEqual(re.match('(a)(?:(?=(b)*)c)*', 'abb').groups(),
  503. ('a', None))
  504. self.assertEqual(re.match('(a)((?!(b)*))*', 'abb').groups(),
  505. ('a', None, None))
  506. def test_bug_764548(self):
  507. # bug 764548, re.compile() barfs on str/unicode subclasses
  508. try:
  509. unicode
  510. except NameError:
  511. return # no problem if we have no unicode
  512. class my_unicode(unicode): pass
  513. pat = re.compile(my_unicode("abc"))
  514. self.assertEqual(pat.match("xyz"), None)
  515. def test_finditer(self):
  516. iter = re.finditer(r":+", "a:b::c:::d")
  517. self.assertEqual([item.group(0) for item in iter],
  518. [":", "::", ":::"])
  519. def test_bug_926075(self):
  520. try:
  521. unicode
  522. except NameError:
  523. return # no problem if we have no unicode
  524. self.assert_(re.compile('bug_926075') is not
  525. re.compile(eval("u'bug_926075'")))
  526. def test_bug_931848(self):
  527. try:
  528. unicode
  529. except NameError:
  530. pass
  531. pattern = eval('u"[\u002E\u3002\uFF0E\uFF61]"')
  532. self.assertEqual(re.compile(pattern).split("a.b.c"),
  533. ['a','b','c'])
  534. def test_bug_581080(self):
  535. iter = re.finditer(r"\s", "a b")
  536. self.assertEqual(iter.next().span(), (1,2))
  537. self.assertRaises(StopIteration, iter.next)
  538. scanner = re.compile(r"\s").scanner("a b")
  539. self.assertEqual(scanner.search().span(), (1, 2))
  540. self.assertEqual(scanner.search(), None)
  541. def test_bug_817234(self):
  542. iter = re.finditer(r".*", "asdf")
  543. self.assertEqual(iter.next().span(), (0, 4))
  544. self.assertEqual(iter.next().span(), (4, 4))
  545. self.assertRaises(StopIteration, iter.next)
  546. def test_empty_array(self):
  547. # SF buf 1647541
  548. import array
  549. for typecode in 'cbBuhHiIlLfd':
  550. a = array.array(typecode)
  551. self.assertEqual(re.compile("bla").match(a), None)
  552. self.assertEqual(re.compile("").match(a).groups(), ())
  553. def test_inline_flags(self):
  554. # Bug #1700
  555. upper_char = unichr(0x1ea0) # Latin Capital Letter A with Dot Bellow
  556. lower_char = unichr(0x1ea1) # Latin Small Letter A with Dot Bellow
  557. p = re.compile(upper_char, re.I | re.U)
  558. q = p.match(lower_char)
  559. self.assertNotEqual(q, None)
  560. p = re.compile(lower_char, re.I | re.U)
  561. q = p.match(upper_char)
  562. self.assertNotEqual(q, None)
  563. p = re.compile('(?i)' + upper_char, re.U)
  564. q = p.match(lower_char)
  565. self.assertNotEqual(q, None)
  566. p = re.compile('(?i)' + lower_char, re.U)
  567. q = p.match(upper_char)
  568. self.assertNotEqual(q, None)
  569. p = re.compile('(?iu)' + upper_char)
  570. q = p.match(lower_char)
  571. self.assertNotEqual(q, None)
  572. p = re.compile('(?iu)' + lower_char)
  573. q = p.match(upper_char)
  574. self.assertNotEqual(q, None)
  575. def test_dollar_matches_twice(self):
  576. "$ matches the end of string, and just before the terminating \n"
  577. pattern = re.compile('$')
  578. self.assertEqual(pattern.sub('#', 'a\nb\n'), 'a\nb#\n#')
  579. self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a\nb\nc#')
  580. self.assertEqual(pattern.sub('#', '\n'), '#\n#')
  581. pattern = re.compile('$', re.MULTILINE)
  582. self.assertEqual(pattern.sub('#', 'a\nb\n' ), 'a#\nb#\n#' )
  583. self.assertEqual(pattern.sub('#', 'a\nb\nc'), 'a#\nb#\nc#')
  584. self.assertEqual(pattern.sub('#', '\n'), '#\n#')
  585. def test_dealloc(self):
  586. # issue 3299: check for segfault in debug build
  587. import _sre
  588. # the overflow limit is different on wide and narrow builds and it
  589. # depends on the definition of SRE_CODE (see sre.h).
  590. # 2**128 should be big enough to overflow on both. For smaller values
  591. # a RuntimeError is raised instead of OverflowError.
  592. long_overflow = 2**128
  593. self.assertRaises(TypeError, re.finditer, "a", {})
  594. self.assertRaises(OverflowError, _sre.compile, "abc", 0, [long_overflow])
  595. def run_re_tests():
  596. from re_tests import benchmarks, tests, SUCCEED, FAIL, SYNTAX_ERROR
  597. if verbose:
  598. print 'Running re_tests test suite'
  599. else:
  600. # To save time, only run the first and last 10 tests
  601. #tests = tests[:10] + tests[-10:]
  602. pass
  603. for t in tests:
  604. sys.stdout.flush()
  605. pattern = s = outcome = repl = expected = None
  606. if len(t) == 5:
  607. pattern, s, outcome, repl, expected = t
  608. elif len(t) == 3:
  609. pattern, s, outcome = t
  610. else:
  611. raise ValueError, ('Test tuples should have 3 or 5 fields', t)
  612. try:
  613. obj = re.compile(pattern)
  614. except re.error:
  615. if outcome == SYNTAX_ERROR: pass # Expected a syntax error
  616. else:
  617. print '=== Syntax error:', t
  618. except KeyboardInterrupt: raise KeyboardInterrupt
  619. except:
  620. print '*** Unexpected error ***', t
  621. if verbose:
  622. traceback.print_exc(file=sys.stdout)
  623. else:
  624. try:
  625. result = obj.search(s)
  626. except re.error, msg:
  627. print '=== Unexpected exception', t, repr(msg)
  628. if outcome == SYNTAX_ERROR:
  629. # This should have been a syntax error; forget it.
  630. pass
  631. elif outcome == FAIL:
  632. if result is None: pass # No match, as expected
  633. else: print '=== Succeeded incorrectly', t
  634. elif outcome == SUCCEED:
  635. if result is not None:
  636. # Matched, as expected, so now we compute the
  637. # result string and compare it to our expected result.
  638. start, end = result.span(0)
  639. vardict={'found': result.group(0),
  640. 'groups': result.group(),
  641. 'flags': result.re.flags}
  642. for i in range(1, 100):
  643. try:
  644. gi = result.group(i)
  645. # Special hack because else the string concat fails:
  646. if gi is None:
  647. gi = "None"
  648. except IndexError:
  649. gi = "Error"
  650. vardict['g%d' % i] = gi
  651. for i in result.re.groupindex.keys():
  652. try:
  653. gi = result.group(i)
  654. if gi is None:
  655. gi = "None"
  656. except IndexError:
  657. gi = "Error"
  658. vardict[i] = gi
  659. repl = eval(repl, vardict)
  660. if repl != expected:
  661. print '=== grouping error', t,
  662. print repr(repl) + ' should be ' + repr(expected)
  663. else:
  664. print '=== Failed incorrectly', t
  665. # Try the match on a unicode string, and check that it
  666. # still succeeds.
  667. try:
  668. result = obj.search(unicode(s, "latin-1"))
  669. if result is None:
  670. print '=== Fails on unicode match', t
  671. except NameError:
  672. continue # 1.5.2
  673. except TypeError:
  674. continue # unicode test case
  675. # Try the match on a unicode pattern, and check that it
  676. # still succeeds.
  677. obj=re.compile(unicode(pattern, "latin-1"))
  678. result = obj.search(s)
  679. if result is None:
  680. print '=== Fails on unicode pattern match', t
  681. # Try the match with the search area limited to the extent
  682. # of the match and see if it still succeeds. \B will
  683. # break (because it won't match at the end or start of a
  684. # string), so we'll ignore patterns that feature it.
  685. if pattern[:2] != '\\B' and pattern[-2:] != '\\B' \
  686. and result is not None:
  687. obj = re.compile(pattern)
  688. result = obj.search(s, result.start(0), result.end(0) + 1)
  689. if result is None:
  690. print '=== Failed on range-limited match', t
  691. # Try the match with IGNORECASE enabled, and check that it
  692. # still succeeds.
  693. obj = re.compile(pattern, re.IGNORECASE)
  694. result = obj.search(s)
  695. if result is None:
  696. print '=== Fails on case-insensitive match', t
  697. # Try the match with LOCALE enabled, and check that it
  698. # still succeeds.
  699. obj = re.compile(pattern, re.LOCALE)
  700. result = obj.search(s)
  701. if result is None:
  702. print '=== Fails on locale-sensitive match', t
  703. # Try the match with UNICODE locale enabled, and check
  704. # that it still succeeds.
  705. obj = re.compile(pattern, re.UNICODE)
  706. result = obj.search(s)
  707. if result is None:
  708. print '=== Fails on unicode-sensitive match', t
  709. def test_main():
  710. run_unittest(ReTests)
  711. run_re_tests()
  712. if __name__ == "__main__":
  713. test_main()