home *** CD-ROM | disk | FTP | other *** search
/ Freelog 33 / Freelog033.iso / Progr / Python-2.2.1.exe / REGRTEST.PY < prev    next >
Encoding:
Python Source  |  2001-12-14  |  19.4 KB  |  670 lines

  1. #! /usr/bin/env python
  2.  
  3. """Regression test.
  4.  
  5. This will find all modules whose name is "test_*" in the test
  6. directory, and run them.  Various command line options provide
  7. additional facilities.
  8.  
  9. Command line options:
  10.  
  11. -v: verbose   -- run tests in verbose mode with output to stdout
  12. -q: quiet     -- don't print anything except if a test fails
  13. -g: generate  -- write the output file for a test instead of comparing it
  14. -x: exclude   -- arguments are tests to *exclude*
  15. -s: single    -- run only a single test (see below)
  16. -r: random    -- randomize test execution order
  17. -l: findleaks -- if GC is available detect tests that leak memory
  18. -u: use       -- specify which special resource intensive tests to run
  19. -h: help      -- print this text and exit
  20.  
  21. If non-option arguments are present, they are names for tests to run,
  22. unless -x is given, in which case they are names for tests not to run.
  23. If no test names are given, all tests are run.
  24.  
  25. -v is incompatible with -g and does not compare test output files.
  26.  
  27. -s means to run only a single test and exit.  This is useful when doing memory
  28. analysis on the Python interpreter (which tend to consume to many resources to
  29. run the full regression test non-stop).  The file /tmp/pynexttest is read to
  30. find the next test to run.  If this file is missing, the first test_*.py file
  31. in testdir or on the command line is used.  (actually tempfile.gettempdir() is
  32. used instead of /tmp).
  33.  
  34. -u is used to specify which special resource intensive tests to run, such as
  35. those requiring large file support or network connectivity.  The argument is a
  36. comma-separated list of words indicating the resources to test.  Currently
  37. only the following are defined:
  38.  
  39.     curses -    Tests that use curses and will modify the terminal's
  40.                 state and output modes.
  41.  
  42.     largefile - It is okay to run some test that may create huge files.  These
  43.                 tests can take a long time and may consume >2GB of disk space
  44.                 temporarily.
  45.  
  46.     network -   It is okay to run tests that use external network resource,
  47.                 e.g. testing SSL support for sockets.
  48. """
  49.  
  50. import sys
  51. import os
  52. import getopt
  53. import traceback
  54. import random
  55. import StringIO
  56.  
  57. import test_support
  58.  
  59. def usage(code, msg=''):
  60.     print __doc__
  61.     if msg: print msg
  62.     sys.exit(code)
  63.  
  64.  
  65. def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0,
  66.          exclude=0, single=0, randomize=0, findleaks=0,
  67.          use_resources=None):
  68.     """Execute a test suite.
  69.  
  70.     This also parses command-line options and modifies its behavior
  71.     accordingly.
  72.  
  73.     tests -- a list of strings containing test names (optional)
  74.     testdir -- the directory in which to look for tests (optional)
  75.  
  76.     Users other than the Python test suite will certainly want to
  77.     specify testdir; if it's omitted, the directory containing the
  78.     Python test suite is searched for.
  79.  
  80.     If the tests argument is omitted, the tests listed on the
  81.     command-line will be used.  If that's empty, too, then all *.py
  82.     files beginning with test_ will be used.
  83.  
  84.     The other default arguments (verbose, quiet, generate, exclude, single,
  85.     randomize, findleaks, and use_resources) allow programmers calling main()
  86.     directly to set the values that would normally be set by flags on the
  87.     command line.
  88.  
  89.     """
  90.  
  91.     test_support.record_original_stdout(sys.stdout)
  92.     try:
  93.         opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrlu:',
  94.                                    ['help', 'verbose', 'quiet', 'generate',
  95.                                     'exclude', 'single', 'random',
  96.                                     'findleaks', 'use='])
  97.     except getopt.error, msg:
  98.         usage(2, msg)
  99.  
  100.     # Defaults
  101.     if use_resources is None:
  102.         use_resources = []
  103.     for o, a in opts:
  104.         if o in ('-h', '--help'):
  105.             usage(0)
  106.         elif o in ('-v', '--verbose'):
  107.             verbose += 1
  108.         elif o in ('-q', '--quiet'):
  109.             quiet = 1;
  110.             verbose = 0
  111.         elif o in ('-g', '--generate'):
  112.             generate = 1
  113.         elif o in ('-x', '--exclude'):
  114.             exclude = 1
  115.         elif o in ('-s', '--single'):
  116.             single = 1
  117.         elif o in ('-r', '--randomize'):
  118.             randomize = 1
  119.         elif o in ('-l', '--findleaks'):
  120.             findleaks = 1
  121.         elif o in ('-u', '--use'):
  122.             u = [x.lower() for x in a.split(',')]
  123.             for r in u:
  124.                 if r not in ('curses', 'largefile', 'network'):
  125.                     usage(1, 'Invalid -u/--use option: %s' % a)
  126.             use_resources.extend(u)
  127.     if generate and verbose:
  128.         usage(2, "-g and -v don't go together!")
  129.  
  130.     good = []
  131.     bad = []
  132.     skipped = []
  133.  
  134.     if findleaks:
  135.         try:
  136.             import gc
  137.         except ImportError:
  138.             print 'No GC available, disabling findleaks.'
  139.             findleaks = 0
  140.         else:
  141.             # Uncomment the line below to report garbage that is not
  142.             # freeable by reference counting alone.  By default only
  143.             # garbage that is not collectable by the GC is reported.
  144.             #gc.set_debug(gc.DEBUG_SAVEALL)
  145.             found_garbage = []
  146.  
  147.     if single:
  148.         from tempfile import gettempdir
  149.         filename = os.path.join(gettempdir(), 'pynexttest')
  150.         try:
  151.             fp = open(filename, 'r')
  152.             next = fp.read().strip()
  153.             tests = [next]
  154.             fp.close()
  155.         except IOError:
  156.             pass
  157.     for i in range(len(args)):
  158.         # Strip trailing ".py" from arguments
  159.         if args[i][-3:] == os.extsep+'py':
  160.             args[i] = args[i][:-3]
  161.     stdtests = STDTESTS[:]
  162.     nottests = NOTTESTS[:]
  163.     if exclude:
  164.         for arg in args:
  165.             if arg in stdtests:
  166.                 stdtests.remove(arg)
  167.         nottests[:0] = args
  168.         args = []
  169.     tests = tests or args or findtests(testdir, stdtests, nottests)
  170.     if single:
  171.         tests = tests[:1]
  172.     if randomize:
  173.         random.shuffle(tests)
  174.     test_support.verbose = verbose      # Tell tests to be moderately quiet
  175.     test_support.use_resources = use_resources
  176.     save_modules = sys.modules.keys()
  177.     for test in tests:
  178.         if not quiet:
  179.             print test
  180.         ok = runtest(test, generate, verbose, quiet, testdir)
  181.         if ok > 0:
  182.             good.append(test)
  183.         elif ok == 0:
  184.             bad.append(test)
  185.         else:
  186.             skipped.append(test)
  187.         if findleaks:
  188.             gc.collect()
  189.             if gc.garbage:
  190.                 print "Warning: test created", len(gc.garbage),
  191.                 print "uncollectable object(s)."
  192.                 # move the uncollectable objects somewhere so we don't see
  193.                 # them again
  194.                 found_garbage.extend(gc.garbage)
  195.                 del gc.garbage[:]
  196.         # Unload the newly imported modules (best effort finalization)
  197.         for module in sys.modules.keys():
  198.             if module not in save_modules and module.startswith("test."):
  199.                 test_support.unload(module)
  200.  
  201.     # The lists won't be sorted if running with -r
  202.     good.sort()
  203.     bad.sort()
  204.     skipped.sort()
  205.  
  206.     if good and not quiet:
  207.         if not bad and not skipped and len(good) > 1:
  208.             print "All",
  209.         print count(len(good), "test"), "OK."
  210.         if verbose:
  211.             print "CAUTION:  stdout isn't compared in verbose mode:  a test"
  212.             print "that passes in verbose mode may fail without it."
  213.     if bad:
  214.         print count(len(bad), "test"), "failed:"
  215.         printlist(bad)
  216.     if skipped and not quiet:
  217.         print count(len(skipped), "test"), "skipped:"
  218.         printlist(skipped)
  219.  
  220.         e = _ExpectedSkips()
  221.         plat = sys.platform
  222.         if e.isvalid():
  223.             surprise = _Set(skipped) - e.getexpected()
  224.             if surprise:
  225.                 print count(len(surprise), "skip"), \
  226.                       "unexpected on", plat + ":"
  227.                 printlist(surprise)
  228.             else:
  229.                 print "Those skips are all expected on", plat + "."
  230.         else:
  231.             print "Ask someone to teach regrtest.py about which tests are"
  232.             print "expected to get skipped on", plat + "."
  233.  
  234.     if single:
  235.         alltests = findtests(testdir, stdtests, nottests)
  236.         for i in range(len(alltests)):
  237.             if tests[0] == alltests[i]:
  238.                 if i == len(alltests) - 1:
  239.                     os.unlink(filename)
  240.                 else:
  241.                     fp = open(filename, 'w')
  242.                     fp.write(alltests[i+1] + '\n')
  243.                     fp.close()
  244.                 break
  245.         else:
  246.             os.unlink(filename)
  247.  
  248.     sys.exit(len(bad) > 0)
  249.  
  250.  
  251. STDTESTS = [
  252.     'test_grammar',
  253.     'test_opcodes',
  254.     'test_operations',
  255.     'test_builtin',
  256.     'test_exceptions',
  257.     'test_types',
  258.    ]
  259.  
  260. NOTTESTS = [
  261.     'test_support',
  262.     'test_b1',
  263.     'test_b2',
  264.     'test_future1',
  265.     'test_future2',
  266.     'test_future3',
  267.     ]
  268.  
  269. def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
  270.     """Return a list of all applicable test modules."""
  271.     if not testdir: testdir = findtestdir()
  272.     names = os.listdir(testdir)
  273.     tests = []
  274.     for name in names:
  275.         if name[:5] == "test_" and name[-3:] == os.extsep+"py":
  276.             modname = name[:-3]
  277.             if modname not in stdtests and modname not in nottests:
  278.                 tests.append(modname)
  279.     tests.sort()
  280.     return stdtests + tests
  281.  
  282. def runtest(test, generate, verbose, quiet, testdir = None):
  283.     """Run a single test.
  284.     test -- the name of the test
  285.     generate -- if true, generate output, instead of running the test
  286.     and comparing it to a previously created output file
  287.     verbose -- if true, print more messages
  288.     quiet -- if true, don't print 'skipped' messages (probably redundant)
  289.     testdir -- test directory
  290.     """
  291.     test_support.unload(test)
  292.     if not testdir: testdir = findtestdir()
  293.     outputdir = os.path.join(testdir, "output")
  294.     outputfile = os.path.join(outputdir, test)
  295.     if verbose:
  296.         cfp = None
  297.     else:
  298.         cfp = StringIO.StringIO()
  299.     try:
  300.         save_stdout = sys.stdout
  301.         try:
  302.             if cfp:
  303.                 sys.stdout = cfp
  304.                 print test              # Output file starts with test name
  305.             the_module = __import__(test, globals(), locals(), [])
  306.             # Most tests run to completion simply as a side-effect of
  307.             # being imported.  For the benefit of tests that can't run
  308.             # that way (like test_threaded_import), explicitly invoke
  309.             # their test_main() function (if it exists).
  310.             indirect_test = getattr(the_module, "test_main", None)
  311.             if indirect_test is not None:
  312.                 indirect_test()
  313.         finally:
  314.             sys.stdout = save_stdout
  315.     except (ImportError, test_support.TestSkipped), msg:
  316.         if not quiet:
  317.             print "test", test, "skipped --", msg
  318.         return -1
  319.     except KeyboardInterrupt:
  320.         raise
  321.     except test_support.TestFailed, msg:
  322.         print "test", test, "failed --", msg
  323.         return 0
  324.     except:
  325.         type, value = sys.exc_info()[:2]
  326.         print "test", test, "crashed --", str(type) + ":", value
  327.         if verbose:
  328.             traceback.print_exc(file=sys.stdout)
  329.         return 0
  330.     else:
  331.         if not cfp:
  332.             return 1
  333.         output = cfp.getvalue()
  334.         if generate:
  335.             if output == test + "\n":
  336.                 if os.path.exists(outputfile):
  337.                     # Write it since it already exists (and the contents
  338.                     # may have changed), but let the user know it isn't
  339.                     # needed:
  340.                     print "output file", outputfile, \
  341.                           "is no longer needed; consider removing it"
  342.                 else:
  343.                     # We don't need it, so don't create it.
  344.                     return 1
  345.             fp = open(outputfile, "w")
  346.             fp.write(output)
  347.             fp.close()
  348.             return 1
  349.         if os.path.exists(outputfile):
  350.             fp = open(outputfile, "r")
  351.             expected = fp.read()
  352.             fp.close()
  353.         else:
  354.             expected = test + "\n"
  355.         if output == expected:
  356.             return 1
  357.         print "test", test, "produced unexpected output:"
  358.         reportdiff(expected, output)
  359.         return 0
  360.  
  361. def reportdiff(expected, output):
  362.     import difflib
  363.     print "*" * 70
  364.     a = expected.splitlines(1)
  365.     b = output.splitlines(1)
  366.     sm = difflib.SequenceMatcher(a=a, b=b)
  367.     tuples = sm.get_opcodes()
  368.  
  369.     def pair(x0, x1):
  370.         # x0:x1 are 0-based slice indices; convert to 1-based line indices.
  371.         x0 += 1
  372.         if x0 >= x1:
  373.             return "line " + str(x0)
  374.         else:
  375.             return "lines %d-%d" % (x0, x1)
  376.  
  377.     for op, a0, a1, b0, b1 in tuples:
  378.         if op == 'equal':
  379.             pass
  380.  
  381.         elif op == 'delete':
  382.             print "***", pair(a0, a1), "of expected output missing:"
  383.             for line in a[a0:a1]:
  384.                 print "-", line,
  385.  
  386.         elif op == 'replace':
  387.             print "*** mismatch between", pair(a0, a1), "of expected", \
  388.                   "output and", pair(b0, b1), "of actual output:"
  389.             for line in difflib.ndiff(a[a0:a1], b[b0:b1]):
  390.                 print line,
  391.  
  392.         elif op == 'insert':
  393.             print "***", pair(b0, b1), "of actual output doesn't appear", \
  394.                   "in expected output after line", str(a1)+":"
  395.             for line in b[b0:b1]:
  396.                 print "+", line,
  397.  
  398.         else:
  399.             print "get_opcodes() returned bad tuple?!?!", (op, a0, a1, b0, b1)
  400.  
  401.     print "*" * 70
  402.  
  403. def findtestdir():
  404.     if __name__ == '__main__':
  405.         file = sys.argv[0]
  406.     else:
  407.         file = __file__
  408.     testdir = os.path.dirname(file) or os.curdir
  409.     return testdir
  410.  
  411. def count(n, word):
  412.     if n == 1:
  413.         return "%d %s" % (n, word)
  414.     else:
  415.         return "%d %ss" % (n, word)
  416.  
  417. def printlist(x, width=70, indent=4):
  418.     """Print the elements of a sequence to stdout.
  419.  
  420.     Optional arg width (default 70) is the maximum line length.
  421.     Optional arg indent (default 4) is the number of blanks with which to
  422.     begin each line.
  423.     """
  424.  
  425.     line = ' ' * indent
  426.     for one in map(str, x):
  427.         w = len(line) + len(one)
  428.         if line[-1:] == ' ':
  429.             pad = ''
  430.         else:
  431.             pad = ' '
  432.             w += 1
  433.         if w > width:
  434.             print line
  435.             line = ' ' * indent + one
  436.         else:
  437.             line += pad + one
  438.     if len(line) > indent:
  439.         print line
  440.  
  441. class _Set:
  442.     def __init__(self, seq=[]):
  443.         data = self.data = {}
  444.         for x in seq:
  445.             data[x] = 1
  446.  
  447.     def __len__(self):
  448.         return len(self.data)
  449.  
  450.     def __sub__(self, other):
  451.         "Return set of all elements in self not in other."
  452.         result = _Set()
  453.         data = result.data = self.data.copy()
  454.         for x in other.data:
  455.             if x in data:
  456.                 del data[x]
  457.         return result
  458.  
  459.     def __iter__(self):
  460.         return iter(self.data)
  461.  
  462.     def tolist(self, sorted=1):
  463.         "Return _Set elements as a list."
  464.         data = self.data.keys()
  465.         if sorted:
  466.             data.sort()
  467.         return data
  468.  
  469. _expectations = {
  470.     'win32':
  471.         """
  472.         test_al
  473.         test_cd
  474.         test_cl
  475.         test_commands
  476.         test_crypt
  477.         test_curses
  478.         test_dbm
  479.         test_dl
  480.         test_fcntl
  481.         test_fork1
  482.         test_gdbm
  483.         test_gl
  484.         test_grp
  485.         test_imgfile
  486.         test_largefile
  487.         test_linuxaudiodev
  488.         test_mhlib
  489.         test_nis
  490.         test_openpty
  491.         test_poll
  492.         test_pty
  493.         test_pwd
  494.         test_signal
  495.         test_socket_ssl
  496.         test_socketserver
  497.         test_sunaudiodev
  498.         test_timing
  499.         """,
  500.     'linux2':
  501.         """
  502.         test_al
  503.         test_cd
  504.         test_cl
  505.         test_curses
  506.         test_dl
  507.         test_gl
  508.         test_imgfile
  509.         test_largefile
  510.         test_nis
  511.         test_ntpath
  512.         test_socket_ssl
  513.         test_socketserver
  514.         test_sunaudiodev
  515.         test_unicode_file
  516.         test_winreg
  517.         test_winsound
  518.         """,
  519.    'mac':
  520.         """
  521.         test_al
  522.         test_bsddb
  523.         test_cd
  524.         test_cl
  525.         test_commands
  526.         test_crypt
  527.         test_curses
  528.         test_dbm
  529.         test_dl
  530.         test_fcntl
  531.         test_fork1
  532.         test_gl
  533.         test_grp
  534.         test_imgfile
  535.         test_largefile
  536.         test_linuxaudiodev
  537.         test_locale
  538.         test_mmap
  539.         test_nis
  540.         test_ntpath
  541.         test_openpty
  542.         test_poll
  543.         test_popen2
  544.         test_pty
  545.         test_pwd
  546.         test_signal
  547.         test_socket_ssl
  548.         test_socketserver
  549.         test_sunaudiodev
  550.         test_sundry
  551.         test_timing
  552.         test_unicode_file
  553.         test_winreg
  554.         test_winsound
  555.         """,
  556.     'unixware5':
  557.         """
  558.         test_al
  559.         test_bsddb
  560.         test_cd
  561.         test_cl
  562.         test_dl
  563.         test_gl
  564.         test_imgfile
  565.         test_largefile
  566.         test_linuxaudiodev
  567.         test_minidom
  568.         test_nis
  569.         test_ntpath
  570.         test_openpty
  571.         test_pyexpat
  572.         test_sax
  573.         test_socketserver
  574.         test_sunaudiodev
  575.         test_sundry
  576.         test_unicode_file
  577.         test_winreg
  578.         test_winsound
  579.         """,
  580.     'riscos':
  581.         """
  582.         test_al
  583.         test_asynchat
  584.         test_bsddb
  585.         test_cd
  586.         test_cl
  587.         test_commands
  588.         test_crypt
  589.         test_dbm
  590.         test_dl
  591.         test_fcntl
  592.         test_fork1
  593.         test_gdbm
  594.         test_gl
  595.         test_grp
  596.         test_imgfile
  597.         test_largefile
  598.         test_linuxaudiodev
  599.         test_locale
  600.         test_mmap
  601.         test_nis
  602.         test_ntpath
  603.         test_openpty
  604.         test_poll
  605.         test_popen2
  606.         test_pty
  607.         test_pwd
  608.         test_socket_ssl
  609.         test_socketserver
  610.         test_strop
  611.         test_sunaudiodev
  612.         test_sundry
  613.         test_thread
  614.         test_threaded_import
  615.         test_threadedtempfile
  616.         test_threading
  617.         test_timing
  618.         test_unicode_file
  619.         test_winreg
  620.         test_winsound
  621.         """,
  622.     'darwin':
  623.         """
  624.         test_al
  625.         test_cd
  626.         test_cl
  627.         test_curses
  628.         test_dl
  629.         test_gdbm
  630.         test_gl
  631.         test_imgfile
  632.         test_largefile
  633.         test_linuxaudiodev
  634.         test_minidom
  635.         test_nis
  636.         test_ntpath
  637.         test_poll
  638.         test_socket_ssl
  639.         test_socketserver
  640.         test_sunaudiodev
  641.         test_unicode_file
  642.         test_winreg
  643.         test_winsound
  644.         """,
  645. }
  646.  
  647. class _ExpectedSkips:
  648.     def __init__(self):
  649.         self.valid = 0
  650.         if _expectations.has_key(sys.platform):
  651.             s = _expectations[sys.platform]
  652.             self.expected = _Set(s.split())
  653.             self.valid = 1
  654.  
  655.     def isvalid(self):
  656.         "Return true iff _ExpectedSkips knows about the current platform."
  657.         return self.valid
  658.  
  659.     def getexpected(self):
  660.         """Return set of test names we expect to skip on current platform.
  661.  
  662.         self.isvalid() must be true.
  663.         """
  664.  
  665.         assert self.isvalid()
  666.         return self.expected
  667.  
  668. if __name__ == '__main__':
  669.     main()
  670.