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 / REGRTEST.PY < prev    next >
Encoding:
Python Source  |  2000-10-13  |  9.7 KB  |  307 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 Purifying
  27. the Python interpreter.  The file /tmp/pynexttest is read to find the next
  28. test to run.  If this file is missing, the first test_*.py file in testdir or
  29. on the command line is used.  (actually tempfile.gettempdir() is used instead
  30. of /tmp).
  31.  
  32. """
  33.  
  34. import sys
  35. import string
  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 = string.strip(fp.read())
  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 bad:
  162.         print count(len(bad), "test"), "failed:",
  163.         print string.join(bad)
  164.     if skipped and not quiet:
  165.         print count(len(skipped), "test"), "skipped:",
  166.         print string.join(skipped)
  167.  
  168.     if single:
  169.         alltests = findtests(testdir, stdtests, nottests)
  170.         for i in range(len(alltests)):
  171.             if tests[0] == alltests[i]:
  172.                 if i == len(alltests) - 1:
  173.                     os.unlink(filename)
  174.                 else:
  175.                     fp = open(filename, 'w')
  176.                     fp.write(alltests[i+1] + '\n')
  177.                     fp.close()
  178.                 break
  179.         else:
  180.             os.unlink(filename)
  181.  
  182.     return len(bad) > 0
  183.  
  184. STDTESTS = [
  185.     'test_grammar',
  186.     'test_opcodes',
  187.     'test_operations',
  188.     'test_builtin',
  189.     'test_exceptions',
  190.     'test_types',
  191.    ]
  192.  
  193. NOTTESTS = [
  194.     'test_support',
  195.     'test_b1',
  196.     'test_b2',
  197.     ]
  198.  
  199. def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
  200.     """Return a list of all applicable test modules."""
  201.     if not testdir: testdir = findtestdir()
  202.     names = os.listdir(testdir)
  203.     tests = []
  204.     for name in names:
  205.         if name[:5] == "test_" and name[-3:] == ".py":
  206.             modname = name[:-3]
  207.             if modname not in stdtests and modname not in nottests:
  208.                 tests.append(modname)
  209.     tests.sort()
  210.     return stdtests + tests
  211.  
  212. def runtest(test, generate, verbose, quiet, testdir = None):
  213.     """Run a single test.
  214.     test -- the name of the test
  215.     generate -- if true, generate output, instead of running the test
  216.     and comparing it to a previously created output file
  217.     verbose -- if true, print more messages
  218.     quiet -- if true, don't print 'skipped' messages (probably redundant)
  219.     testdir -- test directory
  220.     """
  221.     test_support.unload(test)
  222.     if not testdir: testdir = findtestdir()
  223.     outputdir = os.path.join(testdir, "output")
  224.     outputfile = os.path.join(outputdir, test)
  225.     try:
  226.         if generate:
  227.             cfp = open(outputfile, "w")
  228.         elif verbose:
  229.             cfp = sys.stdout
  230.         else:
  231.             cfp = Compare(outputfile)
  232.     except IOError:
  233.         cfp = None
  234.         print "Warning: can't open", outputfile
  235.     try:
  236.         save_stdout = sys.stdout
  237.         try:
  238.             if cfp:
  239.                 sys.stdout = cfp
  240.                 print test              # Output file starts with test name
  241.             __import__(test, globals(), locals(), [])
  242.             if cfp and not (generate or verbose):
  243.                 cfp.close()
  244.         finally:
  245.             sys.stdout = save_stdout
  246.     except (ImportError, test_support.TestSkipped), msg:
  247.         if not quiet:
  248.             print "test", test,
  249.             print "skipped -- ", msg
  250.         return -1
  251.     except KeyboardInterrupt:
  252.         raise
  253.     except test_support.TestFailed, msg:
  254.         print "test", test, "failed --", msg
  255.         return 0
  256.     except:
  257.         type, value = sys.exc_info()[:2]
  258.         print "test", test, "crashed --", str(type) + ":", value
  259.         if verbose:
  260.             traceback.print_exc(file=sys.stdout)
  261.         return 0
  262.     else:
  263.         return 1
  264.  
  265. def findtestdir():
  266.     if __name__ == '__main__':
  267.         file = sys.argv[0]
  268.     else:
  269.         file = __file__
  270.     testdir = os.path.dirname(file) or os.curdir
  271.     return testdir
  272.  
  273. def count(n, word):
  274.     if n == 1:
  275.         return "%d %s" % (n, word)
  276.     else:
  277.         return "%d %ss" % (n, word)
  278.  
  279. class Compare:
  280.  
  281.     def __init__(self, filename):
  282.         self.fp = open(filename, 'r')
  283.  
  284.     def write(self, data):
  285.         expected = self.fp.read(len(data))
  286.         if data <> expected:
  287.             raise test_support.TestFailed, \
  288.                     'Writing: '+`data`+', expected: '+`expected`
  289.  
  290.     def writelines(self, listoflines):
  291.         map(self.write, listoflines)
  292.  
  293.     def flush(self):
  294.         pass
  295.  
  296.     def close(self):
  297.         leftover = self.fp.read()
  298.         if leftover:
  299.             raise test_support.TestFailed, 'Unread: '+`leftover`
  300.         self.fp.close()
  301.  
  302.     def isatty(self):
  303.         return 0
  304.  
  305. if __name__ == '__main__':
  306.     sys.exit(main())
  307.