blob: 342c33d471994ecf756cd41a89074c96b51db20c [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
267from re_tests import *
268
269if verbose:
270 print 'Running re_tests test suite'
271else:
272 # To save time, only run the first and last 10 tests
273 #tests = tests[:10] + tests[-10:]
Fredrik Lundh6f013982000-07-03 18:44:21 +0000274 pass
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000275
276for t in tests:
277 sys.stdout.flush()
278 pattern=s=outcome=repl=expected=None
279 if len(t)==5:
280 pattern, s, outcome, repl, expected = t
281 elif len(t)==3:
Fredrik Lundh6f013982000-07-03 18:44:21 +0000282 pattern, s, outcome = t
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000283 else:
284 raise ValueError, ('Test tuples should have 3 or 5 fields',t)
285
286 try:
287 obj=sre.compile(pattern)
288 except sre.error:
289 if outcome==SYNTAX_ERROR: pass # Expected a syntax error
Fredrik Lundh6f013982000-07-03 18:44:21 +0000290 else:
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000291 print '=== Syntax error:', t
292 except KeyboardInterrupt: raise KeyboardInterrupt
293 except:
294 print '*** Unexpected error ***', t
295 if verbose:
296 traceback.print_exc(file=sys.stdout)
297 else:
298 try:
299 result=obj.search(s)
300 except (sre.error), msg:
301 print '=== Unexpected exception', t, repr(msg)
302 if outcome==SYNTAX_ERROR:
303 # This should have been a syntax error; forget it.
304 pass
305 elif outcome==FAIL:
306 if result is None: pass # No match, as expected
307 else: print '=== Succeeded incorrectly', t
308 elif outcome==SUCCEED:
309 if result is not None:
310 # Matched, as expected, so now we compute the
311 # result string and compare it to our expected result.
312 start, end = result.span(0)
313 vardict={'found': result.group(0),
314 'groups': result.group(),
315 'flags': result.re.flags}
316 for i in range(1, 100):
317 try:
318 gi = result.group(i)
319 # Special hack because else the string concat fails:
320 if gi is None:
321 gi = "None"
322 except IndexError:
323 gi = "Error"
324 vardict['g%d' % i] = gi
325 for i in result.re.groupindex.keys():
326 try:
327 gi = result.group(i)
328 if gi is None:
329 gi = "None"
330 except IndexError:
331 gi = "Error"
332 vardict[i] = gi
333 repl=eval(repl, vardict)
334 if repl!=expected:
335 print '=== grouping error', t,
336 print repr(repl)+' should be '+repr(expected)
337 else:
338 print '=== Failed incorrectly', t
Fredrik Lundh90a07912000-06-30 07:50:59 +0000339 continue
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000340
341 # Try the match on a unicode string, and check that it
342 # still succeeds.
343 result=obj.search(unicode(s, "latin-1"))
344 if result==None:
345 print '=== Fails on unicode match', t
346
347 # Try the match on a unicode pattern, and check that it
348 # still succeeds.
349 obj=sre.compile(unicode(pattern, "latin-1"))
350 result=obj.search(s)
351 if result==None:
352 print '=== Fails on unicode pattern match', t
353
354 # Try the match with the search area limited to the extent
355 # of the match and see if it still succeeds. \B will
356 # break (because it won't match at the end or start of a
357 # string), so we'll ignore patterns that feature it.
Fredrik Lundh6f013982000-07-03 18:44:21 +0000358
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000359 if pattern[:2]!='\\B' and pattern[-2:]!='\\B':
360 obj=sre.compile(pattern)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000361 result=obj.search(s, result.start(0), result.end(0)+1)
362 if result==None:
363 print '=== Failed on range-limited match', t
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000364
365 # Try the match with IGNORECASE enabled, and check that it
366 # still succeeds.
367 obj=sre.compile(pattern, sre.IGNORECASE)
368 result=obj.search(s)
369 if result==None:
370 print '=== Fails on case-insensitive match', t
371
372 # Try the match with LOCALE enabled, and check that it
373 # still succeeds.
374 obj=sre.compile(pattern, sre.LOCALE)
375 result=obj.search(s)
376 if result==None:
377 print '=== Fails on locale-sensitive match', t
378
Fredrik Lundhc2ed6212000-08-01 13:01:43 +0000379 # Try the match with UNICODE locale enabled, and check
380 # that it still succeeds.
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000381 obj=sre.compile(pattern, sre.UNICODE)
382 result=obj.search(s)
383 if result==None:
384 print '=== Fails on unicode-sensitive match', t