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

/pypy/module/_sre/test/test_app_sre.py

https://bitbucket.org/squeaky/pypy
Python | 990 lines | 975 code | 3 blank | 12 comment | 1 complexity | e79f00df0ec15068f56ebc193543a5ce MD5 | raw file
Possible License(s): Apache-2.0
  1. """Regular expression tests specific to _sre.py and accumulated during TDD."""
  2. import os
  3. import py
  4. from py.test import raises, skip
  5. from pypy.interpreter.gateway import app2interp_temp
  6. def init_app_test(cls, space):
  7. cls.w_s = space.appexec(
  8. [space.wrap(os.path.realpath(os.path.dirname(__file__)))],
  9. """(this_dir):
  10. import sys
  11. # Uh-oh, ugly hack
  12. sys.path.insert(0, this_dir)
  13. try:
  14. import support_test_app_sre
  15. return support_test_app_sre
  16. finally:
  17. sys.path.pop(0)
  18. """)
  19. class AppTestSrePy:
  20. def test_magic(self):
  21. import _sre, sre_constants
  22. assert sre_constants.MAGIC == _sre.MAGIC
  23. def test_codesize(self):
  24. import _sre
  25. assert _sre.getcodesize() == _sre.CODESIZE
  26. class AppTestSrePattern:
  27. def setup_class(cls):
  28. # This imports support_test_sre as the global "s"
  29. init_app_test(cls, cls.space)
  30. def test_copy(self):
  31. # copy support is disabled by default in _sre.c
  32. import re
  33. p = re.compile("b")
  34. raises(TypeError, p.__copy__) # p.__copy__() should raise
  35. raises(TypeError, p.__deepcopy__) # p.__deepcopy__() should raise
  36. def test_creation_attributes(self):
  37. import re
  38. pattern_string = "(b)l(?P<g>a)"
  39. p = re.compile(pattern_string, re.I | re.M)
  40. assert pattern_string == p.pattern
  41. assert re.I | re.M == p.flags
  42. assert 2 == p.groups
  43. assert {"g": 2} == p.groupindex
  44. def test_repeat_minmax_overflow(self):
  45. import re
  46. string = "x" * 100000
  47. assert re.match(r".{%d}" % (self.s.MAXREPEAT - 1), string) is None
  48. assert re.match(r".{,%d}" % (self.s.MAXREPEAT - 1), string).span() == (0, 100000)
  49. assert re.match(r".{%d,}?" % (self.s.MAXREPEAT - 1), string) is None
  50. raises(OverflowError, re.compile, r".{%d}" % self.s.MAXREPEAT)
  51. raises(OverflowError, re.compile, r".{,%d}" % self.s.MAXREPEAT)
  52. raises(OverflowError, re.compile, r".{%d,}?" % self.s.MAXREPEAT)
  53. def test_match_none(self):
  54. import re
  55. p = re.compile("bla")
  56. none_matches = ["b", "bl", "blub", "jupidu"]
  57. for string in none_matches:
  58. assert None == p.match(string)
  59. def test_pos_endpos(self):
  60. import re
  61. # XXX maybe fancier tests here
  62. p = re.compile("bl(a)")
  63. tests = [("abla", 0, 4), ("abla", 1, 4), ("ablaa", 1, 4)]
  64. for string, pos, endpos in tests:
  65. assert p.search(string, pos, endpos)
  66. tests = [("abla", 0, 3), ("abla", 2, 4)]
  67. for string, pos, endpos in tests:
  68. assert not p.search(string, pos, endpos)
  69. def test_findall(self):
  70. import re
  71. assert ["b"] == re.findall("b", "bla")
  72. assert ["a", "u"] == re.findall("b(.)", "abalbus")
  73. assert [("a", "l"), ("u", "s")] == re.findall("b(.)(.)", "abalbus")
  74. assert [("a", ""), ("s", "s")] == re.findall("b(a|(s))", "babs")
  75. def test_finditer(self):
  76. import re
  77. it = re.finditer("b(.)", "brabbel")
  78. assert "br" == it.next().group(0)
  79. assert "bb" == it.next().group(0)
  80. raises(StopIteration, it.next)
  81. def test_split(self):
  82. import re
  83. assert ["a", "o", "u", ""] == re.split("b", "abobub")
  84. assert ["a", "o", "ub"] == re.split("b", "abobub", 2)
  85. assert ['', 'a', 'l', 'a', 'lla'] == re.split("b(a)", "balballa")
  86. assert ['', 'a', None, 'l', 'u', None, 'lla'] == (
  87. re.split("b([ua]|(s))", "balbulla"))
  88. def test_weakref(self):
  89. import re, _weakref
  90. _weakref.ref(re.compile(r""))
  91. class AppTestSreMatch:
  92. spaceconfig = dict(usemodules=('array', ))
  93. def test_copy(self):
  94. import re
  95. # copy support is disabled by default in _sre.c
  96. m = re.match("bla", "bla")
  97. raises(TypeError, m.__copy__)
  98. raises(TypeError, m.__deepcopy__)
  99. def test_match_attributes(self):
  100. import re
  101. c = re.compile("bla")
  102. m = c.match("blastring")
  103. assert "blastring" == m.string
  104. assert c == m.re
  105. assert 0 == m.pos
  106. assert 9 == m.endpos
  107. assert None == m.lastindex
  108. assert None == m.lastgroup
  109. assert ((0, 3),) == m.regs
  110. def test_match_attributes_with_groups(self):
  111. import re
  112. m = re.search("a(b)(?P<name>c)", "aabcd")
  113. assert 0 == m.pos
  114. assert 5 == m.endpos
  115. assert 2 == m.lastindex
  116. assert "name" == m.lastgroup
  117. assert ((1, 4), (2, 3), (3, 4)) == m.regs
  118. def test_regs_overlapping_groups(self):
  119. import re
  120. m = re.match("a((b)c)", "abc")
  121. assert ((0, 3), (1, 3), (1, 2)) == m.regs
  122. def test_start_end_span(self):
  123. import re
  124. m = re.search("a((b)c)", "aabcd")
  125. assert (1, 4) == (m.start(), m.end())
  126. assert (1, 4) == m.span()
  127. assert (2, 4) == (m.start(1), m.end(1))
  128. assert (2, 4) == m.span(1)
  129. assert (2, 3) == (m.start(2), m.end(2))
  130. assert (2, 3) == m.span(2)
  131. raises(IndexError, m.start, 3)
  132. raises(IndexError, m.end, 3)
  133. raises(IndexError, m.span, 3)
  134. raises(IndexError, m.start, -1)
  135. def test_groups(self):
  136. import re
  137. m = re.search("a((.).)", "aabcd")
  138. assert ("ab", "a") == m.groups()
  139. assert ("ab", "a") == m.groups(True)
  140. m = re.search("a((\d)|(\s))", "aa1b")
  141. assert ("1", "1", None) == m.groups()
  142. assert ("1", "1", True) == m.groups(True)
  143. m = re.search("a((\d)|(\s))", "a ")
  144. assert (" ", None, " ") == m.groups()
  145. m = re.match("(a)", "a")
  146. assert ("a",) == m.groups()
  147. def test_groupdict(self):
  148. import re
  149. m = re.search("a((.).)", "aabcd")
  150. assert {} == m.groupdict()
  151. m = re.search("a((?P<first>.).)", "aabcd")
  152. assert {"first": "a"} == m.groupdict()
  153. m = re.search("a((?P<first>\d)|(?P<second>\s))", "aa1b")
  154. assert {"first": "1", "second": None} == m.groupdict()
  155. assert {"first": "1", "second": True} == m.groupdict(True)
  156. def test_group(self):
  157. import re
  158. m = re.search("a((?P<first>\d)|(?P<second>\s))", "aa1b")
  159. assert "a1" == m.group()
  160. assert ("1", "1", None) == m.group(1, 2, 3)
  161. assert ("1", None) == m.group("first", "second")
  162. raises(IndexError, m.group, 1, 4)
  163. assert ("1", None) == m.group(1, "second")
  164. raises(IndexError, m.group, 'foobarbaz')
  165. raises(IndexError, m.group, 'first', 'foobarbaz')
  166. def test_expand(self):
  167. import re
  168. m = re.search("a(..)(?P<name>..)", "ab1bc")
  169. assert "b1bcbc" == m.expand(r"\1\g<name>\2")
  170. def test_sub(self):
  171. import re
  172. assert "bbbbb" == re.sub("a", "b", "ababa")
  173. assert ("bbbbb", 3) == re.subn("a", "b", "ababa")
  174. assert "dddd" == re.sub("[abc]", "d", "abcd")
  175. assert ("dddd", 3) == re.subn("[abc]", "d", "abcd")
  176. assert "rbd\nbr\n" == re.sub("a(.)", r"b\1\n", "radar")
  177. assert ("rbd\nbr\n", 2) == re.subn("a(.)", r"b\1\n", "radar")
  178. assert ("bbbba", 2) == re.subn("a", "b", "ababa", 2)
  179. def test_sub_unicode(self):
  180. import re
  181. assert isinstance(re.sub(u"a", u"b", u""), unicode)
  182. # the input is returned unmodified if no substitution is performed,
  183. # which (if interpreted literally, as CPython does) gives the
  184. # following strangeish rules:
  185. assert isinstance(re.sub(u"a", u"b", "diwoiioamoi"), unicode)
  186. assert isinstance(re.sub(u"a", u"b", "diwoiiobmoi"), str)
  187. assert isinstance(re.sub(u'x', 'y', 'x'), str)
  188. def test_sub_callable(self):
  189. import re
  190. def call_me(match):
  191. ret = ""
  192. for char in match.group():
  193. ret += chr(ord(char) + 1)
  194. return ret
  195. assert ("bbbbb", 3) == re.subn("a", call_me, "ababa")
  196. def test_sub_callable_returns_none(self):
  197. import re
  198. def call_me(match):
  199. return None
  200. assert "acd" == re.sub("b", call_me, "abcd")
  201. def test_sub_callable_suddenly_unicode(self):
  202. import re
  203. def call_me(match):
  204. if match.group() == 'A':
  205. return unichr(0x3039)
  206. return ''
  207. assert (u"bb\u3039b", 2) == re.subn("[aA]", call_me, "babAb")
  208. def test_sub_subclass_of_str(self):
  209. import re
  210. class MyString(str):
  211. pass
  212. class MyUnicode(unicode):
  213. pass
  214. s1 = MyString('zz')
  215. s2 = re.sub('aa', 'bb', s1)
  216. assert s2 == s1
  217. assert type(s2) is str # and not MyString
  218. s2 = re.sub(u'aa', u'bb', s1)
  219. assert s2 == s1
  220. assert type(s2) is str # and not MyString
  221. u1 = MyUnicode(u'zz')
  222. u2 = re.sub(u'aa', u'bb', u1)
  223. assert u2 == u1
  224. assert type(u2) is unicode # and not MyUnicode
  225. def test_sub_bug(self):
  226. import re
  227. assert re.sub('=\w{2}', 'x', '=CA') == 'x'
  228. def test_match_array(self):
  229. import re, array
  230. a = array.array('c', 'hello')
  231. m = re.match('hel+', a)
  232. assert m.end() == 4
  233. def test_match_typeerror(self):
  234. import re
  235. raises(TypeError, re.match, 'hel+', list('hello'))
  236. def test_group_bugs(self):
  237. import re
  238. r = re.compile(r"""
  239. \&(?:
  240. (?P<escaped>\&) |
  241. (?P<named>[_a-z][_a-z0-9]*) |
  242. {(?P<braced>[_a-z][_a-z0-9]*)} |
  243. (?P<invalid>)
  244. )
  245. """, re.IGNORECASE | re.VERBOSE)
  246. matches = list(r.finditer('this &gift is for &{who} &&'))
  247. assert len(matches) == 3
  248. assert matches[0].groupdict() == {'escaped': None,
  249. 'named': 'gift',
  250. 'braced': None,
  251. 'invalid': None}
  252. assert matches[1].groupdict() == {'escaped': None,
  253. 'named': None,
  254. 'braced': 'who',
  255. 'invalid': None}
  256. assert matches[2].groupdict() == {'escaped': '&',
  257. 'named': None,
  258. 'braced': None,
  259. 'invalid': None}
  260. matches = list(r.finditer('&who likes &{what)')) # note the ')'
  261. assert len(matches) == 2
  262. assert matches[0].groupdict() == {'escaped': None,
  263. 'named': 'who',
  264. 'braced': None,
  265. 'invalid': None}
  266. assert matches[1].groupdict() == {'escaped': None,
  267. 'named': None,
  268. 'braced': None,
  269. 'invalid': ''}
  270. def test_sub_typecheck(self):
  271. import re
  272. KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
  273. raises(TypeError, KEYCRE.sub, "hello", {"%(": 1})
  274. class AppTestSreScanner:
  275. def test_scanner_attributes(self):
  276. import re
  277. p = re.compile("bla")
  278. s = p.scanner("blablubla")
  279. assert p == s.pattern
  280. def test_scanner_match(self):
  281. import re
  282. p = re.compile(".").scanner("bla")
  283. assert ("b", "l", "a") == (p.match().group(0),
  284. p.match().group(0), p.match().group(0))
  285. assert None == p.match()
  286. def test_scanner_match_detail(self):
  287. import re
  288. p = re.compile("a").scanner("aaXaa")
  289. assert "a" == p.match().group(0)
  290. assert "a" == p.match().group(0)
  291. assert None == p.match()
  292. assert "a" == p.match().group(0)
  293. assert "a" == p.match().group(0)
  294. assert None == p.match()
  295. assert None == p.match()
  296. assert None == p.match()
  297. def test_scanner_search(self):
  298. import re
  299. p = re.compile("\d").scanner("bla23c5a")
  300. assert ("2", "3", "5") == (p.search().group(0),
  301. p.search().group(0), p.search().group(0))
  302. assert None == p.search()
  303. def test_scanner_zero_width_match(self):
  304. import re, sys
  305. if sys.version_info[:2] == (2, 3):
  306. skip("2.3 is different here")
  307. p = re.compile(".*").scanner("bla")
  308. assert ("bla", "") == (p.search().group(0), p.search().group(0))
  309. assert None == p.search()
  310. class AppTestGetlower:
  311. spaceconfig = dict(usemodules=('_locale',))
  312. def setup_class(cls):
  313. # This imports support_test_sre as the global "s"
  314. init_app_test(cls, cls.space)
  315. def setup_method(self, method):
  316. import locale
  317. locale.setlocale(locale.LC_ALL, (None, None))
  318. def teardown_method(self, method):
  319. import locale
  320. locale.setlocale(locale.LC_ALL, (None, None))
  321. def test_getlower_no_flags(self):
  322. s = self.s
  323. UPPER_AE = "\xc4"
  324. s.assert_lower_equal([("a", "a"), ("A", "a"), (UPPER_AE, UPPER_AE),
  325. (u"\u00c4", u"\u00c4"), (u"\u4444", u"\u4444")], 0)
  326. def test_getlower_locale(self):
  327. s = self.s
  328. import locale, sre_constants
  329. UPPER_AE = "\xc4"
  330. LOWER_AE = "\xe4"
  331. UPPER_PI = u"\u03a0"
  332. try:
  333. locale.setlocale(locale.LC_ALL, "de_DE")
  334. s.assert_lower_equal([("a", "a"), ("A", "a"), (UPPER_AE, LOWER_AE),
  335. (u"\u00c4", u"\u00e4"), (UPPER_PI, UPPER_PI)],
  336. sre_constants.SRE_FLAG_LOCALE)
  337. except locale.Error:
  338. # skip test
  339. skip("unsupported locale de_DE")
  340. def test_getlower_unicode(self):
  341. s = self.s
  342. import sre_constants
  343. UPPER_AE = "\xc4"
  344. LOWER_AE = "\xe4"
  345. UPPER_PI = u"\u03a0"
  346. LOWER_PI = u"\u03c0"
  347. s.assert_lower_equal([("a", "a"), ("A", "a"), (UPPER_AE, LOWER_AE),
  348. (u"\u00c4", u"\u00e4"), (UPPER_PI, LOWER_PI),
  349. (u"\u4444", u"\u4444")], sre_constants.SRE_FLAG_UNICODE)
  350. class AppTestSimpleSearches:
  351. def test_search_simple_literal(self):
  352. import re
  353. assert re.search("bla", "bla")
  354. assert re.search("bla", "blab")
  355. assert not re.search("bla", "blu")
  356. def test_search_simple_ats(self):
  357. import re
  358. assert re.search("^bla", "bla")
  359. assert re.search("^bla", "blab")
  360. assert not re.search("^bla", "bbla")
  361. assert re.search("bla$", "abla")
  362. assert re.search("bla$", "bla\n")
  363. assert not re.search("bla$", "blaa")
  364. def test_search_simple_boundaries(self):
  365. import re
  366. UPPER_PI = u"\u03a0"
  367. assert re.search(r"bla\b", "bla")
  368. assert re.search(r"bla\b", "bla ja")
  369. assert re.search(r"bla\b", u"bla%s" % UPPER_PI)
  370. assert not re.search(r"bla\b", "blano")
  371. assert not re.search(r"bla\b", u"bla%s" % UPPER_PI, re.UNICODE)
  372. def test_search_simple_categories(self):
  373. import re
  374. LOWER_PI = u"\u03c0"
  375. INDIAN_DIGIT = u"\u0966"
  376. EM_SPACE = u"\u2001"
  377. LOWER_AE = "\xe4"
  378. assert re.search(r"bla\d\s\w", "bla3 b")
  379. assert re.search(r"b\d", u"b%s" % INDIAN_DIGIT, re.UNICODE)
  380. assert not re.search(r"b\D", u"b%s" % INDIAN_DIGIT, re.UNICODE)
  381. assert re.search(r"b\s", u"b%s" % EM_SPACE, re.UNICODE)
  382. assert not re.search(r"b\S", u"b%s" % EM_SPACE, re.UNICODE)
  383. assert re.search(r"b\w", u"b%s" % LOWER_PI, re.UNICODE)
  384. assert not re.search(r"b\W", u"b%s" % LOWER_PI, re.UNICODE)
  385. assert re.search(r"b\w", "b%s" % LOWER_AE, re.UNICODE)
  386. def test_search_simple_any(self):
  387. import re
  388. assert re.search(r"b..a", "jboaas")
  389. assert not re.search(r"b..a", "jbo\nas")
  390. assert re.search(r"b..a", "jbo\nas", re.DOTALL)
  391. def test_search_simple_in(self):
  392. import re
  393. UPPER_PI = u"\u03a0"
  394. LOWER_PI = u"\u03c0"
  395. EM_SPACE = u"\u2001"
  396. LINE_SEP = u"\u2028"
  397. assert re.search(r"b[\da-z]a", "bb1a")
  398. assert re.search(r"b[\da-z]a", "bbsa")
  399. assert not re.search(r"b[\da-z]a", "bbSa")
  400. assert re.search(r"b[^okd]a", "bsa")
  401. assert not re.search(r"b[^okd]a", "bda")
  402. assert re.search(u"b[%s%s%s]a" % (LOWER_PI, UPPER_PI, EM_SPACE),
  403. u"b%sa" % UPPER_PI) # bigcharset
  404. assert re.search(u"b[%s%s%s]a" % (LOWER_PI, UPPER_PI, EM_SPACE),
  405. u"b%sa" % EM_SPACE)
  406. assert not re.search(u"b[%s%s%s]a" % (LOWER_PI, UPPER_PI, EM_SPACE),
  407. u"b%sa" % LINE_SEP)
  408. def test_search_simple_literal_ignore(self):
  409. import re
  410. UPPER_PI = u"\u03a0"
  411. LOWER_PI = u"\u03c0"
  412. assert re.search(r"ba", "ba", re.IGNORECASE)
  413. assert re.search(r"ba", "BA", re.IGNORECASE)
  414. assert re.search(u"b%s" % UPPER_PI, u"B%s" % LOWER_PI,
  415. re.IGNORECASE | re.UNICODE)
  416. def test_search_simple_in_ignore(self):
  417. import re
  418. UPPER_PI = u"\u03a0"
  419. LOWER_PI = u"\u03c0"
  420. assert re.search(r"ba[A-C]", "bac", re.IGNORECASE)
  421. assert re.search(r"ba[a-c]", "baB", re.IGNORECASE)
  422. assert re.search(u"ba[%s]" % UPPER_PI, "ba%s" % LOWER_PI,
  423. re.IGNORECASE | re.UNICODE)
  424. assert re.search(r"ba[^A-C]", "bar", re.IGNORECASE)
  425. assert not re.search(r"ba[^A-C]", "baA", re.IGNORECASE)
  426. assert not re.search(r"ba[^A-C]", "baa", re.IGNORECASE)
  427. def test_search_simple_branch(self):
  428. import re
  429. assert re.search(r"a(bb|d[ef])b", "adeb")
  430. assert re.search(r"a(bb|d[ef])b", "abbb")
  431. def test_search_simple_repeat_one(self):
  432. import re
  433. assert re.search(r"aa+", "aa") # empty tail
  434. assert re.search(r"aa+ab", "aaaab") # backtracking
  435. assert re.search(r"aa*ab", "aab") # empty match
  436. assert re.search(r"a[bc]+", "abbccb")
  437. assert "abbcb" == re.search(r"a.+b", "abbcb\nb").group()
  438. assert "abbcb\nb" == re.search(r"a.+b", "abbcb\nb", re.DOTALL).group()
  439. assert re.search(r"ab+c", "aBbBbBc", re.IGNORECASE)
  440. assert not re.search(r"aa{2,3}", "aa") # string too short
  441. assert not re.search(r"aa{2,3}b", "aab") # too few repetitions
  442. assert not re.search(r"aa+b", "aaaac") # tail doesn't match
  443. def test_search_simple_min_repeat_one(self):
  444. import re
  445. assert re.search(r"aa+?", "aa") # empty tail
  446. assert re.search(r"aa+?ab", "aaaab") # forward tracking
  447. assert re.search(r"a[bc]+?", "abbccb")
  448. assert "abb" == re.search(r"a.+?b", "abbcb\nb").group()
  449. assert "a\nbb" == re.search(r"a.+b", "a\nbbc", re.DOTALL).group()
  450. assert re.search(r"ab+?c", "aBbBbBc", re.IGNORECASE)
  451. assert not re.search(r"aa+?", "a") # string too short
  452. assert not re.search(r"aa{2,3}?b", "aab") # too few repetitions
  453. assert not re.search(r"aa+?b", "aaaac") # tail doesn't match
  454. assert re.match(".*?cd", "abcabcde").end(0) == 7
  455. def test_search_simple_repeat_maximizing(self):
  456. import re
  457. assert not re.search(r"(ab){3,5}", "abab")
  458. assert not re.search(r"(ab){3,5}", "ababa")
  459. assert re.search(r"(ab){3,5}", "ababab")
  460. assert re.search(r"(ab){3,5}", "abababababab").end(0) == 10
  461. assert "ad" == re.search(r"(a.)*", "abacad").group(1)
  462. assert ("abcg", "cg") == (
  463. re.search(r"(ab(c.)*)+", "ababcecfabcg").groups())
  464. assert ("cg", "cg") == (
  465. re.search(r"(ab|(c.))+", "abcg").groups())
  466. assert ("ab", "cf") == (
  467. re.search(r"((c.)|ab)+", "cfab").groups())
  468. assert re.search(r".*", "")
  469. def test_search_simple_repeat_minimizing(self):
  470. import re
  471. assert not re.search(r"(ab){3,5}?", "abab")
  472. assert re.search(r"(ab){3,5}?", "ababab")
  473. assert re.search(r"b(a){3,5}?b", "baaaaab")
  474. assert not re.search(r"b(a){3,5}?b", "baaaaaab")
  475. assert re.search(r"a(b(.)+?)*", "abdbebb")
  476. def test_search_simple_groupref(self):
  477. import re
  478. UPPER_PI = u"\u03a0"
  479. LOWER_PI = u"\u03c0"
  480. assert re.match(r"((ab)+)c\1", "ababcabab")
  481. assert not re.match(r"((ab)+)c\1", "ababcab")
  482. assert not re.search(r"(a|(b))\2", "aa")
  483. assert re.match(r"((ab)+)c\1", "aBAbcAbaB", re.IGNORECASE)
  484. assert re.match(r"((a.)+)c\1", u"a%sca%s" % (UPPER_PI, LOWER_PI),
  485. re.IGNORECASE | re.UNICODE)
  486. def test_search_simple_groupref_exists(self):
  487. import re, sys
  488. if not sys.version_info[:2] == (2, 3):
  489. assert re.search(r"(<)?bla(?(1)>)", "<bla>")
  490. assert re.search(r"(<)?bla(?(1)>)", "bla")
  491. assert not re.match(r"(<)?bla(?(1)>)", "<bla")
  492. assert re.search(r"(<)?bla(?(1)>|u)", "blau")
  493. def test_search_simple_assert(self):
  494. import re
  495. assert re.search(r"b(?=\d\d).{3,}", "b23a")
  496. assert not re.search(r"b(?=\d\d).{3,}", "b2aa")
  497. assert re.search(r"b(?<=\d.)a", "2ba")
  498. assert not re.search(r"b(?<=\d.)a", "ba")
  499. def test_search_simple_assert_not(self):
  500. import re
  501. assert re.search(r"b(?<!\d.)a", "aba")
  502. assert re.search(r"b(?<!\d.)a", "ba")
  503. assert not re.search(r"b(?<!\d.)a", "11ba")
  504. class AppTestMarksStack:
  505. def test_mark_stack_branch(self):
  506. import re
  507. m = re.match("b(.)a|b.b", "bob")
  508. assert None == m.group(1)
  509. assert None == m.lastindex
  510. def test_mark_stack_repeat_one(self):
  511. import re
  512. m = re.match("\d+1((2)|(3))4", "2212413")
  513. assert ("2", "2", None) == m.group(1, 2, 3)
  514. assert 1 == m.lastindex
  515. def test_mark_stack_min_repeat_one(self):
  516. import re
  517. m = re.match("\d+?1((2)|(3))44", "221341244")
  518. assert ("2", "2", None) == m.group(1, 2, 3)
  519. assert 1 == m.lastindex
  520. def test_mark_stack_max_until(self):
  521. import re
  522. m = re.match("(\d)+1((2)|(3))4", "2212413")
  523. assert ("2", "2", None) == m.group(2, 3, 4)
  524. assert 2 == m.lastindex
  525. def test_mark_stack_min_until(self):
  526. import re
  527. m = re.match("(\d)+?1((2)|(3))44", "221341244")
  528. assert ("2", "2", None) == m.group(2, 3, 4)
  529. assert 2 == m.lastindex
  530. def test_bug_725149(self):
  531. # mark_stack_base restoring before restoring marks
  532. # test copied from CPython test
  533. import re
  534. assert re.match('(a)(?:(?=(b)*)c)*', 'abb').groups() == ('a', None)
  535. assert re.match('(a)((?!(b)*))*', 'abb').groups() == ('a', None, None)
  536. class AppTestOpcodes:
  537. spaceconfig = dict(usemodules=('_locale',))
  538. def setup_class(cls):
  539. if cls.runappdirect:
  540. py.test.skip("can only be run on py.py: _sre opcodes don't match")
  541. # This imports support_test_sre as the global "s"
  542. init_app_test(cls, cls.space)
  543. def test_length_optimization(self):
  544. s = self.s
  545. pattern = "bla"
  546. opcodes = [s.OPCODES["info"], 3, 3, len(pattern)] \
  547. + s.encode_literal(pattern) + [s.OPCODES["success"]]
  548. s.assert_no_match(opcodes, ["b", "bl", "ab"])
  549. def test_literal(self):
  550. s = self.s
  551. opcodes = s.encode_literal("bla") + [s.OPCODES["success"]]
  552. s.assert_no_match(opcodes, ["bl", "blu"])
  553. s.assert_match(opcodes, ["bla", "blab", "cbla", "bbla"])
  554. def test_not_literal(self):
  555. s = self.s
  556. opcodes = s.encode_literal("b") \
  557. + [s.OPCODES["not_literal"], ord("a"), s.OPCODES["success"]]
  558. s.assert_match(opcodes, ["bx", "ababy"])
  559. s.assert_no_match(opcodes, ["ba", "jabadu"])
  560. def test_unknown(self):
  561. s = self.s
  562. raises(RuntimeError, s.search, [55555], "b")
  563. def test_at_beginning(self):
  564. s = self.s
  565. for atname in ["at_beginning", "at_beginning_string"]:
  566. opcodes = [s.OPCODES["at"], s.ATCODES[atname]] \
  567. + s.encode_literal("bla") + [s.OPCODES["success"]]
  568. s.assert_match(opcodes, "bla")
  569. s.assert_no_match(opcodes, "abla")
  570. def test_at_beginning_line(self):
  571. s = self.s
  572. opcodes = [s.OPCODES["at"], s.ATCODES["at_beginning_line"]] \
  573. + s.encode_literal("bla") + [s.OPCODES["success"]]
  574. s.assert_match(opcodes, ["bla", "x\nbla"])
  575. s.assert_no_match(opcodes, ["abla", "abla\nubla"])
  576. def test_at_end(self):
  577. s = self.s
  578. opcodes = s.encode_literal("bla") \
  579. + [s.OPCODES["at"], s.ATCODES["at_end"], s.OPCODES["success"]]
  580. s.assert_match(opcodes, ["bla", "bla\n"])
  581. s.assert_no_match(opcodes, ["blau", "abla\nblau"])
  582. def test_at_end_line(self):
  583. s = self.s
  584. opcodes = s.encode_literal("bla") \
  585. + [s.OPCODES["at"], s.ATCODES["at_end_line"], s.OPCODES["success"]]
  586. s.assert_match(opcodes, ["bla\n", "bla\nx", "bla"])
  587. s.assert_no_match(opcodes, ["blau"])
  588. def test_at_end_string(self):
  589. s = self.s
  590. opcodes = s.encode_literal("bla") \
  591. + [s.OPCODES["at"], s.ATCODES["at_end_string"], s.OPCODES["success"]]
  592. s.assert_match(opcodes, "bla")
  593. s.assert_no_match(opcodes, ["blau", "bla\n"])
  594. def test_at_boundary(self):
  595. s = self.s
  596. for atname in "at_boundary", "at_loc_boundary", "at_uni_boundary":
  597. opcodes = s.encode_literal("bla") \
  598. + [s.OPCODES["at"], s.ATCODES[atname], s.OPCODES["success"]]
  599. s.assert_match(opcodes, ["bla", "bla ha", "bla,x"])
  600. s.assert_no_match(opcodes, ["blaja", ""])
  601. opcodes = [s.OPCODES["at"], s.ATCODES[atname]] \
  602. + s.encode_literal("bla") + [s.OPCODES["success"]]
  603. s.assert_match(opcodes, "bla")
  604. s.assert_no_match(opcodes, "")
  605. def test_at_non_boundary(self):
  606. s = self.s
  607. for atname in "at_non_boundary", "at_loc_non_boundary", "at_uni_non_boundary":
  608. opcodes = s.encode_literal("bla") \
  609. + [s.OPCODES["at"], s.ATCODES[atname], s.OPCODES["success"]]
  610. s.assert_match(opcodes, "blan")
  611. s.assert_no_match(opcodes, ["bla ja", "bla"])
  612. def test_at_loc_boundary(self):
  613. s = self.s
  614. import locale
  615. try:
  616. s.void_locale()
  617. opcodes1 = s.encode_literal("bla") \
  618. + [s.OPCODES["at"], s.ATCODES["at_loc_boundary"], s.OPCODES["success"]]
  619. opcodes2 = s.encode_literal("bla") \
  620. + [s.OPCODES["at"], s.ATCODES["at_loc_non_boundary"], s.OPCODES["success"]]
  621. s.assert_match(opcodes1, "bla\xFC")
  622. s.assert_no_match(opcodes2, "bla\xFC")
  623. oldlocale = locale.setlocale(locale.LC_ALL)
  624. locale.setlocale(locale.LC_ALL, "de_DE")
  625. s.assert_no_match(opcodes1, "bla\xFC")
  626. s.assert_match(opcodes2, "bla\xFC")
  627. locale.setlocale(locale.LC_ALL, oldlocale)
  628. except locale.Error:
  629. # skip test
  630. skip("locale error")
  631. def test_at_uni_boundary(self):
  632. s = self.s
  633. UPPER_PI = u"\u03a0"
  634. LOWER_PI = u"\u03c0"
  635. opcodes = s.encode_literal("bl") + [s.OPCODES["any"], s.OPCODES["at"],
  636. s.ATCODES["at_uni_boundary"], s.OPCODES["success"]]
  637. s.assert_match(opcodes, ["bla ha", u"bl%s ja" % UPPER_PI])
  638. s.assert_no_match(opcodes, [u"bla%s" % LOWER_PI])
  639. opcodes = s.encode_literal("bl") + [s.OPCODES["any"], s.OPCODES["at"],
  640. s.ATCODES["at_uni_non_boundary"], s.OPCODES["success"]]
  641. s.assert_match(opcodes, ["blaha", u"bl%sja" % UPPER_PI])
  642. def test_category_loc_word(self):
  643. s = self.s
  644. import locale
  645. try:
  646. s.void_locale()
  647. opcodes1 = s.encode_literal("b") \
  648. + [s.OPCODES["category"], s.CHCODES["category_loc_word"], s.OPCODES["success"]]
  649. opcodes2 = s.encode_literal("b") \
  650. + [s.OPCODES["category"], s.CHCODES["category_loc_not_word"], s.OPCODES["success"]]
  651. s.assert_no_match(opcodes1, "b\xFC")
  652. s.assert_no_match(opcodes1, u"b\u00FC")
  653. s.assert_match(opcodes2, "b\xFC")
  654. locale.setlocale(locale.LC_ALL, "de_DE")
  655. s.assert_match(opcodes1, "b\xFC")
  656. s.assert_no_match(opcodes1, u"b\u00FC")
  657. s.assert_no_match(opcodes2, "b\xFC")
  658. s.void_locale()
  659. except locale.Error:
  660. # skip test
  661. skip("locale error")
  662. def test_any(self):
  663. s = self.s
  664. opcodes = s.encode_literal("b") + [s.OPCODES["any"]] \
  665. + s.encode_literal("a") + [s.OPCODES["success"]]
  666. s.assert_match(opcodes, ["b a", "bla", "bboas"])
  667. s.assert_no_match(opcodes, ["b\na", "oba", "b"])
  668. def test_any_all(self):
  669. s = self.s
  670. opcodes = s.encode_literal("b") + [s.OPCODES["any_all"]] \
  671. + s.encode_literal("a") + [s.OPCODES["success"]]
  672. s.assert_match(opcodes, ["b a", "bla", "bboas", "b\na"])
  673. s.assert_no_match(opcodes, ["oba", "b"])
  674. def test_in_failure(self):
  675. s = self.s
  676. opcodes = s.encode_literal("b") + [s.OPCODES["in"], 2, s.OPCODES["failure"]] \
  677. + s.encode_literal("a") + [s.OPCODES["success"]]
  678. s.assert_no_match(opcodes, ["ba", "bla"])
  679. def test_in_literal(self):
  680. s = self.s
  681. opcodes = s.encode_literal("b") + [s.OPCODES["in"], 7] \
  682. + s.encode_literal("la") + [s.OPCODES["failure"], s.OPCODES["failure"]] \
  683. + s.encode_literal("a") + [s.OPCODES["success"]]
  684. s.assert_match(opcodes, ["bla", "baa", "blbla"])
  685. s.assert_no_match(opcodes, ["ba", "bja", "blla"])
  686. def test_in_category(self):
  687. s = self.s
  688. opcodes = s.encode_literal("b") + [s.OPCODES["in"], 6, s.OPCODES["category"],
  689. s.CHCODES["category_digit"], s.OPCODES["category"], s.CHCODES["category_space"],
  690. s.OPCODES["failure"]] + s.encode_literal("a") + [s.OPCODES["success"]]
  691. s.assert_match(opcodes, ["b1a", "b a", "b4b\tas"])
  692. s.assert_no_match(opcodes, ["baa", "b5"])
  693. def test_in_charset_ucs2(self):
  694. import _sre
  695. if _sre.CODESIZE != 2:
  696. return
  697. s = self.s
  698. # charset bitmap for characters "l" and "h"
  699. bitmap = 6 * [0] + [4352] + 9 * [0]
  700. opcodes = s.encode_literal("b") + [s.OPCODES["in"], 19, s.OPCODES["charset"]] \
  701. + bitmap + [s.OPCODES["failure"]] + s.encode_literal("a") + [s.OPCODES["success"]]
  702. s.assert_match(opcodes, ["bla", "bha", "blbha"])
  703. s.assert_no_match(opcodes, ["baa", "bl"])
  704. def _test_in_bigcharset_ucs2(self):
  705. # disabled because this actually only works on big-endian machines
  706. if _sre.CODESIZE != 2:
  707. return
  708. s = self.s
  709. # constructing bigcharset for lowercase pi (\u03c0)
  710. UPPER_PI = u"\u03a0"
  711. LOWER_PI = u"\u03c0"
  712. bitmap = 6 * [0] + [4352] + 9 * [0]
  713. opcodes = s.encode_literal("b") + [s.OPCODES["in"], 164, s.OPCODES["bigcharset"], 2] \
  714. + [0, 1] + 126 * [0] \
  715. + 16 * [0] \
  716. + 12 * [0] + [1] + 3 * [0] \
  717. + [s.OPCODES["failure"]] + s.encode_literal("a") + [s.OPCODES["success"]]
  718. s.assert_match(opcodes, [u"b%sa" % LOWER_PI])
  719. s.assert_no_match(opcodes, [u"b%sa" % UPPER_PI])
  720. # XXX bigcharset test for ucs4 missing here
  721. def test_in_range(self):
  722. s = self.s
  723. opcodes = s.encode_literal("b") + [s.OPCODES["in"], 5, s.OPCODES["range"],
  724. ord("1"), ord("9"), s.OPCODES["failure"]] \
  725. + s.encode_literal("a") + [s.OPCODES["success"]]
  726. s.assert_match(opcodes, ["b1a", "b56b7aa"])
  727. s.assert_no_match(opcodes, ["baa", "b5"])
  728. def test_in_negate(self):
  729. s = self.s
  730. opcodes = s.encode_literal("b") + [s.OPCODES["in"], 7, s.OPCODES["negate"]] \
  731. + s.encode_literal("la") + [s.OPCODES["failure"]] \
  732. + s.encode_literal("a") + [s.OPCODES["success"]]
  733. s.assert_match(opcodes, ["b1a", "bja", "bubua"])
  734. s.assert_no_match(opcodes, ["bla", "baa", "blbla"])
  735. def test_literal_ignore(self):
  736. s = self.s
  737. opcodes = s.encode_literal("b") \
  738. + [s.OPCODES["literal_ignore"], ord("a"), s.OPCODES["success"]]
  739. s.assert_match(opcodes, ["ba", "bA"])
  740. s.assert_no_match(opcodes, ["bb", "bu"])
  741. def test_not_literal_ignore(self):
  742. s = self.s
  743. UPPER_PI = u"\u03a0"
  744. opcodes = s.encode_literal("b") \
  745. + [s.OPCODES["not_literal_ignore"], ord("a"), s.OPCODES["success"]]
  746. s.assert_match(opcodes, ["bb", "bu", u"b%s" % UPPER_PI])
  747. s.assert_no_match(opcodes, ["ba", "bA"])
  748. def test_in_ignore(self):
  749. s = self.s
  750. opcodes = s.encode_literal("b") + [s.OPCODES["in_ignore"], 8] \
  751. + s.encode_literal("abc") + [s.OPCODES["failure"]] \
  752. + s.encode_literal("a") + [s.OPCODES["success"]]
  753. s.assert_match(opcodes, ["baa", "bAa", "bbbBa"])
  754. s.assert_no_match(opcodes, ["ba", "bja", "blla"])
  755. def test_in_jump_info(self):
  756. s = self.s
  757. for opname in "jump", "info":
  758. opcodes = s.encode_literal("b") \
  759. + [s.OPCODES[opname], 3, s.OPCODES["failure"], s.OPCODES["failure"]] \
  760. + s.encode_literal("a") + [s.OPCODES["success"]]
  761. s.assert_match(opcodes, "ba")
  762. def _test_mark(self):
  763. s = self.s
  764. # XXX need to rewrite this implementation-independent
  765. opcodes = s.encode_literal("a") + [s.OPCODES["mark"], 0] \
  766. + s.encode_literal("b") + [s.OPCODES["mark"], 1, s.OPCODES["success"]]
  767. state = self.create_state("abc")
  768. _sre._sre_search(state, opcodes)
  769. assert 1 == state.lastindex
  770. assert 1 == state.lastmark
  771. # NB: the following are indexes from the start of the match
  772. assert [1, 2] == state.marks
  773. def test_branch(self):
  774. s = self.s
  775. opcodes = [s.OPCODES["branch"], 7] + s.encode_literal("ab") \
  776. + [s.OPCODES["jump"], 9, 7] + s.encode_literal("cd") \
  777. + [s.OPCODES["jump"], 2, s.OPCODES["failure"], s.OPCODES["success"]]
  778. s.assert_match(opcodes, ["ab", "cd"])
  779. s.assert_no_match(opcodes, ["aacas", "ac", "bla"])
  780. def test_repeat_one(self):
  781. s = self.s
  782. opcodes = [s.OPCODES["repeat_one"], 6, 1, self.s.MAXREPEAT] + s.encode_literal("a") \
  783. + [s.OPCODES["success"]] + s.encode_literal("ab") + [s.OPCODES["success"]]
  784. s.assert_match(opcodes, ["aab", "aaaab"])
  785. s.assert_no_match(opcodes, ["ab", "a"])
  786. def test_min_repeat_one(self):
  787. s = self.s
  788. opcodes = [s.OPCODES["min_repeat_one"], 5, 1, self.s.MAXREPEAT, s.OPCODES["any"]] \
  789. + [s.OPCODES["success"]] + s.encode_literal("b") + [s.OPCODES["success"]]
  790. s.assert_match(opcodes, ["aab", "ardb", "bb"])
  791. s.assert_no_match(opcodes, ["b"])
  792. def test_repeat_maximizing(self):
  793. s = self.s
  794. opcodes = [s.OPCODES["repeat"], 5, 1, self.s.MAXREPEAT] + s.encode_literal("a") \
  795. + [s.OPCODES["max_until"]] + s.encode_literal("b") + [s.OPCODES["success"]]
  796. s.assert_match(opcodes, ["ab", "aaaab", "baabb"])
  797. s.assert_no_match(opcodes, ["aaa", "", "ac"])
  798. def test_max_until_zero_width_match(self):
  799. # re.compile won't compile prospective zero-with matches (all of them?),
  800. # so we can only produce an example by directly constructing bytecodes.
  801. # CPython 2.3 fails with a recursion limit exceeded error here.
  802. import sys
  803. if not sys.version_info[:2] == (2, 3):
  804. s = self.s
  805. opcodes = [s.OPCODES["repeat"], 10, 1, self.s.MAXREPEAT, s.OPCODES["repeat_one"],
  806. 6, 0, self.s.MAXREPEAT] + s.encode_literal("a") + [s.OPCODES["success"],
  807. s.OPCODES["max_until"], s.OPCODES["success"]]
  808. s.assert_match(opcodes, ["ab", "bb"])
  809. assert "" == s.search(opcodes, "bb").group(0)
  810. def test_repeat_minimizing(self):
  811. s = self.s
  812. opcodes = [s.OPCODES["repeat"], 4, 1, self.s.MAXREPEAT, s.OPCODES["any"],
  813. s.OPCODES["min_until"]] + s.encode_literal("b") + [s.OPCODES["success"]]
  814. s.assert_match(opcodes, ["ab", "aaaab", "baabb"])
  815. s.assert_no_match(opcodes, ["b"])
  816. assert "aab" == s.search(opcodes, "aabb").group(0)
  817. def test_groupref(self):
  818. s = self.s
  819. opcodes = [s.OPCODES["mark"], 0, s.OPCODES["any"], s.OPCODES["mark"], 1] \
  820. + s.encode_literal("a") + [s.OPCODES["groupref"], 0, s.OPCODES["success"]]
  821. s.assert_match(opcodes, ["bab", "aaa", "dad"])
  822. s.assert_no_match(opcodes, ["ba", "bad", "baad"])
  823. def test_groupref_ignore(self):
  824. s = self.s
  825. opcodes = [s.OPCODES["mark"], 0, s.OPCODES["any"], s.OPCODES["mark"], 1] \
  826. + s.encode_literal("a") + [s.OPCODES["groupref_ignore"], 0, s.OPCODES["success"]]
  827. s.assert_match(opcodes, ["bab", "baB", "Dad"])
  828. s.assert_no_match(opcodes, ["ba", "bad", "baad"])
  829. def test_assert(self):
  830. s = self.s
  831. opcodes = s.encode_literal("a") + [s.OPCODES["assert"], 4, 0] \
  832. + s.encode_literal("b") + [s.OPCODES["success"], s.OPCODES["success"]]
  833. assert "a" == s.search(opcodes, "ab").group(0)
  834. s.assert_no_match(opcodes, ["a", "aa"])
  835. def test_assert_not(self):
  836. s = self.s
  837. opcodes = s.encode_literal("a") + [s.OPCODES["assert_not"], 4, 0] \
  838. + s.encode_literal("b") + [s.OPCODES["success"], s.OPCODES["success"]]
  839. assert "a" == s.search(opcodes, "ac").group(0)
  840. s.assert_match(opcodes, ["a"])
  841. s.assert_no_match(opcodes, ["ab"])
  842. class AppTestOptimizations:
  843. """These tests try to trigger optmized edge cases."""
  844. def test_match_length_optimization(self):
  845. import re
  846. assert None == re.match("bla", "blub")
  847. def test_fast_search(self):
  848. import re
  849. assert None == re.search("bl", "abaub")
  850. assert None == re.search("bl", "b")
  851. assert ["bl", "bl"] == re.findall("bl", "blbl")
  852. assert ["a", "u"] == re.findall("bl(.)", "blablu")
  853. def test_branch_literal_shortcut(self):
  854. import re
  855. assert None == re.search("bl|a|c", "hello")
  856. def test_literal_search(self):
  857. import re
  858. assert re.search("b(\d)", "ababbbab1")
  859. assert None == re.search("b(\d)", "ababbbab")
  860. def test_repeat_one_literal_tail(self):
  861. import re
  862. assert re.search(".+ab", "wowowowawoabwowo")
  863. assert None == re.search(".+ab", "wowowaowowo")