PageRenderTime 66ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

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

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