PageRenderTime 56ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/IronPython_Main/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/test/test_re.py

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