Debian Codegraph @

pypy/module/_sre/test/test_app_sre.py

raw symbols SCIP
1 """Regular expression tests specific to _sre.py and accumulated during TDD."""
2
3 import os
4 import py
5 from py.test import raises, skip
6 from pypy.interpreter.gateway import app2interp_temp
7
8
9 def init_app_test(cls, space):
10 cls.w_s = space.appexec(
11 [space.wrap(os.path.realpath(os.path.dirname(__file__)))],
12 """(this_dir):
13 import sys
14 # Uh-oh, ugly hack
15 sys.path.insert(0, this_dir)
16 try:
17 import support_test_app_sre
18 return support_test_app_sre
19 finally:
20 sys.path.pop(0)
21 """)
22
23
24 class AppTestSrePy:
25 def test_magic(self):
26 import _sre, sre_constants
27 assert sre_constants.MAGIC == _sre.MAGIC
28
29 def test_codesize(self):
30 import _sre
31 assert _sre.getcodesize() == _sre.CODESIZE
32 # in py3.7, it should always be 4
33 assert _sre.CODESIZE == 4
34
35 def test_opcodes(self):
36 import _sre
37 assert _sre.OPCODES[:4] == 'failure success any any_all'.split()
38
39
40 class AppTestSrePattern:
41 def setup_class(cls):
42 # This imports support_test_sre as the global "s"
43 init_app_test(cls, cls.space)
44
45 spaceconfig = {'usemodules': ['itertools']}
46
47 def test_copy(self):
48 # new in 3.7
49 import re
50 p = re.compile("b")
51 assert p.__copy__() is p
52 assert p.__deepcopy__("whatever") is p
53
54 def test_creation_attributes(self):
55 import re
56 pattern_string = b"(b)l(?P<g>a)"
57 p = re.compile(pattern_string, re.I | re.M)
58 assert pattern_string == p.pattern
59 assert re.I | re.M == p.flags
60 assert 2 == p.groups
61 assert {"g": 2} == p.groupindex
62 raises(TypeError, "p.groupindex['g'] = 3")
63
64 def test_repeat_minmax_overflow(self):
65 import re
66 string = "x" * 100000
67 assert re.match(r".{%d}" % (self.s.MAXREPEAT - 1), string) is None
68 assert re.match(r".{,%d}" % (self.s.MAXREPEAT - 1), string).span() == (0, 100000)
69 assert re.match(r".{%d,}?" % (self.s.MAXREPEAT - 1), string) is None
70 import sys
71 if sys.version_info[:3] <= (3, 2, 3):
72 # XXX: These are fixed in 3.2.4 or so
73 return
74 raises(OverflowError, re.compile, r".{%d}" % self.s.MAXREPEAT)
75 raises(OverflowError, re.compile, r".{,%d}" % self.s.MAXREPEAT)
76 raises(OverflowError, re.compile, r".{%d,}?" % self.s.MAXREPEAT)
77
78 def test_match_none(self):
79 import re
80 p = re.compile("bla")
81 none_matches = ["b", "bl", "blub", "jupidu"]
82 for string in none_matches:
83 assert None == p.match(string)
84
85 def test_pos_endpos(self):
86 import re
87 # XXX maybe fancier tests here
88 p = re.compile("bl(a)")
89 tests = [("abla", 0, 4), ("abla", 1, 4), ("ablaa", 1, 4)]
90 for string, pos, endpos in tests:
91 assert p.search(string, pos, endpos)
92 tests = [("abla", 0, 3), ("abla", 2, 4)]
93 for string, pos, endpos in tests:
94 assert not p.search(string, pos, endpos)
95
96 def test_findall(self):
97 import re
98 assert ["b"] == re.findall("b", "bla")
99 assert ["a", "u"] == re.findall("b(.)", "abalbus")
100 assert [("a", "l"), ("u", "s")] == re.findall("b(.)(.)", "abalbus")
101 assert [("a", ""), ("s", "s")] == re.findall("b(a|(s))", "babs")
102 assert ['', '', 'X', '', ''] == re.findall("X??", "1X4") # new in 3.7
103
104 def test_findall_unicode(self):
105 import re
106 assert [u"\u1234"] == re.findall(u"\u1234", u"\u1000\u1234\u2000")
107 assert ["a", "u"] == re.findall("b(.)", "abalbus")
108 assert [("a", "l"), ("u", "s")] == re.findall("b(.)(.)", "abalbus")
109 assert [("a", ""), ("s", "s")] == re.findall("b(a|(s))", "babs")
110 assert [(b"a", b""), (b"s", b"s")] == re.findall(b"b(a|(s))", b"babs")
111 assert [u"xyz"] == re.findall(u".*yz", u"xyz")
112
113 def test_finditer(self):
114 import re
115 it = re.finditer("b(.)", "brabbel")
116 assert "br" == next(it).group(0)
117 assert "bb" == next(it).group(0)
118 raises(StopIteration, next, it)
119
120 def test_split(self):
121 import re
122 assert ["a", "o", "u", ""] == re.split("b", "abobub")
123 assert ["a", "o", "ub"] == re.split("b", "abobub", 2)
124 assert ['', 'a', 'l', 'a', 'lla'] == re.split("b(a)", "balballa")
125 assert ['', 'a', None, 'l', 'u', None, 'lla'] == (
126 re.split("b([ua]|(s))", "balbulla"))
127 assert ['Hello \udce2\udc9c\udc93', ''] == re.split(r'\r\n|\r|\n',
128 'Hello \udce2\udc9c\udc93\n')
129
130 def test_weakref(self):
131 import re, _weakref
132 _weakref.ref(re.compile(r""))
133
134 def test_match_compat(self):
135 import re
136 res = re.match(r'(a)|(b)', 'b').start(1)
137 assert res == -1
138
139 def test_pattern_check(self):
140 import _sre
141 raises(TypeError, _sre.compile, {}, 0, [])
142
143 def test_fullmatch(self):
144 import re
145 assert re.compile(r"ab*c").fullmatch("abbcdef") is None
146 assert re.compile(r"ab*c").fullmatch("abbc") is not None
147 assert re.fullmatch(r"ab*c", "abbbcdef") is None
148 assert re.fullmatch(r"ab*c", "abbbc") is not None
149
150 def test_repr(self):
151 import re
152 r = re.compile(r'f(o"\d)', 0)
153 assert repr(r) == (
154 r"""re.compile('f(o"\\d)')""")
155 r = re.compile(r'f(o"\d)', re.IGNORECASE|re.DOTALL|re.VERBOSE)
156 assert repr(r) == (
157 r"""re.compile('f(o"\\d)', re.IGNORECASE|re.DOTALL|re.VERBOSE)""")
158
159 def test_pattern_compare(self):
160 import re
161 pattern1 = re.compile('abc', re.IGNORECASE)
162
163 # equal to itself
164 assert pattern1 == pattern1
165 assert not(pattern1 != pattern1)
166 # equal
167 re.purge()
168 pattern2 = re.compile('abc', re.IGNORECASE)
169 assert hash(pattern2) == hash(pattern1)
170 assert pattern2 == pattern1
171
172 # not equal: different pattern
173 re.purge()
174 pattern3 = re.compile('XYZ', re.IGNORECASE)
175 # warranty that hash values are different
176 assert pattern3 != pattern1
177
178 # not equal: different flag (flags=0)
179 re.purge()
180 pattern4 = re.compile('abc')
181 assert pattern4 != pattern1
182
183 # only == and != comparison operators are supported
184 raises(TypeError, "pattern1 < pattern2")
185
186
187 class AppTestSreMatch:
188 spaceconfig = dict(usemodules=('array', ))
189
190 def test_copy(self):
191 import re
192 # new in 3.7
193 m = re.match("bla", "bla")
194 assert m.__copy__() is m
195 assert m.__deepcopy__("whatever") is m
196
197 def test_match_attributes(self):
198 import re
199 c = re.compile("bla")
200 m = c.match("blastring")
201 assert "blastring" == m.string
202 assert c == m.re
203 assert 0 == m.pos
204 assert 9 == m.endpos
205 assert None == m.lastindex
206 assert None == m.lastgroup
207 assert ((0, 3),) == m.regs
208
209 def test_match_attributes_with_groups(self):
210 import re
211 m = re.search("a(b)(?P<name>c)", "aabcd")
212 assert 0 == m.pos
213 assert 5 == m.endpos
214 assert 2 == m.lastindex
215 assert "name" == m.lastgroup
216 assert ((1, 4), (2, 3), (3, 4)) == m.regs
217
218 def test_regs_overlapping_groups(self):
219 import re
220 m = re.match("a((b)c)", "abc")
221 assert ((0, 3), (1, 3), (1, 2)) == m.regs
222
223 def test_start_end_span(self):
224 import re
225 m = re.search("a((b)c)", "aabcd")
226 assert (1, 4) == (m.start(), m.end())
227 assert (1, 4) == m.span()
228 assert (2, 4) == (m.start(1), m.end(1))
229 assert (2, 4) == m.span(1)
230 assert (2, 3) == (m.start(2), m.end(2))
231 assert (2, 3) == m.span(2)
232 raises(IndexError, m.start, 3)
233 raises(IndexError, m.end, 3)
234 raises(IndexError, m.span, 3)
235 raises(IndexError, m.start, -1)
236
237 def test_groups(self):
238 import re
239 m = re.search("a((.).)", "aabcd")
240 assert ("ab", "a") == m.groups()
241 assert ("ab", "a") == m.groups(True)
242 m = re.search("a((\d)|(\s))", "aa1b")
243 assert ("1", "1", None) == m.groups()
244 assert ("1", "1", True) == m.groups(True)
245 m = re.search("a((\d)|(\s))", "a ")
246 assert (" ", None, " ") == m.groups()
247 m = re.match("(a)", "a")
248 assert ("a",) == m.groups()
249
250 def test_groupdict(self):
251 import re
252 m = re.search("a((.).)", "aabcd")
253 assert {} == m.groupdict()
254 m = re.search("a((?P<first>.).)", "aabcd")
255 assert {"first": "a"} == m.groupdict()
256 m = re.search("a((?P<first>\d)|(?P<second>\s))", "aa1b")
257 assert {"first": "1", "second": None} == m.groupdict()
258 assert {"first": "1", "second": True} == m.groupdict(True)
259
260 def test_group(self):
261 import re
262 m = re.search("a((?P<first>\d)|(?P<second>\s))", "aa1b")
263 assert "a1" == m.group()
264 assert ("1", "1", None) == m.group(1, 2, 3)
265 assert ("1", None) == m.group("first", "second")
266 raises(IndexError, m.group, 1, 4)
267 assert ("1", None) == m.group(1, "second")
268 raises(IndexError, m.group, 'foobarbaz')
269 raises(IndexError, m.group, 'first', 'foobarbaz')
270
271 def test_group_takes_long(self):
272 import re
273 import sys
274 if sys.version_info < (2, 7, 9):
275 skip()
276 assert re.match("(foo)", "foo").group(1) == "foo"
277 exc = raises(IndexError, re.match("", "").group, sys.maxsize + 1)
278 assert str(exc.value) == "no such group"
279
280 def test_group_takes_index(self):
281 import re
282 class Index:
283 def __init__(self, value):
284 self.value = value
285 def __index__(self):
286 return self.value
287 assert re.match("(foo)", "foo").group(Index(1)) == "foo"
288
289 def test_getitem(self):
290 import re
291 assert re.match("(foo)bar", "foobar")[1] == "foo"
292
293 def test_expand(self):
294 import re
295 m = re.search("a(..)(?P<name>..)", "ab1bc")
296 assert "b1bcbc" == m.expand(r"\1\g<name>\2")
297
298 def test_sub_bytes(self):
299 import re
300 assert b"bbbbb" == re.sub(b"a", b"b", b"ababa")
301 assert (b"bbbbb", 3) == re.subn(b"a", b"b", b"ababa")
302 assert b"dddd" == re.sub(b"[abc]", b"d", b"abcd")
303 assert (b"dddd", 3) == re.subn(b"[abc]", b"d", b"abcd")
304 assert b"rbd\nbr\n" == re.sub(b"a(.)", br"b\1\n", b"radar")
305 assert (b"rbd\nbr\n", 2) == re.subn(b"a(.)", br"b\1\n", b"radar")
306 assert (b"bbbba", 2) == re.subn(b"a", b"b", b"ababa", 2)
307
308 def test_sub_unicode(self):
309 import re
310 assert isinstance(re.sub("a", "b", ""), str)
311 # the input is returned unmodified if no substitution is performed,
312 # which (if interpreted literally, as CPython does) gives the
313 # following strangeish rules:
314 assert isinstance(re.sub("a", "b", "diwoiioamoi"), str)
315 raises(TypeError, re.sub, "a", "b", b"diwoiiobmoi")
316 raises(TypeError, re.sub, 'x', b'y', b'x')
317
318 def test_sub_callable(self):
319 import re
320 def call_me(match):
321 ret = ""
322 for char in match.group():
323 ret += chr(ord(char) + 1)
324 return ret
325 assert ("bbbbb", 3) == re.subn("a", call_me, "ababa")
326
327 def test_sub_callable_returns_none(self):
328 import re
329 def call_me(match):
330 return None
331 assert "acd" == re.sub("b", call_me, "abcd")
332
333 def test_sub_subclass_of_str(self):
334 import re
335 class MyString(str):
336 pass
337 class MyBytes(bytes):
338 pass
339 s1 = MyString('zz')
340 s2 = re.sub('aa', 'bb', s1)
341 assert s2 == s1
342 assert type(s2) is str # and not MyString
343 u1 = MyBytes(b'zz')
344 u2 = re.sub(b'aa', b'bb', u1)
345 assert u2 == u1
346 assert type(u2) is bytes # and not MyBytes
347
348 def test_sub_bug(self):
349 import re
350 assert re.sub('=\w{2}', 'x', '=CA') == 'x'
351
352 def test_sub_emptymatch(self):
353 import re
354 assert re.sub(r"b*", "*", "abc") == "*a*c*" # changes in 3.7
355
356 def test_sub_shortcut_no_match(self):
357 import re
358 s = b"ccccccc"
359 assert re.sub(b"a", b"b", s) is s
360 s = u"ccccccc"
361 assert re.sub(u"a", u"b", s) is s
362
363 def test_sub_bytearray(self):
364 import re
365 assert re.sub(b'a', bytearray(b'A'), b'axa') == b'AxA'
366 # this fails on CPython 3.5:
367 assert re.sub(b'a', bytearray(b'\\n'), b'axa') == b'\nx\n'
368
369 def test_sub_emptymatch(self):
370 import re
371 assert re.sub(r"b*", "*", "abc") == "*a**c*"
372
373 def test_match_array(self):
374 import re, array
375 a = array.array('b', b'hello')
376 m = re.match(b'hel+', a)
377 assert m.end() == 4
378
379 def test_match_typeerror(self):
380 import re
381 raises(TypeError, re.match, 'hel+', list('hello'))
382
383 def test_match_repr(self):
384 import re
385 m = re.search("ab+c", "xabbbcd")
386 assert repr(m) == "<re.Match object; span=(1, 6), match='abbbc'>"
387
388 def test_unicode_iscased(self):
389 import _sre
390 assert _sre.unicode_iscased(64261)
391 assert not _sre.unicode_iscased(32)
392
393 def test_group_bugs(self):
394 import re
395 r = re.compile(r"""
396 \&(?:
397 (?P<escaped>\&) |
398 (?P<named>[_a-z][_a-z0-9]*) |
399 {(?P<braced>[_a-z][_a-z0-9]*)} |
400 (?P<invalid>)
401 )
402 """, re.IGNORECASE | re.VERBOSE)
403 matches = list(r.finditer('this &gift is for &{who} &&'))
404 assert len(matches) == 3
405 assert matches[0].groupdict() == {'escaped': None,
406 'named': 'gift',
407 'braced': None,
408 'invalid': None}
409 assert matches[1].groupdict() == {'escaped': None,
410 'named': None,
411 'braced': 'who',
412 'invalid': None}
413 assert matches[2].groupdict() == {'escaped': '&',
414 'named': None,
415 'braced': None,
416 'invalid': None}
417 matches = list(r.finditer('&who likes &{what)')) # note the ')'
418 assert len(matches) == 2
419 assert matches[0].groupdict() == {'escaped': None,
420 'named': 'who',
421 'braced': None,
422 'invalid': None}
423 assert matches[1].groupdict() == {'escaped': None,
424 'named': None,
425 'braced': None,
426 'invalid': ''}
427
428 def test_sub_typecheck(self):
429 import re
430 KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
431 raises(TypeError, KEYCRE.sub, "hello", {"%(": 1})
432
433 def test_sub_matches_stay_valid(self):
434 import re
435 matches = []
436 def callback(match):
437 matches.append(match)
438 return "x"
439 result = re.compile(r"[ab]").sub(callback, "acb")
440 assert result == "xcx"
441 assert len(matches) == 2
442 assert matches[0].group() == "a"
443 assert matches[1].group() == "b"
444
445
446 class AppTestSreScanner:
447
448 spaceconfig = {'usemodules': ['itertools']}
449
450 def test_scanner_attributes(self):
451 import re
452 p = re.compile("bla")
453 s = p.scanner("blablubla")
454 assert p == s.pattern
455
456 def test_scanner_match(self):
457 import re
458 p = re.compile(".").scanner("bla")
459 assert ("b", "l", "a") == (p.match().group(0),
460 p.match().group(0), p.match().group(0))
461 assert None == p.match()
462
463 def test_scanner_match_detail(self):
464 import re
465 p = re.compile("a").scanner("aaXaa")
466 assert "a" == p.match().group(0)
467 assert "a" == p.match().group(0)
468 assert None == p.match()
469 # the rest has been changed somewhere between Python 2.6.9
470 # and Python 2.7.18. PyPy now follows the 2.7.18 behavior
471 assert None == p.match()
472 assert None == p.match()
473
474 def test_scanner_search(self):
475 import re
476 p = re.compile("\d").scanner("bla23c5a")
477 assert ("2", "3", "5") == (p.search().group(0),
478 p.search().group(0), p.search().group(0))
479 assert None == p.search()
480
481 def test_scanner_zero_width_match(self):
482 import re, sys
483 if sys.version_info[:2] == (2, 3):
484 skip("2.3 is different here")
485 p = re.compile(".*").scanner("bla")
486 assert ("bla", "") == (p.search().group(0), p.search().group(0))
487 assert None == p.search()
488
489 def test_scanner_empty_match(self):
490 import re, sys
491 p = re.compile("a??").scanner("bac")
492 assert ("", "", "a", "", "") == (
493 p.search().group(0), p.search().group(0), p.search().group(0),
494 p.search().group(0), p.search().group(0))
495 assert None == p.search()
496
497 def test_no_pattern(self):
498 import sre_compile, sre_parse
499 sre_pattern = sre_compile.compile(
500 sre_parse.SubPattern(sre_parse.State()))
501 assert sre_pattern.scanner('s') is not None
502
503 def test_scanner_match_string(self):
504 import re
505 class mystr(type(u"")):
506 pass
507 s = mystr(u"bla")
508 p = re.compile(u".").scanner(s)
509 m = p.match()
510 assert m.string is s
511
512 class AppTestGetlower:
513 spaceconfig = dict(usemodules=('_locale',))
514
515 def setup_class(cls):
516 # This imports support_test_sre as the global "s"
517 init_app_test(cls, cls.space)
518
519 def setup_method(self, method):
520 import locale
521 locale.setlocale(locale.LC_ALL, (None, None))
522
523 def teardown_method(self, method):
524 import locale
525 locale.setlocale(locale.LC_ALL, (None, None))
526
527 def test_getlower_no_flags(self):
528 s = self.s
529 UPPER_AE = "\xc4"
530 s.assert_lower_equal([("a", "a"), ("A", "a"), (UPPER_AE, UPPER_AE),
531 ("\u00c4", "\u00c4"), ("\u4444", "\u4444")], 0)
532
533 def test_getlower_unicode(self):
534 s = self.s
535 import sre_constants
536 UPPER_AE = "\xc4"
537 LOWER_AE = "\xe4"
538 UPPER_PI = "\u03a0"
539 LOWER_PI = "\u03c0"
540 s.assert_lower_equal([("a", "a"), ("A", "a"), (UPPER_AE, LOWER_AE),
541 ("\u00c4", "\u00e4"), (UPPER_PI, LOWER_PI),
542 ("\u4444", "\u4444")], sre_constants.SRE_FLAG_UNICODE)
543
544
545 class AppTestSimpleSearches:
546
547 spaceconfig = {'usemodules': ('array', 'itertools')}
548
549 def test_search_simple_literal(self):
550 import re
551 assert re.search("bla", "bla")
552 assert re.search("bla", "blab")
553 assert not re.search("bla", "blu")
554
555 def test_search_simple_ats(self):
556 import re
557 assert re.search("^bla", "bla")
558 assert re.search("^bla", "blab")
559 assert not re.search("^bla", "bbla")
560 assert re.search("bla$", "abla")
561 assert re.search("bla$", "bla\n")
562 assert not re.search("bla$", "blaa")
563
564 def test_search_simple_boundaries(self):
565 import re
566 UPPER_PI = "\u03a0"
567 assert re.search(r"bla\b", "bla")
568 assert re.search(r"bla\b", "bla ja")
569 assert re.search(r"bla\b", "bla%s" % UPPER_PI, re.ASCII)
570 assert not re.search(r"bla\b", "blano")
571 assert not re.search(r"bla\b", "bla%s" % UPPER_PI, re.UNICODE)
572
573 def test_search_simple_categories(self):
574 import re
575 LOWER_PI = "\u03c0"
576 INDIAN_DIGIT = "\u0966"
577 EM_SPACE = "\u2001"
578 LOWER_AE = "\xe4"
579 assert re.search(r"bla\d\s\w", "bla3 b")
580 assert re.search(r"b\d", "b%s" % INDIAN_DIGIT, re.UNICODE)
581 assert not re.search(r"b\D", "b%s" % INDIAN_DIGIT, re.UNICODE)
582 assert re.search(r"b\s", "b%s" % EM_SPACE, re.UNICODE)
583 assert not re.search(r"b\S", "b%s" % EM_SPACE, re.UNICODE)
584 assert re.search(r"b\w", "b%s" % LOWER_PI, re.UNICODE)
585 assert not re.search(r"b\W", "b%s" % LOWER_PI, re.UNICODE)
586 assert re.search(r"b\w", "b%s" % LOWER_AE, re.UNICODE)
587
588 def test_search_simple_any(self):
589 import re
590 assert re.search(r"b..a", "jboaas")
591 assert not re.search(r"b..a", "jbo\nas")
592 assert re.search(r"b..a", "jbo\nas", re.DOTALL)
593
594 def test_search_simple_in(self):
595 import re
596 UPPER_PI = "\u03a0"
597 LOWER_PI = "\u03c0"
598 EM_SPACE = "\u2001"
599 LINE_SEP = "\u2028"
600 assert re.search(r"b[\da-z]a", "bb1a")
601 assert re.search(r"b[\da-z]a", "bbsa")
602 assert not re.search(r"b[\da-z]a", "bbSa")
603 assert re.search(r"b[^okd]a", "bsa")
604 assert not re.search(r"b[^okd]a", "bda")
605 assert re.search("b[%s%s%s]a" % (LOWER_PI, UPPER_PI, EM_SPACE),
606 "b%sa" % UPPER_PI) # bigcharset
607 assert re.search("b[%s%s%s]a" % (LOWER_PI, UPPER_PI, EM_SPACE),
608 "b%sa" % EM_SPACE)
609 assert not re.search("b[%s%s%s]a" % (LOWER_PI, UPPER_PI, EM_SPACE),
610 "b%sa" % LINE_SEP)
611
612 def test_search_simple_literal_ignore(self):
613 import re
614 UPPER_PI = "\u03a0"
615 LOWER_PI = "\u03c0"
616 assert re.search(r"ba", "ba", re.IGNORECASE)
617 assert re.search(r"ba", "BA", re.IGNORECASE)
618 assert re.search("b%s" % UPPER_PI, "B%s" % LOWER_PI,
619 re.IGNORECASE | re.UNICODE)
620
621 def test_search_simple_in_ignore(self):
622 import re
623 UPPER_PI = "\u03a0"
624 LOWER_PI = "\u03c0"
625 assert re.search(r"ba[A-C]", "bac", re.IGNORECASE)
626 assert re.search(r"ba[a-c]", "baB", re.IGNORECASE)
627 assert re.search("ba[%s]" % UPPER_PI, "ba%s" % LOWER_PI,
628 re.IGNORECASE | re.UNICODE)
629 assert re.search(r"ba[^A-C]", "bar", re.IGNORECASE)
630 assert not re.search(r"ba[^A-C]", "baA", re.IGNORECASE)
631 assert not re.search(r"ba[^A-C]", "baa", re.IGNORECASE)
632
633 def test_search_simple_branch(self):
634 import re
635 assert re.search(r"a(bb|d[ef])b", "adeb")
636 assert re.search(r"a(bb|d[ef])b", "abbb")
637
638 def test_search_simple_repeat_one(self):
639 import re
640 assert re.search(r"aa+", "aa") # empty tail
641 assert re.search(r"aa+ab", "aaaab") # backtracking
642 assert re.search(r"aa*ab", "aab") # empty match
643 assert re.search(r"a[bc]+", "abbccb")
644 assert "abbcb" == re.search(r"a.+b", "abbcb\nb").group()
645 assert "abbcb\nb" == re.search(r"a.+b", "abbcb\nb", re.DOTALL).group()
646 assert re.search(r"ab+c", "aBbBbBc", re.IGNORECASE)
647 assert not re.search(r"aa{2,3}", "aa") # string too short
648 assert not re.search(r"aa{2,3}b", "aab") # too few repetitions
649 assert not re.search(r"aa+b", "aaaac") # tail doesn't match
650
651 def test_search_simple_min_repeat_one(self):
652 import re
653 assert re.search(r"aa+?", "aa") # empty tail
654 assert re.search(r"aa+?ab", "aaaab") # forward tracking
655 assert re.search(r"a[bc]+?", "abbccb")
656 assert "abb" == re.search(r"a.+?b", "abbcb\nb").group()
657 assert "a\nbb" == re.search(r"a.+b", "a\nbbc", re.DOTALL).group()
658 assert re.search(r"ab+?c", "aBbBbBc", re.IGNORECASE)
659 assert not re.search(r"aa+?", "a") # string too short
660 assert not re.search(r"aa{2,3}?b", "aab") # too few repetitions
661 assert not re.search(r"aa+?b", "aaaac") # tail doesn't match
662 assert re.match(".*?cd", "abcabcde").end(0) == 7
663
664 def test_search_simple_repeat_maximizing(self):
665 import re
666 assert not re.search(r"(ab){3,5}", "abab")
667 assert not re.search(r"(ab){3,5}", "ababa")
668 assert re.search(r"(ab){3,5}", "ababab")
669 assert re.search(r"(ab){3,5}", "abababababab").end(0) == 10
670 assert "ad" == re.search(r"(a.)*", "abacad").group(1)
671 assert ("abcg", "cg") == (
672 re.search(r"(ab(c.)*)+", "ababcecfabcg").groups())
673 assert ("cg", "cg") == (
674 re.search(r"(ab|(c.))+", "abcg").groups())
675 assert ("ab", "cf") == (
676 re.search(r"((c.)|ab)+", "cfab").groups())
677 assert re.search(r".*", "")
678
679 def test_search_simple_repeat_minimizing(self):
680 import re
681 assert not re.search(r"(ab){3,5}?", "abab")
682 assert re.search(r"(ab){3,5}?", "ababab")
683 assert re.search(r"b(a){3,5}?b", "baaaaab")
684 assert not re.search(r"b(a){3,5}?b", "baaaaaab")
685 assert re.search(r"a(b(.)+?)*", "abdbebb")
686
687 def test_search_simple_groupref(self):
688 import re
689 UPPER_PI = "\u03a0"
690 LOWER_PI = "\u03c0"
691 assert re.match(r"((ab)+)c\1", "ababcabab")
692 assert not re.match(r"((ab)+)c\1", "ababcab")
693 assert not re.search(r"(a|(b))\2", "aa")
694 assert re.match(r"((ab)+)c\1", "aBAbcAbaB", re.IGNORECASE)
695 assert re.match(r"((a.)+)c\1", "a%sca%s" % (UPPER_PI, LOWER_PI),
696 re.IGNORECASE | re.UNICODE)
697
698 def test_search_simple_groupref_exists(self):
699 import re, sys
700 if not sys.version_info[:2] == (2, 3):
701 assert re.search(r"(<)?bla(?(1)>)", "<bla>")
702 assert re.search(r"(<)?bla(?(1)>)", "bla")
703 assert not re.match(r"(<)?bla(?(1)>)", "<bla")
704 assert re.search(r"(<)?bla(?(1)>|u)", "blau")
705
706 def test_search_simple_assert(self):
707 import re
708 assert re.search(r"b(?=\d\d).{3,}", "b23a")
709 assert not re.search(r"b(?=\d\d).{3,}", "b2aa")
710 assert re.search(r"b(?<=\d.)a", "2ba")
711 assert not re.search(r"b(?<=\d.)a", "ba")
712
713 def test_search_simple_assert_not(self):
714 import re
715 assert re.search(r"b(?<!\d.)a", "aba")
716 assert re.search(r"b(?<!\d.)a", "ba")
717 assert not re.search(r"b(?<!\d.)a", "11ba")
718
719
720 class AppTestMarksStack:
721
722 spaceconfig = {'usemodules': ['itertools']}
723
724 def test_mark_stack_branch(self):
725 import re
726 m = re.match("b(.)a|b.b", "bob")
727 assert None == m.group(1)
728 assert None == m.lastindex
729
730 def test_mark_stack_repeat_one(self):
731 import re
732 m = re.match("\d+1((2)|(3))4", "2212413")
733 assert ("2", "2", None) == m.group(1, 2, 3)
734 assert 1 == m.lastindex
735
736 def test_mark_stack_min_repeat_one(self):
737 import re
738 m = re.match("\d+?1((2)|(3))44", "221341244")
739 assert ("2", "2", None) == m.group(1, 2, 3)
740 assert 1 == m.lastindex
741
742 def test_mark_stack_max_until(self):
743 import re
744 m = re.match("(\d)+1((2)|(3))4", "2212413")
745 assert ("2", "2", None) == m.group(2, 3, 4)
746 assert 2 == m.lastindex
747
748 def test_mark_stack_min_until(self):
749 import re
750 m = re.match("(\d)+?1((2)|(3))44", "221341244")
751 assert ("2", "2", None) == m.group(2, 3, 4)
752 assert 2 == m.lastindex
753
754 def test_bug_725149(self):
755 # mark_stack_base restoring before restoring marks
756 # test copied from CPython test
757 import re
758 assert re.match('(a)(?:(?=(b)*)c)*', 'abb').groups() == ('a', None)
759 assert re.match('(a)((?!(b)*))*', 'abb').groups() == ('a', None, None)
760
761
762 class AppTestOpcodes:
763 spaceconfig = dict(usemodules=('_locale',))
764
765 def setup_class(cls):
766 if cls.runappdirect:
767 py.test.skip("can only be run on py.py: _sre opcodes don't match")
768 # This imports support_test_sre as the global "s"
769 init_app_test(cls, cls.space)
770
771 def test_length_optimization(self):
772 s = self.s
773 pattern = "bla"
774 opcodes = [s.OPCODES["info"], 3, 3, len(pattern)] \
775 + s.encode_literal(pattern) + [s.OPCODES["success"]]
776 s.assert_no_match(opcodes, ["b", "bl", "ab"])
777
778 def test_literal(self):
779 s = self.s
780 opcodes = s.encode_literal("bla") + [s.OPCODES["success"]]
781 s.assert_no_match(opcodes, ["bl", "blu"])
782 s.assert_match(opcodes, ["bla", "blab", "cbla", "bbla"])
783
784 def test_not_literal(self):
785 s = self.s
786 opcodes = s.encode_literal("b") \
787 + [s.OPCODES["not_literal"], ord("a"), s.OPCODES["success"]]
788 s.assert_match(opcodes, ["bx", "ababy"])
789 s.assert_no_match(opcodes, ["ba", "jabadu"])
790
791 def test_unknown(self):
792 s = self.s
793 raises(RuntimeError, s.search, [55555], "b")
794
795 def test_at_beginning(self):
796 s = self.s
797 for atname in ["at_beginning", "at_beginning_string"]:
798 opcodes = [s.OPCODES["at"], s.ATCODES[atname]] \
799 + s.encode_literal("bla") + [s.OPCODES["success"]]
800 s.assert_match(opcodes, "bla")
801 s.assert_no_match(opcodes, "abla")
802
803 def test_at_beginning_line(self):
804 s = self.s
805 opcodes = [s.OPCODES["at"], s.ATCODES["at_beginning_line"]] \
806 + s.encode_literal("bla") + [s.OPCODES["success"]]
807 s.assert_match(opcodes, ["bla", "x\nbla"])
808 s.assert_no_match(opcodes, ["abla", "abla\nubla"])
809
810 def test_at_end(self):
811 s = self.s
812 opcodes = s.encode_literal("bla") \
813 + [s.OPCODES["at"], s.ATCODES["at_end"], s.OPCODES["success"]]
814 s.assert_match(opcodes, ["bla", "bla\n"])
815 s.assert_no_match(opcodes, ["blau", "abla\nblau"])
816
817 def test_at_end_line(self):
818 s = self.s
819 opcodes = s.encode_literal("bla") \
820 + [s.OPCODES["at"], s.ATCODES["at_end_line"], s.OPCODES["success"]]
821 s.assert_match(opcodes, ["bla\n", "bla\nx", "bla"])
822 s.assert_no_match(opcodes, ["blau"])
823
824 def test_at_end_string(self):
825 s = self.s
826 opcodes = s.encode_literal("bla") \
827 + [s.OPCODES["at"], s.ATCODES["at_end_string"], s.OPCODES["success"]]
828 s.assert_match(opcodes, "bla")
829 s.assert_no_match(opcodes, ["blau", "bla\n"])
830
831 def test_at_boundary(self):
832 s = self.s
833 for atname in "at_boundary", "at_loc_boundary", "at_uni_boundary":
834 opcodes = s.encode_literal("bla") \
835 + [s.OPCODES["at"], s.ATCODES[atname], s.OPCODES["success"]]
836 s.assert_match(opcodes, ["bla", "bla ha", "bla,x"])
837 s.assert_no_match(opcodes, ["blaja", ""])
838 opcodes = [s.OPCODES["at"], s.ATCODES[atname]] \
839 + s.encode_literal("bla") + [s.OPCODES["success"]]
840 assert s.search(opcodes, "bla")
841 s.assert_no_match(opcodes, "")
842
843 def test_at_non_boundary(self):
844 s = self.s
845 for atname in "at_non_boundary", "at_loc_non_boundary", "at_uni_non_boundary":
846 opcodes = s.encode_literal("bla") \
847 + [s.OPCODES["at"], s.ATCODES[atname], s.OPCODES["success"]]
848 assert s.search(opcodes, "blan")
849 s.assert_no_match(opcodes, ["bla ja", "bla"])
850
851 def test_at_loc_boundary(self):
852 s = self.s
853 import locale
854 try:
855 s.void_locale()
856 opcodes1 = s.encode_literal("bla") \
857 + [s.OPCODES["at"], s.ATCODES["at_loc_boundary"], s.OPCODES["success"]]
858 opcodes2 = s.encode_literal("bla") \
859 + [s.OPCODES["at"], s.ATCODES["at_loc_non_boundary"], s.OPCODES["success"]]
860 assert s.search(opcodes1, "bla\xFC")
861 s.assert_no_match(opcodes2, "bla\xFC")
862 oldlocale = locale.setlocale(locale.LC_ALL)
863 locale.setlocale(locale.LC_ALL, "de_DE")
864 s.assert_no_match(opcodes1, "bla\xFC")
865 assert s.search(opcodes2, "bla\xFC")
866 locale.setlocale(locale.LC_ALL, oldlocale)
867 except locale.Error:
868 # skip test
869 skip("locale error")
870
871 def test_at_uni_boundary(self):
872 s = self.s
873 UPPER_PI = "\u03a0"
874 LOWER_PI = "\u03c0"
875 opcodes = s.encode_literal("bl") + [s.OPCODES["any"], s.OPCODES["at"],
876 s.ATCODES["at_uni_boundary"], s.OPCODES["success"]]
877 s.assert_match(opcodes, ["bla ha", "bl%s ja" % UPPER_PI])
878 s.assert_no_match(opcodes, ["bla%s" % LOWER_PI])
879 opcodes = s.encode_literal("bl") + [s.OPCODES["any"], s.OPCODES["at"],
880 s.ATCODES["at_uni_non_boundary"], s.OPCODES["success"]]
881 s.assert_match(opcodes, ["blaha", "bl%sja" % UPPER_PI])
882
883 def test_category_loc_word(self):
884 s = self.s
885 import locale
886 try:
887 s.void_locale()
888 opcodes1 = s.encode_literal("b") \
889 + [s.OPCODES["category"], s.CHCODES["category_loc_word"], s.OPCODES["success"]]
890 opcodes2 = s.encode_literal("b") \
891 + [s.OPCODES["category"], s.CHCODES["category_loc_not_word"], s.OPCODES["success"]]
892 assert not s.search(opcodes1, u"b\xFC")
893 assert s.search(opcodes2, u"b\xFC")
894 locale.setlocale(locale.LC_ALL, "de_DE")
895 assert s.search(opcodes1, u"b\xFC")
896 assert not s.search(opcodes2, u"b\xFC")
897 s.void_locale()
898 except locale.Error:
899 # skip test
900 skip("locale error")
901
902 def test_any(self):
903 s = self.s
904 opcodes = s.encode_literal("b") + [s.OPCODES["any"]] \
905 + s.encode_literal("a") + [s.OPCODES["success"]]
906 s.assert_match(opcodes, ["b a", "bla", "bboas"])
907 s.assert_no_match(opcodes, ["b\na", "oba", "b"])
908
909 def test_any_all(self):
910 s = self.s
911 opcodes = s.encode_literal("b") + [s.OPCODES["any_all"]] \
912 + s.encode_literal("a") + [s.OPCODES["success"]]
913 s.assert_match(opcodes, ["b a", "bla", "bboas", "b\na"])
914 s.assert_no_match(opcodes, ["oba", "b"])
915
916 def test_in_failure(self):
917 s = self.s
918 opcodes = s.encode_literal("b") + [s.OPCODES["in"], 2, s.OPCODES["failure"]] \
919 + s.encode_literal("a") + [s.OPCODES["success"]]
920 s.assert_no_match(opcodes, ["ba", "bla"])
921
922 def test_in_literal(self):
923 s = self.s
924 opcodes = s.encode_literal("b") + [s.OPCODES["in"], 7] \
925 + s.encode_literal("la") + [s.OPCODES["failure"], s.OPCODES["failure"]] \
926 + s.encode_literal("a") + [s.OPCODES["success"]]
927 s.assert_match(opcodes, ["bla", "baa", "blbla"])
928 s.assert_no_match(opcodes, ["ba", "bja", "blla"])
929
930 def test_in_category(self):
931 s = self.s
932 opcodes = s.encode_literal("b") + [s.OPCODES["in"], 6, s.OPCODES["category"],
933 s.CHCODES["category_digit"], s.OPCODES["category"], s.CHCODES["category_space"],
934 s.OPCODES["failure"]] + s.encode_literal("a") + [s.OPCODES["success"]]
935 s.assert_match(opcodes, ["b1a", "b a", "b4b\tas"])
936 s.assert_no_match(opcodes, ["baa", "b5"])
937
938 def test_in_charset_ucs2(self):
939 import _sre
940 if _sre.CODESIZE != 2:
941 return
942 s = self.s
943 # charset bitmap for characters "l" and "h"
944 bitmap = 6 * [0] + [4352] + 9 * [0]
945 opcodes = s.encode_literal("b") + [s.OPCODES["in"], 19, s.OPCODES["charset"]] \
946 + bitmap + [s.OPCODES["failure"]] + s.encode_literal("a") + [s.OPCODES["success"]]
947 s.assert_match(opcodes, ["bla", "bha", "blbha"])
948 s.assert_no_match(opcodes, ["baa", "bl"])
949
950 def _test_in_bigcharset_ucs2(self):
951 # disabled because this actually only works on big-endian machines
952 if _sre.CODESIZE != 2:
953 return
954 s = self.s
955 # constructing bigcharset for lowercase pi (\u03c0)
956 UPPER_PI = u"\u03a0"
957 LOWER_PI = u"\u03c0"
958 bitmap = 6 * [0] + [4352] + 9 * [0]
959 opcodes = s.encode_literal("b") + [s.OPCODES["in"], 164, s.OPCODES["bigcharset"], 2] \
960 + [0, 1] + 126 * [0] \
961 + 16 * [0] \
962 + 12 * [0] + [1] + 3 * [0] \
963 + [s.OPCODES["failure"]] + s.encode_literal("a") + [s.OPCODES["success"]]
964 s.assert_match(opcodes, [u"b%sa" % LOWER_PI])
965 s.assert_no_match(opcodes, [u"b%sa" % UPPER_PI])
966
967 # XXX bigcharset test for ucs4 missing here
968
969 def test_in_range(self):
970 s = self.s
971 opcodes = s.encode_literal("b") + [s.OPCODES["in"], 5, s.OPCODES["range"],
972 ord("1"), ord("9"), s.OPCODES["failure"]] \
973 + s.encode_literal("a") + [s.OPCODES["success"]]
974 s.assert_match(opcodes, ["b1a", "b56b7aa"])
975 s.assert_no_match(opcodes, ["baa", "b5"])
976
977 def test_in_negate(self):
978 s = self.s
979 opcodes = s.encode_literal("b") + [s.OPCODES["in"], 7, s.OPCODES["negate"]] \
980 + s.encode_literal("la") + [s.OPCODES["failure"]] \
981 + s.encode_literal("a") + [s.OPCODES["success"]]
982 s.assert_match(opcodes, ["b1a", "bja", "bubua"])
983 s.assert_no_match(opcodes, ["bla", "baa", "blbla"])
984
985 def test_literal_ignore(self):
986 s = self.s
987 opcodes = s.encode_literal("b") \
988 + [s.OPCODES["literal_ignore"], ord("a"), s.OPCODES["success"]]
989 s.assert_match(opcodes, ["ba", "bA"])
990 s.assert_no_match(opcodes, ["bb", "bu"])
991
992 def test_not_literal_ignore(self):
993 s = self.s
994 UPPER_PI = "\u03a0"
995 opcodes = s.encode_literal("b") \
996 + [s.OPCODES["not_literal_ignore"], ord("a"), s.OPCODES["success"]]
997 s.assert_match(opcodes, ["bb", "bu", "b%s" % UPPER_PI])
998 s.assert_no_match(opcodes, ["ba", "bA"])
999
1000 def test_in_ignore(self):
1001 s = self.s
1002 opcodes = s.encode_literal("b") + [s.OPCODES["in_ignore"], 8] \
1003 + s.encode_literal("abc") + [s.OPCODES["failure"]] \
1004 + s.encode_literal("a") + [s.OPCODES["success"]]
1005 s.assert_match(opcodes, ["baa", "bAa", "bbbBa"])
1006 s.assert_no_match(opcodes, ["ba", "bja", "blla"])
1007
1008 def test_in_jump_info(self):
1009 s = self.s
1010 for opname in "jump", "info":
1011 opcodes = s.encode_literal("b") \
1012 + [s.OPCODES[opname], 3, s.OPCODES["failure"], s.OPCODES["failure"]] \
1013 + s.encode_literal("a") + [s.OPCODES["success"]]
1014 s.assert_match(opcodes, "ba")
1015
1016 def _test_mark(self):
1017 s = self.s
1018 # XXX need to rewrite this implementation-independent
1019 opcodes = s.encode_literal("a") + [s.OPCODES["mark"], 0] \
1020 + s.encode_literal("b") + [s.OPCODES["mark"], 1, s.OPCODES["success"]]
1021 state = self.create_state("abc")
1022 _sre._sre_search(state, opcodes)
1023 assert 1 == state.lastindex
1024 assert 1 == state.lastmark
1025 # NB: the following are indexes from the start of the match
1026 assert [1, 2] == state.marks
1027
1028 def test_branch(self):
1029 s = self.s
1030 opcodes = [s.OPCODES["branch"], 7] + s.encode_literal("ab") \
1031 + [s.OPCODES["jump"], 9, 7] + s.encode_literal("cd") \
1032 + [s.OPCODES["jump"], 2, s.OPCODES["failure"], s.OPCODES["success"]]
1033 s.assert_match(opcodes, ["ab", "cd"])
1034 s.assert_no_match(opcodes, ["aacas", "ac", "bla"])
1035
1036 def test_repeat_one(self):
1037 s = self.s
1038 opcodes = [s.OPCODES["repeat_one"], 6, 1, self.s.MAXREPEAT] + s.encode_literal("a") \
1039 + [s.OPCODES["success"]] + s.encode_literal("ab") + [s.OPCODES["success"]]
1040 s.assert_match(opcodes, ["aab", "aaaab"])
1041 s.assert_no_match(opcodes, ["ab", "a"])
1042
1043 def test_min_repeat_one(self):
1044 s = self.s
1045 opcodes = [s.OPCODES["min_repeat_one"], 5, 1, self.s.MAXREPEAT, s.OPCODES["any"]] \
1046 + [s.OPCODES["success"]] + s.encode_literal("b") + [s.OPCODES["success"]]
1047 s.assert_match(opcodes, ["aab", "ardb", "bb"])
1048 s.assert_no_match(opcodes, ["b"])
1049
1050 def test_repeat_maximizing(self):
1051 s = self.s
1052 opcodes = [s.OPCODES["repeat"], 5, 1, self.s.MAXREPEAT] + s.encode_literal("a") \
1053 + [s.OPCODES["max_until"]] + s.encode_literal("b") + [s.OPCODES["success"]]
1054 s.assert_match(opcodes, ["ab", "aaaab", "baabb"])
1055 s.assert_no_match(opcodes, ["aaa", "", "ac"])
1056
1057 def test_max_until_zero_width_match(self):
1058 # re.compile won't compile prospective zero-with matches (all of them?),
1059 # so we can only produce an example by directly constructing bytecodes.
1060 # CPython 2.3 fails with a recursion limit exceeded error here.
1061 import sys
1062 if not sys.version_info[:2] == (2, 3):
1063 s = self.s
1064 opcodes = [s.OPCODES["repeat"], 10, 1, self.s.MAXREPEAT, s.OPCODES["repeat_one"],
1065 6, 0, self.s.MAXREPEAT] + s.encode_literal("a") + [s.OPCODES["success"],
1066 s.OPCODES["max_until"], s.OPCODES["success"]]
1067 s.assert_match(opcodes, ["ab", "bb"])
1068 assert "" == s.search(opcodes, "bb").group(0)
1069
1070 def test_repeat_minimizing(self):
1071 s = self.s
1072 opcodes = [s.OPCODES["repeat"], 4, 1, self.s.MAXREPEAT, s.OPCODES["any"],
1073 s.OPCODES["min_until"]] + s.encode_literal("b") + [s.OPCODES["success"]]
1074 s.assert_match(opcodes, ["ab", "aaaab", "baabb"])
1075 s.assert_no_match(opcodes, ["b"])
1076 assert "aab" == s.search(opcodes, "aabb").group(0)
1077
1078 def test_groupref(self):
1079 s = self.s
1080 opcodes = [s.OPCODES["mark"], 0, s.OPCODES["any"], s.OPCODES["mark"], 1] \
1081 + s.encode_literal("a") + [s.OPCODES["groupref"], 0, s.OPCODES["success"]]
1082 s.assert_match(opcodes, ["bab", "aaa", "dad"])
1083 s.assert_no_match(opcodes, ["ba", "bad", "baad"])
1084
1085 def test_groupref_ignore(self):
1086 s = self.s
1087 opcodes = [s.OPCODES["mark"], 0, s.OPCODES["any"], s.OPCODES["mark"], 1] \
1088 + s.encode_literal("a") + [s.OPCODES["groupref_ignore"], 0, s.OPCODES["success"]]
1089 s.assert_match(opcodes, ["bab", "baB", "Dad"])
1090 s.assert_no_match(opcodes, ["ba", "bad", "baad"])
1091
1092 def test_assert(self):
1093 s = self.s
1094 opcodes = s.encode_literal("a") + [s.OPCODES["assert"], 4, 0] \
1095 + s.encode_literal("b") + [s.OPCODES["success"], s.OPCODES["success"]]
1096 assert "a" == s.search(opcodes, "ab").group(0)
1097 s.assert_no_match(opcodes, ["a", "aa"])
1098
1099 def test_assert_not(self):
1100 s = self.s
1101 opcodes = s.encode_literal("a") + [s.OPCODES["assert_not"], 4, 0] \
1102 + s.encode_literal("b") + [s.OPCODES["success"], s.OPCODES["success"]]
1103 assert "a" == s.search(opcodes, "ac").group(0)
1104 s.assert_match(opcodes, ["a"])
1105 s.assert_no_match(opcodes, ["ab"])
1106
1107
1108 class AppTestOptimizations:
1109 """These tests try to trigger optmized edge cases."""
1110
1111 spaceconfig = {'usemodules': ['itertools']}
1112
1113 def test_match_length_optimization(self):
1114 import re
1115 assert None == re.match("bla", "blub")
1116
1117 def test_fast_search(self):
1118 import re
1119 assert None == re.search("bl", "abaub")
1120 assert None == re.search("bl", "b")
1121 assert ["bl", "bl"] == re.findall("bl", "blbl")
1122 assert ["a", "u"] == re.findall("bl(.)", "blablu")
1123
1124 def test_branch_literal_shortcut(self):
1125 import re
1126 assert None == re.search("bl|a|c", "hello")
1127
1128 def test_literal_search(self):
1129 import re
1130 assert re.search("b(\d)", "ababbbab1")
1131 assert None == re.search("b(\d)", "ababbbab")
1132
1133 def test_repeat_one_literal_tail(self):
1134 import re
1135 assert re.search(".+ab", "wowowowawoabwowo")
1136 assert None == re.search(".+ab", "wowowaowowo")
1137
1138 def test_split_empty(self):
1139 import re
1140 assert re.split('', '') == ['', '']
1141 assert re.split('', 'ab') == ['', 'a', 'b', '']
1142 assert re.split('a*', '') == ['', '']
1143 assert re.split('a*', 'a') == ['', '', '']
1144 assert re.split('a*', 'aa') == ['', '', '']
1145 assert re.split('a*', 'baaac') == ['', 'b', '', 'c', '']
1146
1147 def test_type_names(self):
1148 import re
1149 assert repr(re.Pattern) == "<class 're.Pattern'>"
1150 assert repr(re.Match) == "<class 're.Match'>"
1151
1152 class AppTestUnicodeExtra:
1153 def test_string_attribute(self):
1154 import re
1155 match = re.search(u"\u1234", u"\u1233\u1234\u1235")
1156 assert match.string == u"\u1233\u1234\u1235"
1157 # check ascii version too
1158 match = re.search(u"a", u"bac")
1159 assert match.string == u"bac"
1160
1161 def test_string_attribute_is_original_string(self):
1162 import re
1163 class mystr(type(u"")):
1164 pass
1165 s = mystr(u"\u1233\u1234\u1235")
1166 match = re.search(u"\u1234", s)
1167 assert match.string is s
1168
1169 def test_match_start(self):
1170 import re
1171 match = re.search(u"\u1234", u"\u1233\u1234\u1235")
1172 assert match.start() == 1
1173
1174 def test_match_repr_span(self):
1175 import re
1176 match = re.match(u"\u1234", u"\u1234")
1177 assert match.span() == (0, 1)
1178 assert "span=(0, 1), match='\u1234'" in repr(match)
1179
1180 def test_match_repr_truncation(self):
1181 import re
1182 s = "xy" + u"\u1234" * 50
1183 match = re.match(s, s)
1184 # this used to produce invalid utf-8 by truncating repr(s)
1185 # after 50 bytes
1186 assert "span=(0, 52), match=" + repr(s)[:50] + ">" in repr(match)
1187
1188 def test_pattern_repr_truncation(self):
1189 import re
1190 s = "xy" + u"\u1234" * 200
1191 pattern = re.compile(s)
1192 # this used to produce invalid utf-8 by truncating repr(s)
1193 # after 200 bytes
1194 assert repr(pattern) == "re.compile(%s)" % (repr(s)[:200],)
1195
1196 def test_subx_unusual_types_no_match(self):
1197 # issue #3515
1198 import re
1199 result = re.sub(b"x", lambda x: 1/0, memoryview(b"yz"))
1200 assert type(result) is bytes
1201 assert result == b"yz"
1202 class U(str): pass
1203 result = re.sub(u"x", lambda x: 1/0, U(u"yz"))
1204 assert type(result) is str
1205 assert result == u"yz"
1206 class B(bytes): pass
1207 result = re.sub(b"x", lambda x: 1/0, B(b"yz"))
1208 assert type(result) is bytes
1209 assert result == b"yz"
1210
1211 def test_bug_40736(self):
1212 # Passing a non-string/bytes-like object to re.search() must raise
1213 # TypeError with a message mentioning the actual type, not a misleading
1214 # "can't use a string pattern on a bytes-like object" message.
1215 import re
1216 try:
1217 re.search("x*", 5)
1218 except TypeError as e:
1219 assert "got 'int'" in str(e), str(e)
1220 else:
1221 raise AssertionError("expected TypeError")
1222 try:
1223 re.search("x*", None)
1224 except TypeError as e:
1225 assert "got 'NoneType'" in str(e), str(e)
1226 else:
1227 raise AssertionError("expected TypeError")