home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / test / test_re.py < prev    next >
Text File  |  1997-12-30  |  7KB  |  239 lines

  1. #!/usr/local/bin/python
  2. # -*- mode: python -*-
  3. # test_re.py,v 1.14 1997/12/30 17:32:33 guido Exp
  4.  
  5. from test_support import verbose, TestFailed
  6. import re
  7. import sys, os, string, traceback
  8.  
  9. # Misc tests from Tim Peters' re.doc
  10.  
  11. if verbose:
  12.     print 'Running tests on re.sub'
  13.  
  14. try:
  15.     assert re.sub("(?i)b+", "x", "bbbb BBBB") == 'x x'
  16.     
  17.     def bump_num(matchobj):
  18.     int_value = int(matchobj.group(0))
  19.     return str(int_value + 1)
  20.  
  21.     assert re.sub(r'\d+', bump_num, '08.2 -2 23x99y') == '9.3 -3 24x100y'
  22.     
  23.     assert re.sub('.', lambda m: r"\n", 'x') == '\\n'
  24.     assert re.sub('.', r"\n", 'x') == '\n'
  25.  
  26.     s = r"\1\1"
  27.     assert re.sub('(.)', s, 'x') == 'xx'
  28.     assert re.sub('(.)', re.escape(s), 'x') == s
  29.     assert re.sub('(.)', lambda m: s, 'x') == s
  30.  
  31.     assert re.sub('(?P<a>x)', '\g<a>\g<a>', 'xx') == 'xxxx'
  32.     assert re.sub('(?P<unk>x)', '\g<unk>\g<unk>', 'xx') == 'xxxx'
  33.  
  34.     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\bBZ\aAwWsSdD'
  35.     assert re.sub('a', '\t\n\v\r\f\a', 'a') == '\t\n\v\r\f\a'
  36.     assert re.sub('a', '\t\n\v\r\f\a', 'a') == (chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7))
  37.  
  38. except AssertionError:
  39.     raise TestFailed, "re.sub"
  40.  
  41. if verbose:
  42.     print 'Running tests on symbolic references'
  43.  
  44. try:
  45.     re.sub('(?P<a>x)', '\g<a', 'xx')
  46. except re.error, reason:
  47.     pass
  48. else:
  49.     raise TestFailed, "symbolic reference"
  50.  
  51. try:
  52.     re.sub('(?P<a>x)', '\g<', 'xx')
  53. except re.error, reason:
  54.     pass
  55. else:
  56.     raise TestFailed, "symbolic reference"
  57.  
  58. try:
  59.     re.sub('(?P<a>x)', '\g', 'xx')
  60. except re.error, reason:
  61.     pass
  62. else:
  63.     raise TestFailed, "symbolic reference"
  64.  
  65. try:
  66.     re.sub('(?P<a>x)', '\g<a a>', 'xx')
  67. except re.error, reason:
  68.     pass
  69. else:
  70.     raise TestFailed, "symbolic reference"
  71.  
  72. try:
  73.     re.sub('(?P<a>x)', '\g<ab>', 'xx')
  74. except IndexError, reason:
  75.     pass
  76. else:
  77.     raise TestFailed, "symbolic reference"
  78.  
  79. try:
  80.     re.sub('(?P<a>x)|(?P<b>y)', '\g<b>', 'xx')
  81. except re.error, reason:
  82.     pass
  83. else:
  84.     raise TestFailed, "symbolic reference"
  85.  
  86. try:
  87.     re.sub('(?P<a>x)|(?P<b>y)', '\\2', 'xx')
  88. except re.error, reason:
  89.     pass
  90. else:
  91.     raise TestFailed, "symbolic reference"
  92.  
  93. if verbose:
  94.     print 'Running tests on re.subn'
  95.  
  96. try:
  97.     assert re.subn("(?i)b+", "x", "bbbb BBBB") == ('x x', 2)
  98.     assert re.subn("b+", "x", "bbbb BBBB") == ('x BBBB', 1)
  99.     assert re.subn("b+", "x", "xyz") == ('xyz', 0)
  100.     assert re.subn("b*", "x", "xyz") == ('xxxyxzx', 4)
  101. except AssertionError:
  102.     raise TestFailed, "re.subn"
  103.  
  104. try:
  105.     assert re.split(":", ":a:b::c") == ['', 'a', 'b', '', 'c']
  106.     assert re.split(":*", ":a:b::c") == ['', 'a', 'b', 'c']
  107.     assert re.split("(:*)", ":a:b::c") == ['', ':', 'a', ':', 'b', '::', 'c']
  108.     assert re.split("(?::*)", ":a:b::c") == ['', 'a', 'b', 'c']
  109.     assert re.split("(:)*", ":a:b::c") == ['', ':', 'a', ':', 'b', ':', 'c']
  110.     assert re.split("([b:]+)", ":a:b::c") == ['', ':', 'a', ':b::', 'c']
  111.     assert re.split("(b)|(:+)", ":a:b::c") == \
  112.            ['', None, ':', 'a', None, ':', '', 'b', None, '', None, '::', 'c']
  113.     assert re.split("(?:b)|(?::+)", ":a:b::c") == ['', 'a', '', '', 'c']
  114.     
  115. except AssertionError:
  116.     raise TestFailed, "re.split"
  117.  
  118. if verbose:
  119.     print 'Pickling a RegexObject instance'
  120.     import pickle
  121.     pat = re.compile('a(?:b|(c|e){1,2}?|d)+?(.)')
  122.     s = pickle.dumps(pat)
  123.     pat = pickle.loads(s)
  124.  
  125. if verbose:
  126.     print 'Running tests on re.split'
  127.     
  128. try:
  129.     assert re.I == re.IGNORECASE
  130.     assert re.L == re.LOCALE
  131.     assert re.M == re.MULTILINE
  132.     assert re.S == re.DOTALL 
  133.     assert re.X == re.VERBOSE 
  134. except AssertionError:
  135.     raise TestFailed, 're module constants'
  136.  
  137. for flags in [re.I, re.M, re.X, re.S, re.L]:
  138.     try:
  139.     r = re.compile('^pattern$', flags)
  140.     except:
  141.     print 'Exception raised on flag', flags
  142.  
  143. from re_tests import *
  144. if verbose:
  145.     print 'Running re_tests test suite'
  146. else:
  147.     # To save time, only run the first and last 10 tests
  148.     pass #tests = tests[:10] + tests[-10:]
  149.  
  150. for t in tests:
  151.     sys.stdout.flush()
  152.     pattern=s=outcome=repl=expected=None
  153.     if len(t)==5:
  154.     pattern, s, outcome, repl, expected = t
  155.     elif len(t)==3:
  156.     pattern, s, outcome = t 
  157.     else:
  158.     raise ValueError, ('Test tuples should have 3 or 5 fields',t)
  159.  
  160.     try:
  161.     obj=re.compile(pattern)
  162.     except re.error:
  163.     if outcome==SYNTAX_ERROR: pass    # Expected a syntax error
  164.     else: 
  165.         print '=== Syntax error:', t
  166.     except KeyboardInterrupt: raise KeyboardInterrupt
  167.     except:
  168.     print '*** Unexpected error ***'
  169.     if verbose:
  170.         traceback.print_exc(file=sys.stdout)
  171.     else:
  172.     try:
  173.         result=obj.search(s)
  174.     except (re.error), msg:
  175.         print '=== Unexpected exception', t, repr(msg)
  176.     if outcome==SYNTAX_ERROR:
  177.         # This should have been a syntax error; forget it.
  178.         pass
  179.     elif outcome==FAIL:
  180.         if result is None: pass   # No match, as expected
  181.         else: print '=== Succeeded incorrectly', t
  182.     elif outcome==SUCCEED:
  183.         if result is not None:
  184.         # Matched, as expected, so now we compute the
  185.         # result string and compare it to our expected result.
  186.         start, end = result.span(0)
  187.         vardict={'found': result.group(0),
  188.              'groups': result.group(),
  189.              'flags': result.re.flags}
  190.         for i in range(1, 100):
  191.             try:
  192.             gi = result.group(i)
  193.             # Special hack because else the string concat fails:
  194.             if gi is None:
  195.                 gi = "None"
  196.             except IndexError:
  197.             gi = "Error"
  198.             vardict['g%d' % i] = gi
  199.         for i in result.re.groupindex.keys():
  200.             try:
  201.             gi = result.group(i)
  202.             if gi is None:
  203.                 gi = "None"
  204.             except IndexError:
  205.             gi = "Error"
  206.             vardict[i] = gi
  207.         repl=eval(repl, vardict)
  208.         if repl!=expected:
  209.             print '=== grouping error', t,
  210.             print repr(repl)+' should be '+repr(expected)
  211.         else:
  212.         print '=== Failed incorrectly', t
  213.  
  214.         # Try the match with the search area limited to the extent
  215.         # of the match and see if it still succeeds.  \B will
  216.         # break (because it won't match at the end or start of a
  217.         # string), so we'll ignore patterns that feature it.
  218.         
  219.         if pattern[:2]!='\\B' and pattern[-2:]!='\\B':
  220.         obj=re.compile(pattern)
  221.         result=obj.search(s, pos=result.start(0), endpos=result.end(0)+1)
  222.         if result==None:
  223.             print '=== Failed on range-limited match', t
  224.  
  225.             # Try the match with IGNORECASE enabled, and check that it
  226.         # still succeeds.
  227.             obj=re.compile(pattern, re.IGNORECASE)
  228.             result=obj.search(s)
  229.             if result==None:
  230.                 print '=== Fails on case-insensitive match', t
  231.  
  232.             # Try the match with LOCALE enabled, and check that it
  233.         # still succeeds.
  234.             obj=re.compile(pattern, re.LOCALE)
  235.             result=obj.search(s)
  236.             if result==None:
  237.                 print '=== Fails on locale-sensitive match', t
  238.  
  239.