home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / test / test_sre.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  15.4 KB  |  431 lines

  1. # SRE test harness for the Python regression suite
  2.  
  3. # this is based on test_re.py, but uses a test function instead
  4. # of all those asserts
  5.  
  6. import sys
  7. sys.path=['.']+sys.path
  8.  
  9. from test_support import verbose, TestFailed, have_unicode
  10. import sre
  11. import sys, os, string, traceback
  12.  
  13. #
  14. # test support
  15.  
  16. def test(expression, result, exception=None):
  17.     try:
  18.         r = eval(expression)
  19.     except:
  20.         if exception:
  21.             if not isinstance(sys.exc_value, exception):
  22.                 print expression, "FAILED"
  23.                 # display name, not actual value
  24.                 if exception is sre.error:
  25.                     print "expected", "sre.error"
  26.                 else:
  27.                     print "expected", exception.__name__
  28.                 print "got", sys.exc_type.__name__, str(sys.exc_value)
  29.         else:
  30.             print expression, "FAILED"
  31.             traceback.print_exc(file=sys.stdout)
  32.     else:
  33.         if exception:
  34.             print expression, "FAILED"
  35.             if exception is sre.error:
  36.                 print "expected", "sre.error"
  37.             else:
  38.                 print "expected", exception.__name__
  39.             print "got result", repr(r)
  40.         else:
  41.             if r != result:
  42.                 print expression, "FAILED"
  43.                 print "expected", repr(result)
  44.                 print "got result", repr(r)
  45.  
  46. if verbose:
  47.     print 'Running tests on character literals'
  48.  
  49. for i in [0, 8, 16, 32, 64, 127, 128, 255]:
  50.     test(r"""sre.match(r"\%03o" % i, chr(i)) is not None""", 1)
  51.     test(r"""sre.match(r"\%03o0" % i, chr(i)+"0") is not None""", 1)
  52.     test(r"""sre.match(r"\%03o8" % i, chr(i)+"8") is not None""", 1)
  53.     test(r"""sre.match(r"\x%02x" % i, chr(i)) is not None""", 1)
  54.     test(r"""sre.match(r"\x%02x0" % i, chr(i)+"0") is not None""", 1)
  55.     test(r"""sre.match(r"\x%02xz" % i, chr(i)+"z") is not None""", 1)
  56. test(r"""sre.match("\911", "")""", None, sre.error)
  57.  
  58. #
  59. # Misc tests from Tim Peters' re.doc
  60.  
  61. if verbose:
  62.     print 'Running tests on sre.search and sre.match'
  63.  
  64. test(r"""sre.search(r'x*', 'axx').span(0)""", (0, 0))
  65. test(r"""sre.search(r'x*', 'axx').span()""", (0, 0))
  66. test(r"""sre.search(r'x+', 'axx').span(0)""", (1, 3))
  67. test(r"""sre.search(r'x+', 'axx').span()""", (1, 3))
  68. test(r"""sre.search(r'x', 'aaa')""", None)
  69.  
  70. test(r"""sre.match(r'a*', 'xxx').span(0)""", (0, 0))
  71. test(r"""sre.match(r'a*', 'xxx').span()""", (0, 0))
  72. test(r"""sre.match(r'x*', 'xxxa').span(0)""", (0, 3))
  73. test(r"""sre.match(r'x*', 'xxxa').span()""", (0, 3))
  74. test(r"""sre.match(r'a+', 'xxx')""", None)
  75.  
  76. # bug 113254
  77. test(r"""sre.match(r'(a)|(b)', 'b').start(1)""", -1)
  78. test(r"""sre.match(r'(a)|(b)', 'b').end(1)""", -1)
  79. test(r"""sre.match(r'(a)|(b)', 'b').span(1)""", (-1, -1))
  80.  
  81. if verbose:
  82.     print 'Running tests on sre.sub'
  83.  
  84. test(r"""sre.sub(r"(?i)b+", "x", "bbbb BBBB")""", 'x x')
  85.  
  86. def bump_num(matchobj):
  87.     int_value = int(matchobj.group(0))
  88.     return str(int_value + 1)
  89.  
  90. test(r"""sre.sub(r'\d+', bump_num, '08.2 -2 23x99y')""", '9.3 -3 24x100y')
  91. test(r"""sre.sub(r'\d+', bump_num, '08.2 -2 23x99y', 3)""", '9.3 -3 23x99y')
  92.  
  93. test(r"""sre.sub(r'.', lambda m: r"\n", 'x')""", '\\n')
  94. test(r"""sre.sub(r'.', r"\n", 'x')""", '\n')
  95.  
  96. s = r"\1\1"
  97.  
  98. test(r"""sre.sub(r'(.)', s, 'x')""", 'xx')
  99. test(r"""sre.sub(r'(.)', sre.escape(s), 'x')""", s)
  100. test(r"""sre.sub(r'(.)', lambda m: s, 'x')""", s)
  101.  
  102. test(r"""sre.sub(r'(?P<a>x)', '\g<a>\g<a>', 'xx')""", 'xxxx')
  103. test(r"""sre.sub(r'(?P<a>x)', '\g<a>\g<1>', 'xx')""", 'xxxx')
  104. test(r"""sre.sub(r'(?P<unk>x)', '\g<unk>\g<unk>', 'xx')""", 'xxxx')
  105. test(r"""sre.sub(r'(?P<unk>x)', '\g<1>\g<1>', 'xx')""", 'xxxx')
  106.  
  107. # bug 449964: fails for group followed by other escape
  108. test(r"""sre.sub(r'(?P<unk>x)', '\g<1>\g<1>\\b', 'xx')""", 'xx\bxx\b')
  109.  
  110. test(r"""sre.sub(r'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')
  111. test(r"""sre.sub(r'a', '\t\n\v\r\f\a', 'a')""", '\t\n\v\r\f\a')
  112. test(r"""sre.sub(r'a', '\t\n\v\r\f\a', 'a')""", (chr(9)+chr(10)+chr(11)+chr(13)+chr(12)+chr(7)))
  113.  
  114. test(r"""sre.sub(r'^\s*', 'X', 'test')""", 'Xtest')
  115.  
  116. # qualified sub
  117. test(r"""sre.sub(r'a', 'b', 'aaaaa')""", 'bbbbb')
  118. test(r"""sre.sub(r'a', 'b', 'aaaaa', 1)""", 'baaaa')
  119.  
  120. # bug 114660
  121. test(r"""sre.sub(r'(\S)\s+(\S)', r'\1 \2', 'hello  there')""", 'hello there')
  122.  
  123. # Test for sub() on escaped characters, see SF bug #449000
  124. test(r"""sre.sub(r'\r\n', r'\n', 'abc\r\ndef\r\n')""", 'abc\ndef\n')
  125. test(r"""sre.sub('\r\n', r'\n', 'abc\r\ndef\r\n')""", 'abc\ndef\n')
  126. test(r"""sre.sub(r'\r\n', '\n', 'abc\r\ndef\r\n')""", 'abc\ndef\n')
  127. test(r"""sre.sub('\r\n', '\n', 'abc\r\ndef\r\n')""", 'abc\ndef\n')
  128.  
  129. # Test for empty sub() behaviour, see SF bug #462270
  130. test(r"""sre.sub('x*', '-', 'abxd')""", '-a-b-d-')
  131. test(r"""sre.sub('x+', '-', 'abxd')""", 'ab-d')
  132.  
  133. if verbose:
  134.     print 'Running tests on symbolic references'
  135.  
  136. test(r"""sre.sub(r'(?P<a>x)', '\g<a', 'xx')""", None, sre.error)
  137. test(r"""sre.sub(r'(?P<a>x)', '\g<', 'xx')""", None, sre.error)
  138. test(r"""sre.sub(r'(?P<a>x)', '\g', 'xx')""", None, sre.error)
  139. test(r"""sre.sub(r'(?P<a>x)', '\g<a a>', 'xx')""", None, sre.error)
  140. test(r"""sre.sub(r'(?P<a>x)', '\g<1a1>', 'xx')""", None, sre.error)
  141. test(r"""sre.sub(r'(?P<a>x)', '\g<ab>', 'xx')""", None, IndexError)
  142. test(r"""sre.sub(r'(?P<a>x)|(?P<b>y)', '\g<b>', 'xx')""", None, sre.error)
  143. test(r"""sre.sub(r'(?P<a>x)|(?P<b>y)', '\\2', 'xx')""", None, sre.error)
  144.  
  145. if verbose:
  146.     print 'Running tests on sre.subn'
  147.  
  148. test(r"""sre.subn(r"(?i)b+", "x", "bbbb BBBB")""", ('x x', 2))
  149. test(r"""sre.subn(r"b+", "x", "bbbb BBBB")""", ('x BBBB', 1))
  150. test(r"""sre.subn(r"b+", "x", "xyz")""", ('xyz', 0))
  151. test(r"""sre.subn(r"b*", "x", "xyz")""", ('xxxyxzx', 4))
  152. test(r"""sre.subn(r"b*", "x", "xyz", 2)""", ('xxxyz', 2))
  153.  
  154. if verbose:
  155.     print 'Running tests on sre.split'
  156.  
  157. test(r"""sre.split(r":", ":a:b::c")""", ['', 'a', 'b', '', 'c'])
  158. test(r"""sre.split(r":+", ":a:b:::")""", ['', 'a', 'b', ''])
  159. test(r"""sre.split(r":*", ":a:b::c")""", ['', 'a', 'b', 'c'])
  160. test(r"""sre.split(r"(:*)", ":a:b::c")""", ['', ':', 'a', ':', 'b', '::', 'c'])
  161. test(r"""sre.split(r"(?::*)", ":a:b::c")""", ['', 'a', 'b', 'c'])
  162. test(r"""sre.split(r"(:)*", ":a:b::c")""", ['', ':', 'a', ':', 'b', ':', 'c'])
  163. test(r"""sre.split(r"([b:]+)", ":a:b::c")""", ['', ':', 'a', ':b::', 'c'])
  164. test(r"""sre.split(r"(b)|(:+)", ":a:b::c")""",
  165.      ['', None, ':', 'a', None, ':', '', 'b', None, '', None, '::', 'c'])
  166. test(r"""sre.split(r"(?:b)|(?::+)", ":a:b::c")""", ['', 'a', '', '', 'c'])
  167.  
  168. test(r"""sre.split(r":", ":a:b::c", 2)""", ['', 'a', 'b::c'])
  169. test(r"""sre.split(r':', 'a:b:c:d', 2)""", ['a', 'b', 'c:d'])
  170.  
  171. test(r"""sre.split(r"(:)", ":a:b::c", 2)""", ['', ':', 'a', ':', 'b::c'])
  172. test(r"""sre.split(r"(:*)", ":a:b::c", 2)""", ['', ':', 'a', ':', 'b::c'])
  173.  
  174. if verbose:
  175.     print "Running tests on sre.findall"
  176.  
  177. test(r"""sre.findall(r":+", "abc")""", [])
  178. test(r"""sre.findall(r":+", "a:b::c:::d")""", [":", "::", ":::"])
  179. test(r"""sre.findall(r"(:+)", "a:b::c:::d")""", [":", "::", ":::"])
  180. test(r"""sre.findall(r"(:)(:*)", "a:b::c:::d")""",
  181.      [(":", ""), (":", ":"), (":", "::")])
  182. test(r"""sre.findall(r"(a)|(b)", "abc")""", [("a", ""), ("", "b")])
  183.  
  184. # bug 117612
  185. test(r"""sre.findall(r"(a|(b))", "aba")""", [("a", ""),("b", "b"),("a", "")])
  186.  
  187. if sys.hexversion >= 0x02020000:
  188.     if verbose:
  189.         print "Running tests on sre.finditer"
  190.     def fixup(seq):
  191.         # convert iterator to list
  192.         if not hasattr(seq, "next") or not hasattr(seq, "__iter__"):
  193.             print "finditer returned", type(seq)
  194.         return map(lambda item: item.group(0), seq)
  195.     # sanity
  196.     test(r"""fixup(sre.finditer(r":+", "a:b::c:::d"))""", [":", "::", ":::"])
  197.  
  198. if verbose:
  199.     print "Running tests on sre.match"
  200.  
  201. test(r"""sre.match(r'a', 'a').groups()""", ())
  202. test(r"""sre.match(r'(a)', 'a').groups()""", ('a',))
  203. test(r"""sre.match(r'(a)', 'a').group(0)""", 'a')
  204. test(r"""sre.match(r'(a)', 'a').group(1)""", 'a')
  205. test(r"""sre.match(r'(a)', 'a').group(1, 1)""", ('a', 'a'))
  206.  
  207. pat = sre.compile(r'((a)|(b))(c)?')
  208. test(r"""pat.match('a').groups()""", ('a', 'a', None, None))
  209. test(r"""pat.match('b').groups()""", ('b', None, 'b', None))
  210. test(r"""pat.match('ac').groups()""", ('a', 'a', None, 'c'))
  211. test(r"""pat.match('bc').groups()""", ('b', None, 'b', 'c'))
  212. test(r"""pat.match('bc').groups("")""", ('b', "", 'b', 'c'))
  213.  
  214. pat = sre.compile(r'(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
  215. test(r"""pat.match('a').group(1, 2, 3)""", ('a', None, None))
  216. test(r"""pat.match('b').group('a1', 'b2', 'c3')""", (None, 'b', None))
  217. test(r"""pat.match('ac').group(1, 'b2', 3)""", ('a', None, 'c'))
  218.  
  219. # bug 448951 (similar to 429357, but with single char match)
  220. # (Also test greedy matches.)
  221. for op in '','?','*':
  222.     test(r"""sre.match(r'((.%s):)?z', 'z').groups()"""%op, (None, None))
  223.     test(r"""sre.match(r'((.%s):)?z', 'a:z').groups()"""%op, ('a:', 'a'))
  224.  
  225. if verbose:
  226.     print "Running tests on sre.escape"
  227.  
  228. p = ""
  229. for i in range(0, 256):
  230.     p = p + chr(i)
  231.     test(r"""sre.match(sre.escape(chr(i)), chr(i)) is not None""", 1)
  232.     test(r"""sre.match(sre.escape(chr(i)), chr(i)).span()""", (0,1))
  233.  
  234. pat = sre.compile(sre.escape(p))
  235. test(r"""pat.match(p) is not None""", 1)
  236. test(r"""pat.match(p).span()""", (0,256))
  237.  
  238. if verbose:
  239.     print 'Running tests on sre.Scanner'
  240.  
  241. def s_ident(scanner, token): return token
  242. def s_operator(scanner, token): return "op%s" % token
  243. def s_float(scanner, token): return float(token)
  244. def s_int(scanner, token): return int(token)
  245.  
  246. scanner = sre.Scanner([
  247.     (r"[a-zA-Z_]\w*", s_ident),
  248.     (r"\d+\.\d*", s_float),
  249.     (r"\d+", s_int),
  250.     (r"=|\+|-|\*|/", s_operator),
  251.     (r"\s+", None),
  252.     ])
  253.  
  254. # sanity check
  255. test('scanner.scan("sum = 3*foo + 312.50 + bar")',
  256.      (['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], ''))
  257.  
  258. if verbose:
  259.     print 'Pickling a SRE_Pattern instance'
  260.  
  261. try:
  262.     import pickle
  263.     pat = sre.compile(r'a(?:b|(c|e){1,2}?|d)+?(.)')
  264.     s = pickle.dumps(pat)
  265.     pat = pickle.loads(s)
  266. except:
  267.     print TestFailed, 're module pickle'
  268.  
  269. try:
  270.     import cPickle
  271.     pat = sre.compile(r'a(?:b|(c|e){1,2}?|d)+?(.)')
  272.     s = cPickle.dumps(pat)
  273.     pat = cPickle.loads(s)
  274. except:
  275.     print TestFailed, 're module cPickle'
  276.  
  277. # constants
  278. test(r"""sre.I""", sre.IGNORECASE)
  279. test(r"""sre.L""", sre.LOCALE)
  280. test(r"""sre.M""", sre.MULTILINE)
  281. test(r"""sre.S""", sre.DOTALL)
  282. test(r"""sre.X""", sre.VERBOSE)
  283. test(r"""sre.T""", sre.TEMPLATE)
  284. test(r"""sre.U""", sre.UNICODE)
  285.  
  286. for flags in [sre.I, sre.M, sre.X, sre.S, sre.L, sre.T, sre.U]:
  287.     try:
  288.         r = sre.compile('^pattern$', flags)
  289.     except:
  290.         print 'Exception raised on flag', flags
  291.  
  292. if verbose:
  293.     print 'Test engine limitations'
  294.  
  295. # Try nasty case that overflows the straightforward recursive
  296. # implementation of repeated groups.
  297. test("sre.match('(x)*', 50000*'x').span()", (0, 50000), RuntimeError)
  298. test("sre.match(r'(x)*y', 50000*'x'+'y').span()", (0, 50001), RuntimeError)
  299. test("sre.match(r'(x)*?y', 50000*'x'+'y').span()", (0, 50001), RuntimeError)
  300.  
  301. from re_tests import *
  302.  
  303. if verbose:
  304.     print 'Running re_tests test suite'
  305. else:
  306.     # To save time, only run the first and last 10 tests
  307.     #tests = tests[:10] + tests[-10:]
  308.     pass
  309.  
  310. for t in tests:
  311.     sys.stdout.flush()
  312.     pattern=s=outcome=repl=expected=None
  313.     if len(t)==5:
  314.         pattern, s, outcome, repl, expected = t
  315.     elif len(t)==3:
  316.         pattern, s, outcome = t
  317.     else:
  318.         raise ValueError, ('Test tuples should have 3 or 5 fields',t)
  319.  
  320.     try:
  321.         obj=sre.compile(pattern)
  322.     except sre.error:
  323.         if outcome==SYNTAX_ERROR: pass  # Expected a syntax error
  324.         else:
  325.             print '=== Syntax error:', t
  326.     except KeyboardInterrupt: raise KeyboardInterrupt
  327.     except:
  328.         print '*** Unexpected error ***', t
  329.         if verbose:
  330.             traceback.print_exc(file=sys.stdout)
  331.     else:
  332.         try:
  333.             result=obj.search(s)
  334.         except (sre.error), msg:
  335.             print '=== Unexpected exception', t, repr(msg)
  336.         if outcome==SYNTAX_ERROR:
  337.             print '=== Compiled incorrectly', t
  338.         elif outcome==FAIL:
  339.             if result is None: pass   # No match, as expected
  340.             else: print '=== Succeeded incorrectly', t
  341.         elif outcome==SUCCEED:
  342.             if result is not None:
  343.                 # Matched, as expected, so now we compute the
  344.                 # result string and compare it to our expected result.
  345.                 start, end = result.span(0)
  346.                 vardict={'found': result.group(0),
  347.                          'groups': result.group(),
  348.                          'flags': result.re.flags}
  349.                 for i in range(1, 100):
  350.                     try:
  351.                         gi = result.group(i)
  352.                         # Special hack because else the string concat fails:
  353.                         if gi is None:
  354.                             gi = "None"
  355.                     except IndexError:
  356.                         gi = "Error"
  357.                     vardict['g%d' % i] = gi
  358.                 for i in result.re.groupindex.keys():
  359.                     try:
  360.                         gi = result.group(i)
  361.                         if gi is None:
  362.                             gi = "None"
  363.                     except IndexError:
  364.                         gi = "Error"
  365.                     vardict[i] = gi
  366.                 repl=eval(repl, vardict)
  367.                 if repl!=expected:
  368.                     print '=== grouping error', t,
  369.                     print repr(repl)+' should be '+repr(expected)
  370.             else:
  371.                 print '=== Failed incorrectly', t
  372.                 continue
  373.  
  374.             # Try the match on a unicode string, and check that it
  375.             # still succeeds.
  376.             try:
  377.                 u = unicode(s, "latin-1")
  378.             except NameError:
  379.                 pass
  380.             except TypeError:
  381.                 continue # skip unicode test strings
  382.             else:
  383.                 result=obj.search(u)
  384.                 if result==None:
  385.                     print '=== Fails on unicode match', t
  386.  
  387.             # Try the match on a unicode pattern, and check that it
  388.             # still succeeds.
  389.             try:
  390.                 u = unicode(pattern, "latin-1")
  391.             except NameError:
  392.                 pass
  393.             else:
  394.                 obj=sre.compile(u)
  395.                 result=obj.search(s)
  396.                 if result==None:
  397.                     print '=== Fails on unicode pattern match', t
  398.  
  399.             # Try the match with the search area limited to the extent
  400.             # of the match and see if it still succeeds.  \B will
  401.             # break (because it won't match at the end or start of a
  402.             # string), so we'll ignore patterns that feature it.
  403.  
  404.             if pattern[:2]!='\\B' and pattern[-2:]!='\\B':
  405.                 obj=sre.compile(pattern)
  406.                 result=obj.search(s, result.start(0), result.end(0)+1)
  407.                 if result==None:
  408.                     print '=== Failed on range-limited match', t
  409.  
  410.             # Try the match with IGNORECASE enabled, and check that it
  411.             # still succeeds.
  412.             obj=sre.compile(pattern, sre.IGNORECASE)
  413.             result=obj.search(s)
  414.             if result==None:
  415.                 print '=== Fails on case-insensitive match', t
  416.  
  417.             # Try the match with LOCALE enabled, and check that it
  418.             # still succeeds.
  419.             obj=sre.compile(pattern, sre.LOCALE)
  420.             result=obj.search(s)
  421.             if result==None:
  422.                 print '=== Fails on locale-sensitive match', t
  423.  
  424.             # Try the match with UNICODE locale enabled, and check
  425.             # that it still succeeds.
  426.             if have_unicode:
  427.                 obj=sre.compile(pattern, sre.UNICODE)
  428.                 result=obj.search(s)
  429.                 if result==None:
  430.                     print '=== Fails on unicode-sensitive match', t
  431.