blob: 1eea12fee82cc5b76a8e0cecd50c0a5b16f80428 [file] [log] [blame]
Fredrik Lundh143328b2000-09-02 11:03:34 +00001# SRE test harness for the Python regression suite
2
3# this is based on test_re.py, but uses a test function instead
4# of all those asserts
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +00005
6import sys
7sys.path=['.']+sys.path
8
9from test_support import verbose, TestFailed
10import sre
11import sys, os, string, traceback
12
Fredrik Lundh143328b2000-09-02 11:03:34 +000013#
14# test support
15
16def test(expression, result, exception=None):
17 try:
18 r = eval(expression)
19 except:
20 if exception:
21 if not isinstance(sys.exc_value, exception):
22 print expression, "FAILED"
23 # display name, not actual value
24 if exception is sre.error:
25 print "expected", "sre.error"
26 else:
27 print "expected", exception.__name__
28 print "got", sys.exc_type.__name__, str(sys.exc_value)
29 else:
30 print expression, "FAILED"
31 traceback.print_exc(file=sys.stdout)
32 else:
33 if exception:
34 print expression, "FAILED"
35 if exception is sre.error:
36 print "expected", "sre.error"
37 else:
38 print "expected", exception.__name__
39 print "got result", repr(r)
40 else:
41 if r != result:
42 print expression, "FAILED"
43 print "expected", repr(result)
44 print "got result", repr(r)
45
46if verbose:
47 print 'Running tests on character literals'
48
Fredrik Lundh510c97b2000-09-02 16:36:57 +000049for i in [0, 8, 16, 32, 64, 127, 128, 255]:
Fredrik Lundh143328b2000-09-02 11:03:34 +000050 test(r"""sre.match("\%03o" % i, chr(i)) != None""", 1)
51 test(r"""sre.match("\%03o0" % i, chr(i)+"0") != None""", 1)
52 test(r"""sre.match("\%03o8" % i, chr(i)+"8") != None""", 1)
53 test(r"""sre.match("\x%02x" % i, chr(i)) != None""", 1)
54 test(r"""sre.match("\x%02x0" % i, chr(i)+"0") != None""", 1)
55 test(r"""sre.match("\x%02xz" % i, chr(i)+"z") != None""", 1)
56test(r"""sre.match("\911", "")""", None, sre.error)
57
58#
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +000059# Misc tests from Tim Peters' re.doc
60
61if verbose:
62 print 'Running tests on sre.search and sre.match'
63
Fredrik Lundh143328b2000-09-02 11:03:34 +000064test(r"""sre.search('x*', 'axx').span(0)""", (0, 0))
65test(r"""sre.search('x*', 'axx').span()""", (0, 0))
66test(r"""sre.search('x+', 'axx').span(0)""", (1, 3))
67test(r"""sre.search('x+', 'axx').span()""", (1, 3))
68test(r"""sre.search('x', 'aaa')""", None)
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +000069
Fredrik Lundh143328b2000-09-02 11:03:34 +000070test(r"""sre.match('a*', 'xxx').span(0)""", (0, 0))
71test(r"""sre.match('a*', 'xxx').span()""", (0, 0))
72test(r"""sre.match('x*', 'xxxa').span(0)""", (0, 3))
73test(r"""sre.match('x*', 'xxxa').span()""", (0, 3))
74test(r"""sre.match('a+', 'xxx')""", None)
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +000075
Fredrik Lundh510c97b2000-09-02 16:36:57 +000076# bug 113254
77test(r"""sre.match('(a)|(b)', 'b').start(1)""", -1)
78test(r"""sre.match('(a)|(b)', 'b').end(1)""", -1)
79test(r"""sre.match('(a)|(b)', 'b').span(1)""", (-1, -1))
80
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +000081if verbose:
82 print 'Running tests on sre.sub'
83
Fredrik Lundh143328b2000-09-02 11:03:34 +000084test(r"""sre.sub("(?i)b+", "x", "bbbb BBBB")""", 'x x')
Fredrik Lundh6f013982000-07-03 18:44:21 +000085
Fredrik Lundh143328b2000-09-02 11:03:34 +000086def bump_num(matchobj):
87 int_value = int(matchobj.group(0))
88 return str(int_value + 1)
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +000089
Fredrik Lundh143328b2000-09-02 11:03:34 +000090test(r"""sre.sub(r'\d+', bump_num, '08.2 -2 23x99y')""", '9.3 -3 24x100y')
91test(r"""sre.sub(r'\d+', bump_num, '08.2 -2 23x99y', 3)""", '9.3 -3 23x99y')
Fredrik Lundh6f013982000-07-03 18:44:21 +000092
Fredrik Lundh143328b2000-09-02 11:03:34 +000093test(r"""sre.sub('.', lambda m: r"\n", 'x')""", '\\n')
94test(r"""sre.sub('.', r"\n", 'x')""", '\n')
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +000095
Fredrik Lundh143328b2000-09-02 11:03:34 +000096s = r"\1\1"
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +000097
Fredrik Lundh143328b2000-09-02 11:03:34 +000098test(r"""sre.sub('(.)', s, 'x')""", 'xx')
99test(r"""sre.sub('(.)', sre.escape(s), 'x')""", s)
100test(r"""sre.sub('(.)', lambda m: s, 'x')""", s)
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000101
Fredrik Lundh143328b2000-09-02 11:03:34 +0000102test(r"""sre.sub('(?P<a>x)', '\g<a>\g<a>', 'xx')""", 'xxxx')
103test(r"""sre.sub('(?P<a>x)', '\g<a>\g<1>', 'xx')""", 'xxxx')
104test(r"""sre.sub('(?P<unk>x)', '\g<unk>\g<unk>', 'xx')""", 'xxxx')
105test(r"""sre.sub('(?P<unk>x)', '\g<1>\g<1>', 'xx')""", 'xxxx')
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000106
Fredrik Lundh143328b2000-09-02 11:03:34 +0000107test(r"""sre.sub('a', r'\t\n\v\r\f\a\b\B\Z\a\A\w\W\s\S\d\D', 'a')""", '\t\n\v\r\f\a\b\\B\\Z\a\\A\\w\\W\\s\\S\\d\\D')
108test(r"""sre.sub('a', '\t\n\v\r\f\a', 'a')""", '\t\n\v\r\f\a')
109test(r"""sre.sub('a', '\t\n\v\r\f\a', 'a')""", (chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7)))
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000110
Fredrik Lundh143328b2000-09-02 11:03:34 +0000111test(r"""sre.sub('^\s*', 'X', 'test')""", 'Xtest')
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000112
Fredrik Lundh143328b2000-09-02 11:03:34 +0000113# qualified sub
114test(r"""sre.sub('a', 'b', 'aaaaa')""", 'bbbbb')
115test(r"""sre.sub('a', 'b', 'aaaaa', 1)""", 'baaaa')
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000116
117if verbose:
118 print 'Running tests on symbolic references'
119
Fredrik Lundh143328b2000-09-02 11:03:34 +0000120test(r"""sre.sub('(?P<a>x)', '\g<a', 'xx')""", None, sre.error)
121test(r"""sre.sub('(?P<a>x)', '\g<', 'xx')""", None, sre.error)
122test(r"""sre.sub('(?P<a>x)', '\g', 'xx')""", None, sre.error)
123test(r"""sre.sub('(?P<a>x)', '\g<a a>', 'xx')""", None, sre.error)
124test(r"""sre.sub('(?P<a>x)', '\g<1a1>', 'xx')""", None, sre.error)
125test(r"""sre.sub('(?P<a>x)', '\g<ab>', 'xx')""", None, IndexError)
126test(r"""sre.sub('(?P<a>x)|(?P<b>y)', '\g<b>', 'xx')""", None, sre.error)
127test(r"""sre.sub('(?P<a>x)|(?P<b>y)', '\\2', 'xx')""", None, sre.error)
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000128
129if verbose:
130 print 'Running tests on sre.subn'
131
Fredrik Lundh143328b2000-09-02 11:03:34 +0000132test(r"""sre.subn("(?i)b+", "x", "bbbb BBBB")""", ('x x', 2))
133test(r"""sre.subn("b+", "x", "bbbb BBBB")""", ('x BBBB', 1))
134test(r"""sre.subn("b+", "x", "xyz")""", ('xyz', 0))
135test(r"""sre.subn("b*", "x", "xyz")""", ('xxxyxzx', 4))
136test(r"""sre.subn("b*", "x", "xyz", 2)""", ('xxxyz', 2))
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000137
138if verbose:
139 print 'Running tests on sre.split'
Fredrik Lundh6f013982000-07-03 18:44:21 +0000140
Fredrik Lundh143328b2000-09-02 11:03:34 +0000141test(r"""sre.split(":", ":a:b::c")""", ['', 'a', 'b', '', 'c'])
142test(r"""sre.split(":*", ":a:b::c")""", ['', 'a', 'b', 'c'])
143test(r"""sre.split("(:*)", ":a:b::c")""", ['', ':', 'a', ':', 'b', '::', 'c'])
144test(r"""sre.split("(?::*)", ":a:b::c")""", ['', 'a', 'b', 'c'])
145test(r"""sre.split("(:)*", ":a:b::c")""", ['', ':', 'a', ':', 'b', ':', 'c'])
146test(r"""sre.split("([b:]+)", ":a:b::c")""", ['', ':', 'a', ':b::', 'c'])
147test(r"""sre.split("(b)|(:+)", ":a:b::c")""",
148 ['', None, ':', 'a', None, ':', '', 'b', None, '', None, '::', 'c'])
149test(r"""sre.split("(?:b)|(?::+)", ":a:b::c")""", ['', 'a', '', '', 'c'])
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000150
Fredrik Lundh143328b2000-09-02 11:03:34 +0000151test(r"""sre.split(":", ":a:b::c", 2)""", ['', 'a', 'b::c'])
152test(r"""sre.split(':', 'a:b:c:d', 2)""", ['a', 'b', 'c:d'])
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000153
Fredrik Lundh143328b2000-09-02 11:03:34 +0000154test(r"""sre.split("(:)", ":a:b::c", 2)""", ['', ':', 'a', ':', 'b::c'])
155test(r"""sre.split("(:*)", ":a:b::c", 2)""", ['', ':', 'a', ':', 'b::c'])
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000156
157if verbose:
158 print "Running tests on sre.findall"
159
Fredrik Lundh143328b2000-09-02 11:03:34 +0000160test(r"""sre.findall(":+", "abc")""", [])
161test(r"""sre.findall(":+", "a:b::c:::d")""", [":", "::", ":::"])
162test(r"""sre.findall("(:+)", "a:b::c:::d")""", [":", "::", ":::"])
163test(r"""sre.findall("(:)(:*)", "a:b::c:::d")""",
164 [(":", ""), (":", ":"), (":", "::")])
165test(r"""sre.findall("(a)|(b)", "abc")""", [("a", ""), ("", "b")])
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000166
167if verbose:
168 print "Running tests on sre.match"
169
Fredrik Lundh143328b2000-09-02 11:03:34 +0000170test(r"""sre.match('a', 'a').groups()""", ())
171test(r"""sre.match('(a)', 'a').groups()""", ('a',))
172test(r"""sre.match('(a)', 'a').group(0)""", 'a')
173test(r"""sre.match('(a)', 'a').group(1)""", 'a')
174test(r"""sre.match('(a)', 'a').group(1, 1)""", ('a', 'a'))
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000175
Fredrik Lundh143328b2000-09-02 11:03:34 +0000176pat = sre.compile('((a)|(b))(c)?')
177test(r"""pat.match('a').groups()""", ('a', 'a', None, None))
178test(r"""pat.match('b').groups()""", ('b', None, 'b', None))
179test(r"""pat.match('ac').groups()""", ('a', 'a', None, 'c'))
180test(r"""pat.match('bc').groups()""", ('b', None, 'b', 'c'))
181test(r"""pat.match('bc').groups("")""", ('b', "", 'b', 'c'))
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000182
Fredrik Lundh143328b2000-09-02 11:03:34 +0000183pat = sre.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
184test(r"""pat.match('a').group(1, 2, 3)""", ('a', None, None))
185test(r"""pat.match('b').group('a1', 'b2', 'c3')""", (None, 'b', None))
186test(r"""pat.match('ac').group(1, 'b2', 3)""", ('a', None, 'c'))
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000187
188if verbose:
189 print "Running tests on sre.escape"
190
Fredrik Lundh143328b2000-09-02 11:03:34 +0000191p = ""
192for i in range(0, 256):
193 p = p + chr(i)
194 test(r"""sre.match(sre.escape(chr(i)), chr(i)) != None""", 1)
195 test(r"""sre.match(sre.escape(chr(i)), chr(i)).span()""", (0,1))
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000196
Fredrik Lundh143328b2000-09-02 11:03:34 +0000197pat = sre.compile(sre.escape(p))
198test(r"""pat.match(p) != None""", 1)
199test(r"""pat.match(p).span()""", (0,256))
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000200
201if verbose:
202 print 'Pickling a SRE_Pattern instance'
203
204try:
205 import pickle
206 pat = sre.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
207 s = pickle.dumps(pat)
208 pat = pickle.loads(s)
209except:
210 print TestFailed, 're module pickle' # expected
211
212try:
213 import cPickle
214 pat = sre.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
215 s = cPickle.dumps(pat)
216 pat = cPickle.loads(s)
217except:
218 print TestFailed, 're module cPickle' # expected
219
Fredrik Lundh143328b2000-09-02 11:03:34 +0000220# constants
221test(r"""sre.I""", sre.IGNORECASE)
222test(r"""sre.L""", sre.LOCALE)
223test(r"""sre.M""", sre.MULTILINE)
224test(r"""sre.S""", sre.DOTALL)
225test(r"""sre.X""", sre.VERBOSE)
226test(r"""sre.T""", sre.TEMPLATE)
227test(r"""sre.U""", sre.UNICODE)
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000228
229for flags in [sre.I, sre.M, sre.X, sre.S, sre.L, sre.T, sre.U]:
230 try:
231 r = sre.compile('^pattern$', flags)
232 except:
233 print 'Exception raised on flag', flags
234
Fredrik Lundh96ab4652000-08-03 16:29:50 +0000235if verbose:
236 print 'Test engine limitations'
237
238# Try nasty case that overflows the straightforward recursive
239# implementation of repeated groups.
Fredrik Lundh143328b2000-09-02 11:03:34 +0000240test(r"""sre.match('(x)*', 50000*'x').span()""", (0, 50000), RuntimeError)
241test(r"""sre.match('(x)*y', 50000*'x'+'y').span()""", (0, 50001), RuntimeError)
242test(r"""sre.match('(x)*?y', 50000*'x'+'y').span()""", (0, 50001), RuntimeError)
Fredrik Lundh96ab4652000-08-03 16:29:50 +0000243
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000244from re_tests import *
245
246if verbose:
247 print 'Running re_tests test suite'
248else:
249 # To save time, only run the first and last 10 tests
250 #tests = tests[:10] + tests[-10:]
Fredrik Lundh6f013982000-07-03 18:44:21 +0000251 pass
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000252
253for t in tests:
254 sys.stdout.flush()
255 pattern=s=outcome=repl=expected=None
256 if len(t)==5:
257 pattern, s, outcome, repl, expected = t
258 elif len(t)==3:
Fredrik Lundh6f013982000-07-03 18:44:21 +0000259 pattern, s, outcome = t
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000260 else:
261 raise ValueError, ('Test tuples should have 3 or 5 fields',t)
262
263 try:
264 obj=sre.compile(pattern)
265 except sre.error:
266 if outcome==SYNTAX_ERROR: pass # Expected a syntax error
Fredrik Lundh6f013982000-07-03 18:44:21 +0000267 else:
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000268 print '=== Syntax error:', t
269 except KeyboardInterrupt: raise KeyboardInterrupt
270 except:
271 print '*** Unexpected error ***', t
272 if verbose:
273 traceback.print_exc(file=sys.stdout)
274 else:
275 try:
276 result=obj.search(s)
277 except (sre.error), msg:
278 print '=== Unexpected exception', t, repr(msg)
279 if outcome==SYNTAX_ERROR:
280 # This should have been a syntax error; forget it.
281 pass
282 elif outcome==FAIL:
283 if result is None: pass # No match, as expected
284 else: print '=== Succeeded incorrectly', t
285 elif outcome==SUCCEED:
286 if result is not None:
287 # Matched, as expected, so now we compute the
288 # result string and compare it to our expected result.
289 start, end = result.span(0)
290 vardict={'found': result.group(0),
291 'groups': result.group(),
292 'flags': result.re.flags}
293 for i in range(1, 100):
294 try:
295 gi = result.group(i)
296 # Special hack because else the string concat fails:
297 if gi is None:
298 gi = "None"
299 except IndexError:
300 gi = "Error"
301 vardict['g%d' % i] = gi
302 for i in result.re.groupindex.keys():
303 try:
304 gi = result.group(i)
305 if gi is None:
306 gi = "None"
307 except IndexError:
308 gi = "Error"
309 vardict[i] = gi
310 repl=eval(repl, vardict)
311 if repl!=expected:
312 print '=== grouping error', t,
313 print repr(repl)+' should be '+repr(expected)
314 else:
315 print '=== Failed incorrectly', t
Fredrik Lundh90a07912000-06-30 07:50:59 +0000316 continue
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000317
318 # Try the match on a unicode string, and check that it
319 # still succeeds.
320 result=obj.search(unicode(s, "latin-1"))
321 if result==None:
322 print '=== Fails on unicode match', t
323
324 # Try the match on a unicode pattern, and check that it
325 # still succeeds.
326 obj=sre.compile(unicode(pattern, "latin-1"))
327 result=obj.search(s)
328 if result==None:
329 print '=== Fails on unicode pattern match', t
330
331 # Try the match with the search area limited to the extent
332 # of the match and see if it still succeeds. \B will
333 # break (because it won't match at the end or start of a
334 # string), so we'll ignore patterns that feature it.
Fredrik Lundh6f013982000-07-03 18:44:21 +0000335
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000336 if pattern[:2]!='\\B' and pattern[-2:]!='\\B':
337 obj=sre.compile(pattern)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000338 result=obj.search(s, result.start(0), result.end(0)+1)
339 if result==None:
340 print '=== Failed on range-limited match', t
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000341
342 # Try the match with IGNORECASE enabled, and check that it
343 # still succeeds.
344 obj=sre.compile(pattern, sre.IGNORECASE)
345 result=obj.search(s)
346 if result==None:
347 print '=== Fails on case-insensitive match', t
348
349 # Try the match with LOCALE enabled, and check that it
350 # still succeeds.
351 obj=sre.compile(pattern, sre.LOCALE)
352 result=obj.search(s)
353 if result==None:
354 print '=== Fails on locale-sensitive match', t
355
Fredrik Lundhc2ed6212000-08-01 13:01:43 +0000356 # Try the match with UNICODE locale enabled, and check
357 # that it still succeeds.
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000358 obj=sre.compile(pattern, sre.UNICODE)
359 result=obj.search(s)
360 if result==None:
361 print '=== Fails on unicode-sensitive match', t