home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / TEST_RE.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  12.3 KB  |  380 lines

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