home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_Lib_test_regrtest.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  11.2 KB  |  340 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. --have-resources   -- run tests that require large resources (time/space)
  19.  
  20. If non-option arguments are present, they are names for tests to run,
  21. unless -x is given, in which case they are names for tests not to run.
  22. If no test names are given, all tests are run.
  23.  
  24. -v is incompatible with -g and does not compare test output files.
  25.  
  26. -s means to run only a single test and exit.  This is useful when doing memory
  27. analysis on the Python interpreter (which tend to consume to many resources to
  28. run the full regression test non-stop).  The file /tmp/pynexttest is read to
  29. find the next test to run.  If this file is missing, the first test_*.py file
  30. in testdir or on the command line is used.  (actually tempfile.gettempdir() is
  31. used instead of /tmp).
  32.  
  33. """
  34.  
  35. import sys
  36. import os
  37. import getopt
  38. import traceback
  39. import random
  40.  
  41. import test_support
  42.  
  43. def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0,
  44.          exclude=0, single=0, randomize=0, findleaks=0,
  45.          use_large_resources=0):
  46.     """Execute a test suite.
  47.  
  48.     This also parses command-line options and modifies its behavior
  49.     accordingly.
  50.  
  51.     tests -- a list of strings containing test names (optional)
  52.     testdir -- the directory in which to look for tests (optional)
  53.  
  54.     Users other than the Python test suite will certainly want to
  55.     specify testdir; if it's omitted, the directory containing the
  56.     Python test suite is searched for.
  57.  
  58.     If the tests argument is omitted, the tests listed on the
  59.     command-line will be used.  If that's empty, too, then all *.py
  60.     files beginning with test_ will be used.
  61.  
  62.     The other seven default arguments (verbose, quiet, generate, exclude,
  63.     single, randomize, and findleaks) allow programmers calling main()
  64.     directly to set the values that would normally be set by flags on the
  65.     command line.
  66.  
  67.     """
  68.  
  69.     try:
  70.         opts, args = getopt.getopt(sys.argv[1:], 'vgqxsrl', ['have-resources'])
  71.     except getopt.error, msg:
  72.         print msg
  73.         print __doc__
  74.         return 2
  75.     for o, a in opts:
  76.         if o == '-v': verbose = verbose+1
  77.         if o == '-q': quiet = 1; verbose = 0
  78.         if o == '-g': generate = 1
  79.         if o == '-x': exclude = 1
  80.         if o == '-s': single = 1
  81.         if o == '-r': randomize = 1
  82.         if o == '-l': findleaks = 1
  83.         if o == '--have-resources': use_large_resources = 1
  84.     if generate and verbose:
  85.         print "-g and -v don't go together!"
  86.         return 2
  87.     good = []
  88.     bad = []
  89.     skipped = []
  90.  
  91.     if findleaks:
  92.         try:
  93.             import gc
  94.         except ImportError:
  95.             print 'No GC available, disabling findleaks.'
  96.             findleaks = 0
  97.         else:
  98.             # Uncomment the line below to report garbage that is not
  99.             # freeable by reference counting alone.  By default only
  100.             # garbage that is not collectable by the GC is reported.
  101.             #gc.set_debug(gc.DEBUG_SAVEALL)
  102.             found_garbage = []
  103.  
  104.     if single:
  105.         from tempfile import gettempdir
  106.         filename = os.path.join(gettempdir(), 'pynexttest')
  107.         try:
  108.             fp = open(filename, 'r')
  109.             next = fp.read().strip()
  110.             tests = [next]
  111.             fp.close()
  112.         except IOError:
  113.             pass
  114.     for i in range(len(args)):
  115.         # Strip trailing ".py" from arguments
  116.         if args[i][-3:] == '.py':
  117.             args[i] = args[i][:-3]
  118.     stdtests = STDTESTS[:]
  119.     nottests = NOTTESTS[:]
  120.     if exclude:
  121.         for arg in args:
  122.             if arg in stdtests:
  123.                 stdtests.remove(arg)
  124.         nottests[:0] = args
  125.         args = []
  126.     tests = tests or args or findtests(testdir, stdtests, nottests)
  127.     if single:
  128.         tests = tests[:1]
  129.     if randomize:
  130.         random.shuffle(tests)
  131.     test_support.verbose = verbose      # Tell tests to be moderately quiet
  132.     test_support.use_large_resources = use_large_resources
  133.     save_modules = sys.modules.keys()
  134.     for test in tests:
  135.         if not quiet:
  136.             print test
  137.         ok = runtest(test, generate, verbose, quiet, testdir)
  138.         if ok > 0:
  139.             good.append(test)
  140.         elif ok == 0:
  141.             bad.append(test)
  142.         else:
  143.             skipped.append(test)
  144.         if findleaks:
  145.             gc.collect()
  146.             if gc.garbage:
  147.                 print "Warning: test created", len(gc.garbage),
  148.                 print "uncollectable object(s)."
  149.                 # move the uncollectable objects somewhere so we don't see
  150.                 # them again
  151.                 found_garbage.extend(gc.garbage)
  152.                 del gc.garbage[:]
  153.         # Unload the newly imported modules (best effort finalization)
  154.         for module in sys.modules.keys():
  155.             if module not in save_modules and module.startswith("test."):
  156.                 test_support.unload(module)
  157.     if good and not quiet:
  158.         if not bad and not skipped and len(good) > 1:
  159.             print "All",
  160.         print count(len(good), "test"), "OK."
  161.         if verbose:
  162.             print "CAUTION:  stdout isn't compared in verbose mode:  a test"
  163.             print "that passes in verbose mode may fail without it."
  164.     if bad:
  165.         print count(len(bad), "test"), "failed:",
  166.         print " ".join(bad)
  167.     if skipped and not quiet:
  168.         print count(len(skipped), "test"), "skipped:",
  169.         print " ".join(skipped)
  170.  
  171.     if single:
  172.         alltests = findtests(testdir, stdtests, nottests)
  173.         for i in range(len(alltests)):
  174.             if tests[0] == alltests[i]:
  175.                 if i == len(alltests) - 1:
  176.                     os.unlink(filename)
  177.                 else:
  178.                     fp = open(filename, 'w')
  179.                     fp.write(alltests[i+1] + '\n')
  180.                     fp.close()
  181.                 break
  182.         else:
  183.             os.unlink(filename)
  184.  
  185.     return len(bad) > 0
  186.  
  187. STDTESTS = [
  188.     'test_grammar',
  189.     'test_opcodes',
  190.     'test_operations',
  191.     'test_builtin',
  192.     'test_exceptions',
  193.     'test_types',
  194.    ]
  195.  
  196. NOTTESTS = [
  197.     'test_support',
  198.     'test_b1',
  199.     'test_b2',
  200.     'test_future1',
  201.     'test_future2',
  202.     'test_future3',
  203.     'test_future4',
  204.     'test_future5',
  205.     'test_future6',
  206.     'test_future7',
  207.     ]
  208.  
  209. def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
  210.     """Return a list of all applicable test modules."""
  211.     if not testdir: testdir = findtestdir()
  212.     names = os.listdir(testdir)
  213.     tests = []
  214.     for name in names:
  215.         if name[:5] == "test_" and name[-3:] == ".py":
  216.             modname = name[:-3]
  217.             if modname not in stdtests and modname not in nottests:
  218.                 tests.append(modname)
  219.     tests.sort()
  220.     return stdtests + tests
  221.  
  222. def runtest(test, generate, verbose, quiet, testdir = None):
  223.     """Run a single test.
  224.     test -- the name of the test
  225.     generate -- if true, generate output, instead of running the test
  226.     and comparing it to a previously created output file
  227.     verbose -- if true, print more messages
  228.     quiet -- if true, don't print 'skipped' messages (probably redundant)
  229.     testdir -- test directory
  230.     """
  231.     test_support.unload(test)
  232.     if not testdir: testdir = findtestdir()
  233.     outputdir = os.path.join(testdir, "output")
  234.     outputfile = os.path.join(outputdir, test)
  235.     try:
  236.         if generate:
  237.             cfp = open(outputfile, "w")
  238.         elif verbose:
  239.             cfp = sys.stdout
  240.         else:
  241.             cfp = Compare(outputfile)
  242.     except IOError:
  243.         cfp = None
  244.         print "Warning: can't open", outputfile
  245.     try:
  246.         save_stdout = sys.stdout
  247.         try:
  248.             if cfp:
  249.                 sys.stdout = cfp
  250.                 print test              # Output file starts with test name
  251.             __import__(test, globals(), locals(), [])
  252.             if cfp and not (generate or verbose):
  253.                 cfp.close()
  254.         finally:
  255.             sys.stdout = save_stdout
  256.     except (ImportError, test_support.TestSkipped), msg:
  257.         if not quiet:
  258.             print "test", test,
  259.             print "skipped -- ", msg
  260.         return -1
  261.     except KeyboardInterrupt:
  262.         raise
  263.     except test_support.TestFailed, msg:
  264.         print "test", test, "failed --", msg
  265.         return 0
  266.     except:
  267.         type, value = sys.exc_info()[:2]
  268.         print "test", test, "crashed --", str(type) + ":", value
  269.         if verbose:
  270.             traceback.print_exc(file=sys.stdout)
  271.         return 0
  272.     else:
  273.         return 1
  274.  
  275. def findtestdir():
  276.     if __name__ == '__main__':
  277.         file = sys.argv[0]
  278.     else:
  279.         file = __file__
  280.     testdir = os.path.dirname(file) or os.curdir
  281.     return testdir
  282.  
  283. def count(n, word):
  284.     if n == 1:
  285.         return "%d %s" % (n, word)
  286.     else:
  287.         return "%d %ss" % (n, word)
  288.  
  289. class Compare:
  290.  
  291.     def __init__(self, filename):
  292.         self.fp = open(filename, 'r')
  293.         self.stuffthatmatched = []
  294.  
  295.     def write(self, data):
  296.         expected = self.fp.read(len(data))
  297.         if data == expected:
  298.             self.stuffthatmatched.append(expected)
  299.         else:
  300.             # This Compare instance is spoofing stdout, so we need to write
  301.             # to stderr instead.
  302.             from sys import stderr as e
  303.             print >> e, "The actual stdout doesn't match the expected stdout."
  304.             if self.stuffthatmatched:
  305.                 print >> e, "This much did match (between asterisk lines):"
  306.                 print >> e, "*" * 70
  307.                 good = "".join(self.stuffthatmatched)
  308.                 e.write(good)
  309.                 if not good.endswith("\n"):
  310.                     e.write("\n")
  311.                 print >> e, "*" * 70
  312.                 print >> e, "Then ..."
  313.             else:
  314.                 print >> e, "The first write to stdout clashed:"
  315.             # Note that the prompts are the same length in next two lines.
  316.             # This is so what we expected and what we got line up.
  317.             print >> e, "We expected (repr):", `expected`
  318.             print >> e, "But instead we got:", `data`
  319.             raise test_support.TestFailed('Writing: ' + `data`+
  320.                                           ', expected: ' + `expected`)
  321.  
  322.     def writelines(self, listoflines):
  323.         map(self.write, listoflines)
  324.  
  325.     def flush(self):
  326.         pass
  327.  
  328.     def close(self):
  329.         leftover = self.fp.read()
  330.         if leftover:
  331.             raise test_support.TestFailed('Tail of expected stdout unseen: ' +
  332.                                           `leftover`)
  333.         self.fp.close()
  334.  
  335.     def isatty(self):
  336.         return 0
  337.  
  338. if __name__ == '__main__':
  339.     sys.exit(main())
  340.