blob: a22c51a3ff635a1a5f9b7f0a22f4775ae7081a6b [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']
155# FIXME: group problem
156# assert sre.split("(b)|(:+)", ":a:b::c") == \
157# ['', None, ':', 'a', None, ':', '', 'b', None, '', None, '::', 'c']
158 assert sre.split("(?:b)|(?::+)", ":a:b::c") == ['', 'a', '', '', 'c']
159except AssertionError:
160 raise TestFailed, "sre.split"
161
162try:
163 assert sre.split(":", ":a:b::c", 2) == ['', 'a', 'b::c']
164 assert sre.split(':', 'a:b:c:d', 2) == ['a', 'b', 'c:d']
165
166 assert sre.split("(:)", ":a:b::c", 2) == ['', ':', 'a', ':', 'b::c']
Fredrik Lundh6f013982000-07-03 18:44:21 +0000167 assert sre.split("(:*)", ":a:b::c", 2) == ['', ':', 'a', ':', 'b::c']
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000168except AssertionError:
169 raise TestFailed, "qualified sre.split"
170
171if verbose:
172 print "Running tests on sre.findall"
173
174try:
175 assert sre.findall(":+", "abc") == []
176 assert sre.findall(":+", "a:b::c:::d") == [":", "::", ":::"]
177 assert sre.findall("(:+)", "a:b::c:::d") == [":", "::", ":::"]
178 assert sre.findall("(:)(:*)", "a:b::c:::d") == [(":", ""),
179 (":", ":"),
180 (":", "::")]
181except AssertionError:
182 raise TestFailed, "sre.findall"
183
184if verbose:
185 print "Running tests on sre.match"
186
187try:
188 # No groups at all
Fredrik Lundh6f013982000-07-03 18:44:21 +0000189 m = sre.match('a', 'a') ; assert m.groups() == ()
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000190 # A single group
Fredrik Lundh6f013982000-07-03 18:44:21 +0000191 m = sre.match('(a)', 'a') ; assert m.groups() == ('a',)
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000192
193 pat = sre.compile('((a)|(b))(c)?')
Fredrik Lundh6f013982000-07-03 18:44:21 +0000194 assert pat.match('a').groups() == ('a', 'a', None, None)
195 assert pat.match('b').groups() == ('b', None, 'b', None)
196 assert pat.match('ac').groups() == ('a', 'a', None, 'c')
197 assert pat.match('bc').groups() == ('b', None, 'b', 'c')
198 assert pat.match('bc').groups("") == ('b', "", 'b', 'c')
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000199except AssertionError:
200 raise TestFailed, "match .groups() method"
201
202try:
203 # A single group
Fredrik Lundh6f013982000-07-03 18:44:21 +0000204 m = sre.match('(a)', 'a')
205 assert m.group(0) == 'a' ; assert m.group(0) == 'a'
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000206 assert m.group(1) == 'a' ; assert m.group(1, 1) == ('a', 'a')
207
208 pat = sre.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
Fredrik Lundh6f013982000-07-03 18:44:21 +0000209 assert pat.match('a').group(1, 2, 3) == ('a', None, None)
210 assert pat.match('b').group('a1', 'b2', 'c3') == (None, 'b', None)
211 assert pat.match('ac').group(1, 'b2', 3) == ('a', None, 'c')
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000212except AssertionError:
213 raise TestFailed, "match .group() method"
214
215if verbose:
216 print "Running tests on sre.escape"
217
218try:
219 p=""
220 for i in range(0, 256):
221 p = p + chr(i)
222 assert sre.match(sre.escape(chr(i)), chr(i)) != None
223 assert sre.match(sre.escape(chr(i)), chr(i)).span() == (0,1)
224
225 pat=sre.compile( sre.escape(p) )
226 assert pat.match(p) != None
227 assert pat.match(p).span() == (0,256)
228except AssertionError:
229 raise TestFailed, "sre.escape"
230
231
232if verbose:
233 print 'Pickling a SRE_Pattern instance'
234
235try:
236 import pickle
237 pat = sre.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
238 s = pickle.dumps(pat)
239 pat = pickle.loads(s)
240except:
241 print TestFailed, 're module pickle' # expected
242
243try:
244 import cPickle
245 pat = sre.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
246 s = cPickle.dumps(pat)
247 pat = cPickle.loads(s)
248except:
249 print TestFailed, 're module cPickle' # expected
250
251try:
252 assert sre.I == sre.IGNORECASE
253 assert sre.L == sre.LOCALE
254 assert sre.M == sre.MULTILINE
Fredrik Lundh6f013982000-07-03 18:44:21 +0000255 assert sre.S == sre.DOTALL
256 assert sre.X == sre.VERBOSE
257 assert sre.T == sre.TEMPLATE
258 assert sre.U == sre.UNICODE
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000259except AssertionError:
260 raise TestFailed, 're module constants'
261
262for flags in [sre.I, sre.M, sre.X, sre.S, sre.L, sre.T, sre.U]:
263 try:
264 r = sre.compile('^pattern$', flags)
265 except:
266 print 'Exception raised on flag', flags
267
268from re_tests import *
269
270if verbose:
271 print 'Running re_tests test suite'
272else:
273 # To save time, only run the first and last 10 tests
274 #tests = tests[:10] + tests[-10:]
Fredrik Lundh6f013982000-07-03 18:44:21 +0000275 pass
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000276
277for t in tests:
278 sys.stdout.flush()
279 pattern=s=outcome=repl=expected=None
280 if len(t)==5:
281 pattern, s, outcome, repl, expected = t
282 elif len(t)==3:
Fredrik Lundh6f013982000-07-03 18:44:21 +0000283 pattern, s, outcome = t
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000284 else:
285 raise ValueError, ('Test tuples should have 3 or 5 fields',t)
286
287 try:
288 obj=sre.compile(pattern)
289 except sre.error:
290 if outcome==SYNTAX_ERROR: pass # Expected a syntax error
Fredrik Lundh6f013982000-07-03 18:44:21 +0000291 else:
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000292 print '=== Syntax error:', t
293 except KeyboardInterrupt: raise KeyboardInterrupt
294 except:
295 print '*** Unexpected error ***', t
296 if verbose:
297 traceback.print_exc(file=sys.stdout)
298 else:
299 try:
300 result=obj.search(s)
301 except (sre.error), msg:
302 print '=== Unexpected exception', t, repr(msg)
303 if outcome==SYNTAX_ERROR:
304 # This should have been a syntax error; forget it.
305 pass
306 elif outcome==FAIL:
307 if result is None: pass # No match, as expected
308 else: print '=== Succeeded incorrectly', t
309 elif outcome==SUCCEED:
310 if result is not None:
311 # Matched, as expected, so now we compute the
312 # result string and compare it to our expected result.
313 start, end = result.span(0)
314 vardict={'found': result.group(0),
315 'groups': result.group(),
316 'flags': result.re.flags}
317 for i in range(1, 100):
318 try:
319 gi = result.group(i)
320 # Special hack because else the string concat fails:
321 if gi is None:
322 gi = "None"
323 except IndexError:
324 gi = "Error"
325 vardict['g%d' % i] = gi
326 for i in result.re.groupindex.keys():
327 try:
328 gi = result.group(i)
329 if gi is None:
330 gi = "None"
331 except IndexError:
332 gi = "Error"
333 vardict[i] = gi
334 repl=eval(repl, vardict)
335 if repl!=expected:
336 print '=== grouping error', t,
337 print repr(repl)+' should be '+repr(expected)
338 else:
339 print '=== Failed incorrectly', t
Fredrik Lundh90a07912000-06-30 07:50:59 +0000340 continue
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000341
342 # Try the match on a unicode string, and check that it
343 # still succeeds.
344 result=obj.search(unicode(s, "latin-1"))
345 if result==None:
346 print '=== Fails on unicode match', t
347
348 # Try the match on a unicode pattern, and check that it
349 # still succeeds.
350 obj=sre.compile(unicode(pattern, "latin-1"))
351 result=obj.search(s)
352 if result==None:
353 print '=== Fails on unicode pattern match', t
354
355 # Try the match with the search area limited to the extent
356 # of the match and see if it still succeeds. \B will
357 # break (because it won't match at the end or start of a
358 # string), so we'll ignore patterns that feature it.
Fredrik Lundh6f013982000-07-03 18:44:21 +0000359
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000360 if pattern[:2]!='\\B' and pattern[-2:]!='\\B':
361 obj=sre.compile(pattern)
Fredrik Lundh90a07912000-06-30 07:50:59 +0000362 result=obj.search(s, result.start(0), result.end(0)+1)
363 if result==None:
364 print '=== Failed on range-limited match', t
Fredrik Lundhdf02d0b2000-06-30 07:08:20 +0000365
366 # Try the match with IGNORECASE enabled, and check that it
367 # still succeeds.
368 obj=sre.compile(pattern, sre.IGNORECASE)
369 result=obj.search(s)
370 if result==None:
371 print '=== Fails on case-insensitive match', t
372
373 # Try the match with LOCALE enabled, and check that it
374 # still succeeds.
375 obj=sre.compile(pattern, sre.LOCALE)
376 result=obj.search(s)
377 if result==None:
378 print '=== Fails on locale-sensitive match', t
379
380 # Try the match with UNICODE enabled, and check that it
381 # still succeeds.
382 obj=sre.compile(pattern, sre.UNICODE)
383 result=obj.search(s)
384 if result==None:
385 print '=== Fails on unicode-sensitive match', t