blob: 2f16d291d8b7e049b1bc03be8421f12f3679b762 [file] [log] [blame]
Fredrik Lundh90a07912000-06-30 07:50:59 +00001# FIXME: this is basically test_re.py, with a few minor changes
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +00002
3import sys
4sys.path=['.']+sys.path
5
6from test_support import verbose, TestFailed
7import sre
8import sys, os, string, traceback
9
10# Misc tests from Tim Peters' re.doc
11
12if verbose:
13 print 'Running tests on sre.search and sre.match'
14
15try:
16 assert sre.search('x*', 'axx').span(0) == (0, 0)
17 assert sre.search('x*', 'axx').span() == (0, 0)
18 assert sre.search('x+', 'axx').span(0) == (1, 3)
19 assert sre.search('x+', 'axx').span() == (1, 3)
20 assert sre.search('x', 'aaa') == None
21except:
22 raise TestFailed, "sre.search"
23
24try:
25 assert sre.match('a*', 'xxx').span(0) == (0, 0)
26 assert sre.match('a*', 'xxx').span() == (0, 0)
27 assert sre.match('x*', 'xxxa').span(0) == (0, 3)
28 assert sre.match('x*', 'xxxa').span() == (0, 3)
29 assert sre.match('a+', 'xxx') == None
30except:
31 raise TestFailed, "sre.search"
32
33if verbose:
34 print 'Running tests on sre.sub'
35
36try:
37 assert sre.sub("(?i)b+", "x", "bbbb BBBB") == 'x x'
Fredrik Lundh6f013982000-07-03 18:44:21 +000038
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +000039 def bump_num(matchobj):
40 int_value = int(matchobj.group(0))
41 return str(int_value + 1)
42
43 assert sre.sub(r'\d+', bump_num, '08.2 -2 23x99y') == '9.3 -3 24x100y'
44 assert sre.sub(r'\d+', bump_num, '08.2 -2 23x99y', 3) == '9.3 -3 23x99y'
Fredrik Lundh6f013982000-07-03 18:44:21 +000045
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +000046 assert sre.sub('.', lambda m: r"\n", 'x') == '\\n'
47 assert sre.sub('.', r"\n", 'x') == '\n'
48
49 s = r"\1\1"
50 assert sre.sub('(.)', s, 'x') == 'xx'
Fredrik Lundh6f013982000-07-03 18:44:21 +000051 assert sre.sub('(.)', sre.escape(s), 'x') == s
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +000052 assert sre.sub('(.)', lambda m: s, 'x') == s
53
54 assert sre.sub('(?P<a>x)', '\g<a>\g<a>', 'xx') == 'xxxx'
55 assert sre.sub('(?P<a>x)', '\g<a>\g<1>', 'xx') == 'xxxx'
56 assert sre.sub('(?P<unk>x)', '\g<unk>\g<unk>', 'xx') == 'xxxx'
57 assert sre.sub('(?P<unk>x)', '\g<1>\g<1>', 'xx') == 'xxxx'
58
59 assert 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'
60 assert sre.sub('a', '\t\n\v\r\f\a', 'a') == '\t\n\v\r\f\a'
61 assert sre.sub('a', '\t\n\v\r\f\a', 'a') == (chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7))
62
63 assert sre.sub('^\s*', 'X', 'test') == 'Xtest'
64except AssertionError:
65 raise TestFailed, "sre.sub"
66
67
68try:
69 assert sre.sub('a', 'b', 'aaaaa') == 'bbbbb'
70 assert sre.sub('a', 'b', 'aaaaa', 1) == 'baaaa'
71except AssertionError:
72 raise TestFailed, "qualified sre.sub"
73
74if verbose:
75 print 'Running tests on symbolic references'
76
77try:
78 sre.sub('(?P<a>x)', '\g<a', 'xx')
79except sre.error, reason:
80 pass
81else:
82 raise TestFailed, "symbolic reference"
83
84try:
85 sre.sub('(?P<a>x)', '\g<', 'xx')
86except sre.error, reason:
87 pass
88else:
89 raise TestFailed, "symbolic reference"
90
91try:
92 sre.sub('(?P<a>x)', '\g', 'xx')
93except sre.error, reason:
94 pass
95else:
96 raise TestFailed, "symbolic reference"
97
98try:
99 sre.sub('(?P<a>x)', '\g<a a>', 'xx')
100except sre.error, reason:
101 pass
102else:
103 raise TestFailed, "symbolic reference"
104
105try:
106 sre.sub('(?P<a>x)', '\g<1a1>', 'xx')
107except sre.error, reason:
108 pass
109else:
110 raise TestFailed, "symbolic reference"
111
112try:
113 sre.sub('(?P<a>x)', '\g<ab>', 'xx')
114except IndexError, reason:
115 pass
116else:
117 raise TestFailed, "symbolic reference"
118
119try:
120 sre.sub('(?P<a>x)|(?P<b>y)', '\g<b>', 'xx')
121except sre.error, reason:
122 pass
123else:
124 raise TestFailed, "symbolic reference"
125
126try:
127 sre.sub('(?P<a>x)|(?P<b>y)', '\\2', 'xx')
128except sre.error, reason:
129 pass
130else:
131 raise TestFailed, "symbolic reference"
132
133if verbose:
134 print 'Running tests on sre.subn'
135
136try:
137 assert sre.subn("(?i)b+", "x", "bbbb BBBB") == ('x x', 2)
138 assert sre.subn("b+", "x", "bbbb BBBB") == ('x BBBB', 1)
139 assert sre.subn("b+", "x", "xyz") == ('xyz', 0)
140 assert sre.subn("b*", "x", "xyz") == ('xxxyxzx', 4)
141 assert sre.subn("b*", "x", "xyz", 2) == ('xxxyz', 2)
142except AssertionError:
143 raise TestFailed, "sre.subn"
144
145if verbose:
146 print 'Running tests on sre.split'
Fredrik Lundh6f013982000-07-03 18:44:21 +0000147
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000148try:
149 assert sre.split(":", ":a:b::c") == ['', 'a', 'b', '', 'c']
150 assert sre.split(":*", ":a:b::c") == ['', 'a', 'b', 'c']
151 assert sre.split("(:*)", ":a:b::c") == ['', ':', 'a', ':', 'b', '::', 'c']
152 assert sre.split("(?::*)", ":a:b::c") == ['', 'a', 'b', 'c']
153 assert sre.split("(:)*", ":a:b::c") == ['', ':', 'a', ':', 'b', ':', 'c']
154 assert sre.split("([b:]+)", ":a:b::c") == ['', ':', 'a', ':b::', 'c']
Fredrik Lundh067bebf2000-08-01 13:16:55 +0000155 assert sre.split("(b)|(:+)", ":a:b::c") == \
156 ['', None, ':', 'a', None, ':', '', 'b', None, '', None, '::', 'c']
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000157 assert sre.split("(?:b)|(?::+)", ":a:b::c") == ['', 'a', '', '', 'c']
158except AssertionError:
159 raise TestFailed, "sre.split"
160
161try:
162 assert sre.split(":", ":a:b::c", 2) == ['', 'a', 'b::c']
163 assert sre.split(':', 'a:b:c:d', 2) == ['a', 'b', 'c:d']
164
165 assert sre.split("(:)", ":a:b::c", 2) == ['', ':', 'a', ':', 'b::c']
Fredrik Lundh6f013982000-07-03 18:44:21 +0000166 assert sre.split("(:*)", ":a:b::c", 2) == ['', ':', 'a', ':', 'b::c']
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000167except AssertionError:
168 raise TestFailed, "qualified sre.split"
169
170if verbose:
171 print "Running tests on sre.findall"
172
173try:
174 assert sre.findall(":+", "abc") == []
175 assert sre.findall(":+", "a:b::c:::d") == [":", "::", ":::"]
176 assert sre.findall("(:+)", "a:b::c:::d") == [":", "::", ":::"]
177 assert sre.findall("(:)(:*)", "a:b::c:::d") == [(":", ""),
178 (":", ":"),
179 (":", "::")]
180except AssertionError:
181 raise TestFailed, "sre.findall"
182
183if verbose:
184 print "Running tests on sre.match"
185
186try:
187 # No groups at all
Fredrik Lundh6f013982000-07-03 18:44:21 +0000188 m = sre.match('a', 'a') ; assert m.groups() == ()
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000189 # A single group
Fredrik Lundh6f013982000-07-03 18:44:21 +0000190 m = sre.match('(a)', 'a') ; assert m.groups() == ('a',)
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000191
192 pat = sre.compile('((a)|(b))(c)?')
Fredrik Lundh6f013982000-07-03 18:44:21 +0000193 assert pat.match('a').groups() == ('a', 'a', None, None)
194 assert pat.match('b').groups() == ('b', None, 'b', None)
195 assert pat.match('ac').groups() == ('a', 'a', None, 'c')
196 assert pat.match('bc').groups() == ('b', None, 'b', 'c')
197 assert pat.match('bc').groups("") == ('b', "", 'b', 'c')
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000198except AssertionError:
199 raise TestFailed, "match .groups() method"
200
201try:
202 # A single group
Fredrik Lundh6f013982000-07-03 18:44:21 +0000203 m = sre.match('(a)', 'a')
204 assert m.group(0) == 'a' ; assert m.group(0) == 'a'
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000205 assert m.group(1) == 'a' ; assert m.group(1, 1) == ('a', 'a')
206
207 pat = sre.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
Fredrik Lundh6f013982000-07-03 18:44:21 +0000208 assert pat.match('a').group(1, 2, 3) == ('a', None, None)
209 assert pat.match('b').group('a1', 'b2', 'c3') == (None, 'b', None)
210 assert pat.match('ac').group(1, 'b2', 3) == ('a', None, 'c')
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000211except AssertionError:
212 raise TestFailed, "match .group() method"
213
214if verbose:
215 print "Running tests on sre.escape"
216
217try:
218 p=""
219 for i in range(0, 256):
220 p = p + chr(i)
221 assert sre.match(sre.escape(chr(i)), chr(i)) != None
222 assert sre.match(sre.escape(chr(i)), chr(i)).span() == (0,1)
223
224 pat=sre.compile( sre.escape(p) )
225 assert pat.match(p) != None
226 assert pat.match(p).span() == (0,256)
227except AssertionError:
228 raise TestFailed, "sre.escape"
229
230
231if verbose:
232 print 'Pickling a SRE_Pattern instance'
233
234try:
235 import pickle
236 pat = sre.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
237 s = pickle.dumps(pat)
238 pat = pickle.loads(s)
239except:
240 print TestFailed, 're module pickle' # expected
241
242try:
243 import cPickle
244 pat = sre.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
245 s = cPickle.dumps(pat)
246 pat = cPickle.loads(s)
247except:
248 print TestFailed, 're module cPickle' # expected
249
250try:
251 assert sre.I == sre.IGNORECASE
252 assert sre.L == sre.LOCALE
253 assert sre.M == sre.MULTILINE
Fredrik Lundh6f013982000-07-03 18:44:21 +0000254 assert sre.S == sre.DOTALL
255 assert sre.X == sre.VERBOSE
256 assert sre.T == sre.TEMPLATE
257 assert sre.U == sre.UNICODE
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000258except AssertionError:
259 raise TestFailed, 're module constants'
260
261for flags in [sre.I, sre.M, sre.X, sre.S, sre.L, sre.T, sre.U]:
262 try:
263 r = sre.compile('^pattern$', flags)
264 except:
265 print 'Exception raised on flag', flags
266
Fredrik Lundh96ab4652000-08-03 16:29:50 +0000267if verbose:
268 print 'Test engine limitations'
269
270# Try nasty case that overflows the straightforward recursive
271# implementation of repeated groups.
272try:
273 assert sre.match('(x)*', 50000*'x').span() == (0, 50000)
274except RuntimeError, v:
275 print v
276
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000277from re_tests import *
278
279if verbose:
280 print 'Running re_tests test suite'
281else:
282 # To save time, only run the first and last 10 tests
283 #tests = tests[:10] + tests[-10:]
Fredrik Lundh6f013982000-07-03 18:44:21 +0000284 pass
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000285
286for t in tests:
287 sys.stdout.flush()
288 pattern=s=outcome=repl=expected=None
289 if len(t)==5:
290 pattern, s, outcome, repl, expected = t
291 elif len(t)==3:
Fredrik Lundh6f013982000-07-03 18:44:21 +0000292 pattern, s, outcome = t
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000293 else:
294 raise ValueError, ('Test tuples should have 3 or 5 fields',t)
295
296 try:
297 obj=sre.compile(pattern)
298 except sre.error:
299 if outcome==SYNTAX_ERROR: pass # Expected a syntax error
Fredrik Lundh6f013982000-07-03 18:44:21 +0000300 else:
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000301 print '=== Syntax error:', t
302 except KeyboardInterrupt: raise KeyboardInterrupt
303 except:
304 print '*** Unexpected error ***', t
305 if verbose:
306 traceback.print_exc(file=sys.stdout)
307 else:
308 try:
309 result=obj.search(s)
310 except (sre.error), msg:
311 print '=== Unexpected exception', t, repr(msg)
312 if outcome==SYNTAX_ERROR:
313 # This should have been a syntax error; forget it.
314 pass
315 elif outcome==FAIL:
316 if result is None: pass # No match, as expected
317 else: print '=== Succeeded incorrectly', t
318 elif outcome==SUCCEED:
319 if result is not None:
320 # Matched, as expected, so now we compute the
321 # result string and compare it to our expected result.
322 start, end = result.span(0)
323 vardict={'found': result.group(0),
324 'groups': result.group(),
325 'flags': result.re.flags}
326 for i in range(1, 100):
327 try:
328 gi = result.group(i)
329 # Special hack because else the string concat fails:
330 if gi is None:
331 gi = "None"
332 except IndexError:
333 gi = "Error"
334 vardict['g%d' % i] = gi
335 for i in result.re.groupindex.keys():
336 try:
337 gi = result.group(i)
338 if gi is None:
339 gi = "None"
340 except IndexError:
341 gi = "Error"
342 vardict[i] = gi
343 repl=eval(repl, vardict)
344 if repl!=expected:
345 print '=== grouping error', t,
346 print repr(repl)+' should be '+repr(expected)
347 else:
348 print '=== Failed incorrectly', t
Fredrik Lundh90a07912000-06-30 07:50:59 +0000349 continue
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000350
351 # Try the match on a unicode string, and check that it
352 # still succeeds.
353 result=obj.search(unicode(s, "latin-1"))
354 if result==None:
355 print '=== Fails on unicode match', t
356
357 # Try the match on a unicode pattern, and check that it
358 # still succeeds.
359 obj=sre.compile(unicode(pattern, "latin-1"))
360 result=obj.search(s)
361 if result==None:
362 print '=== Fails on unicode pattern match', t
363
364 # Try the match with the search area limited to the extent
365 # of the match and see if it still succeeds. \B will
366 # break (because it won't match at the end or start of a
367 # string), so we'll ignore patterns that feature it.
Fredrik Lundh6f013982000-07-03 18:44:21 +0000368
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000369 if pattern[:2]!='\\B' and pattern[-2:]!='\\B':
370 obj=sre.compile(pattern)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000371 result=obj.search(s, result.start(0), result.end(0)+1)
372 if result==None:
373 print '=== Failed on range-limited match', t
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000374
375 # Try the match with IGNORECASE enabled, and check that it
376 # still succeeds.
377 obj=sre.compile(pattern, sre.IGNORECASE)
378 result=obj.search(s)
379 if result==None:
380 print '=== Fails on case-insensitive match', t
381
382 # Try the match with LOCALE enabled, and check that it
383 # still succeeds.
384 obj=sre.compile(pattern, sre.LOCALE)
385 result=obj.search(s)
386 if result==None:
387 print '=== Fails on locale-sensitive match', t
388
Fredrik Lundhc2ed6212000-08-01 13:01:43 +0000389 # Try the match with UNICODE locale enabled, and check
390 # that it still succeeds.
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000391 obj=sre.compile(pattern, sre.UNICODE)
392 result=obj.search(s)
393 if result==None:
394 print '=== Fails on unicode-sensitive match', t