PageRenderTime 56ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

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

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