home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / python2.6 / test / regrtest.py < prev    next >
Encoding:
Python Source  |  2010-12-26  |  37.5 KB  |  1,207 lines

  1. #! /usr/bin/python2.6
  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. -w: verbose2   -- re-run failed tests in verbose mode
  13. -q: quiet      -- don't print anything except if a test fails
  14. -x: exclude    -- arguments are tests to *exclude*
  15. -s: single     -- run only a single test (see below)
  16. -S: slow       -- print the slowest 10 tests
  17. -r: random     -- randomize test execution order
  18. -f: fromfile   -- read names of tests to run from a file (see below)
  19. -l: findleaks  -- if GC is available detect tests that leak memory
  20. -u: use        -- specify which special resource intensive tests to run
  21. -h: help       -- print this text and exit
  22. -t: threshold  -- call gc.set_threshold(N)
  23. -T: coverage   -- turn on code coverage using the trace module
  24. -D: coverdir   -- Directory where coverage files are put
  25. -N: nocoverdir -- Put coverage files alongside modules
  26. -L: runleaks   -- run the leaks(1) command just before exit
  27. -R: huntrleaks -- search for reference leaks (needs debug build, v. slow)
  28. -M: memlimit   -- run very large memory-consuming tests
  29.  
  30. If non-option arguments are present, they are names for tests to run,
  31. unless -x is given, in which case they are names for tests not to run.
  32. If no test names are given, all tests are run.
  33.  
  34. -T turns on code coverage tracing with the trace module.
  35.  
  36. -D specifies the directory where coverage files are put.
  37.  
  38. -N Put coverage files alongside modules.
  39.  
  40. -s means to run only a single test and exit.  This is useful when
  41. doing memory analysis on the Python interpreter (which tend to consume
  42. too many resources to run the full regression test non-stop).  The
  43. file /tmp/pynexttest is read to find the next test to run.  If this
  44. file is missing, the first test_*.py file in testdir or on the command
  45. line is used.  (actually tempfile.gettempdir() is used instead of
  46. /tmp).
  47.  
  48. -f reads the names of tests from the file given as f's argument, one
  49. or more test names per line.  Whitespace is ignored.  Blank lines and
  50. lines beginning with '#' are ignored.  This is especially useful for
  51. whittling down failures involving interactions among tests.
  52.  
  53. -L causes the leaks(1) command to be run just before exit if it exists.
  54. leaks(1) is available on Mac OS X and presumably on some other
  55. FreeBSD-derived systems.
  56.  
  57. -R runs each test several times and examines sys.gettotalrefcount() to
  58. see if the test appears to be leaking references.  The argument should
  59. be of the form stab:run:fname where 'stab' is the number of times the
  60. test is run to let gettotalrefcount settle down, 'run' is the number
  61. of times further it is run and 'fname' is the name of the file the
  62. reports are written to.  These parameters all have defaults (5, 4 and
  63. "reflog.txt" respectively), so the minimal invocation is '-R ::'.
  64.  
  65. -M runs tests that require an exorbitant amount of memory. These tests
  66. typically try to ascertain containers keep working when containing more than
  67. 2 billion objects, which only works on 64-bit systems. There are also some
  68. tests that try to exhaust the address space of the process, which only makes
  69. sense on 32-bit systems with at least 2Gb of memory. The passed-in memlimit,
  70. which is a string in the form of '2.5Gb', determines howmuch memory the
  71. tests will limit themselves to (but they may go slightly over.) The number
  72. shouldn't be more memory than the machine has (including swap memory). You
  73. should also keep in mind that swap memory is generally much, much slower
  74. than RAM, and setting memlimit to all available RAM or higher will heavily
  75. tax the machine. On the other hand, it is no use running these tests with a
  76. limit of less than 2.5Gb, and many require more than 20Gb. Tests that expect
  77. to use more than memlimit memory will be skipped. The big-memory tests
  78. generally run very, very long.
  79.  
  80. -u is used to specify which special resource intensive tests to run,
  81. such as those requiring large file support or network connectivity.
  82. The argument is a comma-separated list of words indicating the
  83. resources to test.  Currently only the following are defined:
  84.  
  85.     all -       Enable all special resources.
  86.  
  87.     audio -     Tests that use the audio device.  (There are known
  88.                 cases of broken audio drivers that can crash Python or
  89.                 even the Linux kernel.)
  90.  
  91.     curses -    Tests that use curses and will modify the terminal's
  92.                 state and output modes.
  93.  
  94.     lib2to3 -   Run the tests for 2to3 (They take a while.)
  95.  
  96.     largefile - It is okay to run some test that may create huge
  97.                 files.  These tests can take a long time and may
  98.                 consume >2GB of disk space temporarily.
  99.  
  100.     network -   It is okay to run tests that use external network
  101.                 resource, e.g. testing SSL support for sockets.
  102.  
  103.     bsddb -     It is okay to run the bsddb testsuite, which takes
  104.                 a long time to complete.
  105.  
  106.     decimal -   Test the decimal module against a large suite that
  107.                 verifies compliance with standards.
  108.  
  109.     compiler -  Test the compiler package by compiling all the source
  110.                 in the standard library and test suite.  This takes
  111.                 a long time.  Enabling this resource also allows
  112.                 test_tokenize to verify round-trip lexing on every
  113.                 file in the test library.
  114.  
  115.     subprocess  Run all tests for the subprocess module.
  116.  
  117.     urlfetch -  It is okay to download files required on testing.
  118.  
  119. To enable all resources except one, use '-uall,-<resource>'.  For
  120. example, to run all the tests except for the bsddb tests, give the
  121. option '-uall,-bsddb'.
  122. """
  123.  
  124. import cStringIO
  125. import getopt
  126. import os
  127. import random
  128. import re
  129. import sys
  130. import time
  131. import traceback
  132. import warnings
  133. # keep a reference to the ascii module to workaround #7140 bug
  134. # (see issue #7027)
  135. import encodings.ascii
  136. import imp
  137.  
  138. # I see no other way to suppress these warnings;
  139. # putting them in test_grammar.py has no effect:
  140. warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning,
  141.                         ".*test.test_grammar$")
  142. if sys.maxint > 0x7fffffff:
  143.     # Also suppress them in <string>, because for 64-bit platforms,
  144.     # that's where test_grammar.py hides them.
  145.     warnings.filterwarnings("ignore", "hex/oct constants", FutureWarning,
  146.                             "<string>")
  147.  
  148. # Ignore ImportWarnings that only occur in the source tree,
  149. # (because of modules with the same name as source-directories in Modules/)
  150. for mod in ("ctypes", "gzip", "zipfile", "tarfile", "encodings.zlib_codec",
  151.             "test.test_zipimport", "test.test_zlib", "test.test_zipfile",
  152.             "test.test_codecs", "test.string_tests"):
  153.     warnings.filterwarnings(module=".*%s$" % (mod,),
  154.                             action="ignore", category=ImportWarning)
  155.  
  156. # MacOSX (a.k.a. Darwin) has a default stack size that is too small
  157. # for deeply recursive regular expressions.  We see this as crashes in
  158. # the Python test suite when running test_re.py and test_sre.py.  The
  159. # fix is to set the stack limit to 2048.
  160. # This approach may also be useful for other Unixy platforms that
  161. # suffer from small default stack limits.
  162. if sys.platform == 'darwin':
  163.     try:
  164.         import resource
  165.     except ImportError:
  166.         pass
  167.     else:
  168.         soft, hard = resource.getrlimit(resource.RLIMIT_STACK)
  169.         newsoft = min(hard, max(soft, 1024*2048))
  170.         resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
  171.  
  172. from test import test_support
  173.  
  174. RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb',
  175.                   'decimal', 'compiler', 'subprocess', 'urlfetch')
  176.  
  177.  
  178. def usage(code, msg=''):
  179.     print __doc__
  180.     if msg: print msg
  181.     sys.exit(code)
  182.  
  183.  
  184. def main(tests=None, testdir=None, verbose=0, quiet=False,
  185.          exclude=False, single=False, randomize=False, fromfile=None,
  186.          findleaks=False, use_resources=None, trace=False, coverdir='coverage',
  187.          runleaks=False, huntrleaks=False, verbose2=False, print_slow=False):
  188.     """Execute a test suite.
  189.  
  190.     This also parses command-line options and modifies its behavior
  191.     accordingly.
  192.  
  193.     tests -- a list of strings containing test names (optional)
  194.     testdir -- the directory in which to look for tests (optional)
  195.  
  196.     Users other than the Python test suite will certainly want to
  197.     specify testdir; if it's omitted, the directory containing the
  198.     Python test suite is searched for.
  199.  
  200.     If the tests argument is omitted, the tests listed on the
  201.     command-line will be used.  If that's empty, too, then all *.py
  202.     files beginning with test_ will be used.
  203.  
  204.     The other default arguments (verbose, quiet, exclude,
  205.     single, randomize, findleaks, use_resources, trace, coverdir, and
  206.     print_slow) allow programmers calling main() directly to set the
  207.     values that would normally be set by flags on the command line.
  208.     """
  209.  
  210.     test_support.record_original_stdout(sys.stdout)
  211.     try:
  212.         opts, args = getopt.getopt(sys.argv[1:], 'hvqxsSrf:lu:t:TD:NLR:wM:',
  213.                                    ['help', 'verbose', 'quiet', 'exclude',
  214.                                     'single', 'slow', 'random', 'fromfile',
  215.                                     'findleaks', 'use=', 'threshold=', 'trace',
  216.                                     'coverdir=', 'nocoverdir', 'runleaks',
  217.                                     'huntrleaks=', 'verbose2', 'memlimit=',
  218.                                     ])
  219.     except getopt.error, msg:
  220.         usage(2, msg)
  221.  
  222.     # Defaults
  223.     if use_resources is None:
  224.         use_resources = []
  225.     for o, a in opts:
  226.         if o in ('-h', '--help'):
  227.             usage(0)
  228.         elif o in ('-v', '--verbose'):
  229.             verbose += 1
  230.         elif o in ('-w', '--verbose2'):
  231.             verbose2 = True
  232.         elif o in ('-q', '--quiet'):
  233.             quiet = True;
  234.             verbose = 0
  235.         elif o in ('-x', '--exclude'):
  236.             exclude = True
  237.         elif o in ('-s', '--single'):
  238.             single = True
  239.         elif o in ('-S', '--slow'):
  240.             print_slow = True
  241.         elif o in ('-r', '--randomize'):
  242.             randomize = True
  243.         elif o in ('-f', '--fromfile'):
  244.             fromfile = a
  245.         elif o in ('-l', '--findleaks'):
  246.             findleaks = True
  247.         elif o in ('-L', '--runleaks'):
  248.             runleaks = True
  249.         elif o in ('-t', '--threshold'):
  250.             import gc
  251.             gc.set_threshold(int(a))
  252.         elif o in ('-T', '--coverage'):
  253.             trace = True
  254.         elif o in ('-D', '--coverdir'):
  255.             coverdir = os.path.join(os.getcwd(), a)
  256.         elif o in ('-N', '--nocoverdir'):
  257.             coverdir = None
  258.         elif o in ('-R', '--huntrleaks'):
  259.             huntrleaks = a.split(':')
  260.             if len(huntrleaks) != 3:
  261.                 print a, huntrleaks
  262.                 usage(2, '-R takes three colon-separated arguments')
  263.             if len(huntrleaks[0]) == 0:
  264.                 huntrleaks[0] = 5
  265.             else:
  266.                 huntrleaks[0] = int(huntrleaks[0])
  267.             if len(huntrleaks[1]) == 0:
  268.                 huntrleaks[1] = 4
  269.             else:
  270.                 huntrleaks[1] = int(huntrleaks[1])
  271.             if len(huntrleaks[2]) == 0:
  272.                 huntrleaks[2] = "reflog.txt"
  273.         elif o in ('-M', '--memlimit'):
  274.             test_support.set_memlimit(a)
  275.         elif o in ('-u', '--use'):
  276.             u = [x.lower() for x in a.split(',')]
  277.             for r in u:
  278.                 if r == 'all':
  279.                     use_resources[:] = RESOURCE_NAMES
  280.                     continue
  281.                 remove = False
  282.                 if r[0] == '-':
  283.                     remove = True
  284.                     r = r[1:]
  285.                 if r not in RESOURCE_NAMES:
  286.                     usage(1, 'Invalid -u/--use option: ' + a)
  287.                 if remove:
  288.                     if r in use_resources:
  289.                         use_resources.remove(r)
  290.                 elif r not in use_resources:
  291.                     use_resources.append(r)
  292.         else:
  293.             print >>sys.stderr, ("No handler for option {0}.  Please "
  294.                 "report this as a bug at http://bugs.python.org.").format(o)
  295.             sys.exit(1)
  296.     if single and fromfile:
  297.         usage(2, "-s and -f don't go together!")
  298.  
  299.     good = []
  300.     bad = []
  301.     skipped = []
  302.     resource_denieds = []
  303.  
  304.     if findleaks:
  305.         try:
  306.             import gc
  307.         except ImportError:
  308.             print 'No GC available, disabling findleaks.'
  309.             findleaks = False
  310.         else:
  311.             # Uncomment the line below to report garbage that is not
  312.             # freeable by reference counting alone.  By default only
  313.             # garbage that is not collectable by the GC is reported.
  314.             #gc.set_debug(gc.DEBUG_SAVEALL)
  315.             found_garbage = []
  316.  
  317.     if single:
  318.         from tempfile import gettempdir
  319.         filename = os.path.join(gettempdir(), 'pynexttest')
  320.         try:
  321.             fp = open(filename, 'r')
  322.             next = fp.read().strip()
  323.             tests = [next]
  324.             fp.close()
  325.         except IOError:
  326.             pass
  327.  
  328.     if fromfile:
  329.         tests = []
  330.         fp = open(fromfile)
  331.         for line in fp:
  332.             guts = line.split() # assuming no test has whitespace in its name
  333.             if guts and not guts[0].startswith('#'):
  334.                 tests.extend(guts)
  335.         fp.close()
  336.  
  337.     # Strip .py extensions.
  338.     if args:
  339.         args = map(removepy, args)
  340.     if tests:
  341.         tests = map(removepy, tests)
  342.  
  343.     stdtests = STDTESTS[:]
  344.     nottests = NOTTESTS[:]
  345.     if exclude:
  346.         for arg in args:
  347.             if arg in stdtests:
  348.                 stdtests.remove(arg)
  349.         nottests[:0] = args
  350.         args = []
  351.     tests = tests or args or findtests(testdir, stdtests, nottests)
  352.     if single:
  353.         tests = tests[:1]
  354.     if randomize:
  355.         random.shuffle(tests)
  356.     if trace:
  357.         import trace
  358.         tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix],
  359.                              trace=False, count=True)
  360.     test_times = []
  361.     test_support.verbose = verbose      # Tell tests to be moderately quiet
  362.     test_support.use_resources = use_resources
  363.     save_modules = sys.modules.keys()
  364.     for test in tests:
  365.         if not quiet:
  366.             print test
  367.             sys.stdout.flush()
  368.         if trace:
  369.             # If we're tracing code coverage, then we don't exit with status
  370.             # if on a false return value from main.
  371.             tracer.runctx('runtest(test, verbose, quiet,'
  372.                           '        test_times, testdir)',
  373.                           globals=globals(), locals=vars())
  374.         else:
  375.             try:
  376.                 ok = runtest(test, verbose, quiet, test_times,
  377.                              testdir, huntrleaks)
  378.             except KeyboardInterrupt:
  379.                 # print a newline separate from the ^C
  380.                 print
  381.                 break
  382.             except:
  383.                 raise
  384.             if ok > 0:
  385.                 good.append(test)
  386.             elif ok == 0:
  387.                 bad.append(test)
  388.             else:
  389.                 skipped.append(test)
  390.                 if ok == -2:
  391.                     resource_denieds.append(test)
  392.         if findleaks:
  393.             gc.collect()
  394.             if gc.garbage:
  395.                 print "Warning: test created", len(gc.garbage),
  396.                 print "uncollectable object(s)."
  397.                 # move the uncollectable objects somewhere so we don't see
  398.                 # them again
  399.                 found_garbage.extend(gc.garbage)
  400.                 del gc.garbage[:]
  401.         # Unload the newly imported modules (best effort finalization)
  402.         for module in sys.modules.keys():
  403.             if module not in save_modules and module.startswith("test."):
  404.                 test_support.unload(module)
  405.  
  406.     if good and not quiet:
  407.         if not bad and not skipped and len(good) > 1:
  408.             print "All",
  409.         print count(len(good), "test"), "OK."
  410.     if print_slow:
  411.         test_times.sort(reverse=True)
  412.         print "10 slowest tests:"
  413.         for time, test in test_times[:10]:
  414.             print "%s: %.1fs" % (test, time)
  415.     if bad:
  416.         print count(len(bad), "test"), "failed:"
  417.         printlist(bad)
  418.     if skipped and not quiet:
  419.         print count(len(skipped), "test"), "skipped:"
  420.         printlist(skipped)
  421.  
  422.         e = _ExpectedSkips()
  423.         plat = sys.platform
  424.         if e.isvalid():
  425.             surprise = set(skipped) - e.getexpected() - set(resource_denieds)
  426.             if surprise:
  427.                 print count(len(surprise), "skip"), \
  428.                       "unexpected on", plat + ":"
  429.                 printlist(surprise)
  430.             else:
  431.                 print "Those skips are all expected on", plat + "."
  432.         else:
  433.             print "Ask someone to teach regrtest.py about which tests are"
  434.             print "expected to get skipped on", plat + "."
  435.  
  436.     if verbose2 and bad:
  437.         print "Re-running failed tests in verbose mode"
  438.         for test in bad:
  439.             print "Re-running test %r in verbose mode" % test
  440.             sys.stdout.flush()
  441.             try:
  442.                 test_support.verbose = True
  443.                 ok = runtest(test, True, quiet, test_times, testdir,
  444.                              huntrleaks)
  445.             except KeyboardInterrupt:
  446.                 # print a newline separate from the ^C
  447.                 print
  448.                 break
  449.             except:
  450.                 raise
  451.  
  452.     if single:
  453.         alltests = findtests(testdir, stdtests, nottests)
  454.         for i in range(len(alltests)):
  455.             if tests[0] == alltests[i]:
  456.                 if i == len(alltests) - 1:
  457.                     os.unlink(filename)
  458.                 else:
  459.                     fp = open(filename, 'w')
  460.                     fp.write(alltests[i+1] + '\n')
  461.                     fp.close()
  462.                 break
  463.         else:
  464.             os.unlink(filename)
  465.  
  466.     if trace:
  467.         r = tracer.results()
  468.         r.write_results(show_missing=True, summary=True, coverdir=coverdir)
  469.  
  470.     if runleaks:
  471.         os.system("leaks %d" % os.getpid())
  472.  
  473.     sys.exit(len(bad) > 0)
  474.  
  475.  
  476. STDTESTS = [
  477.     'test_grammar',
  478.     'test_opcodes',
  479.     'test_dict',
  480.     'test_builtin',
  481.     'test_exceptions',
  482.     'test_types',
  483.     'test_unittest',
  484.     'test_doctest',
  485.     'test_doctest2',
  486.     # On 2.6, when a C module like dl or linuxaudiodev is imported by some
  487.     # test, a DeprecationWarning is raised, but test_py3kwarn can not find
  488.     # it in the __warningregistry__ of the modules in sys.modules.
  489.     # C modules raise the warning only once, and since there's no way to
  490.     # find these warnings, test_py3kwarn is executed first to catch them
  491.     # before the other modules.  This shouldn't affect 2.7+
  492.     'test_py3kwarn',
  493.    ]
  494.  
  495. NOTTESTS = [
  496.     'test_support',
  497.     'test_future1',
  498.     'test_future2',
  499.     ]
  500.  
  501. def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
  502.     """Return a list of all applicable test modules."""
  503.     if not testdir: testdir = findtestdir()
  504.     names = os.listdir(testdir)
  505.     tests = []
  506.     for name in names:
  507.         if name[:5] == "test_" and name[-3:] == os.extsep+"py":
  508.             modname = name[:-3]
  509.             if modname not in stdtests and modname not in nottests:
  510.                 tests.append(modname)
  511.     tests.sort()
  512.     return stdtests + tests
  513.  
  514. def runtest(test, verbose, quiet, test_times,
  515.             testdir=None, huntrleaks=False):
  516.     """Run a single test.
  517.  
  518.     test -- the name of the test
  519.     verbose -- if true, print more messages
  520.     quiet -- if true, don't print 'skipped' messages (probably redundant)
  521.     test_times -- a list of (time, test_name) pairs
  522.     testdir -- test directory
  523.     huntrleaks -- run multiple times to test for leaks; requires a debug
  524.                   build; a triple corresponding to -R's three arguments
  525.     Return:
  526.         -2  test skipped because resource denied
  527.         -1  test skipped for some other reason
  528.          0  test failed
  529.          1  test passed
  530.     """
  531.  
  532.     try:
  533.         return runtest_inner(test, verbose, quiet, test_times,
  534.                              testdir, huntrleaks)
  535.     finally:
  536.         cleanup_test_droppings(test, verbose)
  537.  
  538. def runtest_inner(test, verbose, quiet, test_times,
  539.                   testdir=None, huntrleaks=False):
  540.     test_support.unload(test)
  541.     if not testdir:
  542.         testdir = findtestdir()
  543.     if verbose:
  544.         capture_stdout = None
  545.     else:
  546.         capture_stdout = cStringIO.StringIO()
  547.  
  548.     try:
  549.         save_stdout = sys.stdout
  550.         try:
  551.             if capture_stdout:
  552.                 sys.stdout = capture_stdout
  553.             if test.startswith('test.'):
  554.                 abstest = test
  555.             else:
  556.                 # Always import it from the test package
  557.                 abstest = 'test.' + test
  558.             start_time = time.time()
  559.             the_package = __import__(abstest, globals(), locals(), [])
  560.             the_module = getattr(the_package, test)
  561.             # Old tests run to completion simply as a side-effect of
  562.             # being imported.  For tests based on unittest or doctest,
  563.             # explicitly invoke their test_main() function (if it exists).
  564.             indirect_test = getattr(the_module, "test_main", None)
  565.             if indirect_test is not None:
  566.                 indirect_test()
  567.             if huntrleaks:
  568.                 dash_R(the_module, test, indirect_test, huntrleaks)
  569.             test_time = time.time() - start_time
  570.             test_times.append((test_time, test))
  571.         finally:
  572.             sys.stdout = save_stdout
  573.     except test_support.ResourceDenied, msg:
  574.         if not quiet:
  575.             print test, "skipped --", msg
  576.             sys.stdout.flush()
  577.         return -2
  578.     except (ImportError, test_support.TestSkipped), msg:
  579.         if not quiet:
  580.             print test, "skipped --", msg
  581.             sys.stdout.flush()
  582.         return -1
  583.     except KeyboardInterrupt:
  584.         raise
  585.     except test_support.TestFailed, msg:
  586.         print "test", test, "failed --", msg
  587.         sys.stdout.flush()
  588.         return 0
  589.     except:
  590.         type, value = sys.exc_info()[:2]
  591.         print "test", test, "crashed --", str(type) + ":", value
  592.         sys.stdout.flush()
  593.         if verbose:
  594.             traceback.print_exc(file=sys.stdout)
  595.             sys.stdout.flush()
  596.         return 0
  597.     else:
  598.         # Except in verbose mode, tests should not print anything
  599.         if verbose or huntrleaks:
  600.             return 1
  601.         output = capture_stdout.getvalue()
  602.         if not output:
  603.             return 1
  604.         print "test", test, "produced unexpected output:"
  605.         print "*" * 70
  606.         print output
  607.         print "*" * 70
  608.         sys.stdout.flush()
  609.         return 0
  610.  
  611. def cleanup_test_droppings(testname, verbose):
  612.     import shutil
  613.  
  614.     # Try to clean up junk commonly left behind.  While tests shouldn't leave
  615.     # any files or directories behind, when a test fails that can be tedious
  616.     # for it to arrange.  The consequences can be especially nasty on Windows,
  617.     # since if a test leaves a file open, it cannot be deleted by name (while
  618.     # there's nothing we can do about that here either, we can display the
  619.     # name of the offending test, which is a real help).
  620.     for name in (test_support.TESTFN,
  621.                  "db_home",
  622.                 ):
  623.         if not os.path.exists(name):
  624.             continue
  625.  
  626.         if os.path.isdir(name):
  627.             kind, nuker = "directory", shutil.rmtree
  628.         elif os.path.isfile(name):
  629.             kind, nuker = "file", os.unlink
  630.         else:
  631.             raise SystemError("os.path says %r exists but is neither "
  632.                               "directory nor file" % name)
  633.  
  634.         if verbose:
  635.             print "%r left behind %s %r" % (testname, kind, name)
  636.         try:
  637.             nuker(name)
  638.         except Exception, msg:
  639.             print >> sys.stderr, ("%r left behind %s %r and it couldn't be "
  640.                 "removed: %s" % (testname, kind, name, msg))
  641.  
  642. def dash_R(the_module, test, indirect_test, huntrleaks):
  643.     # This code is hackish and inelegant, but it seems to do the job.
  644.     import copy_reg, _abcoll, io
  645.  
  646.     if not hasattr(sys, 'gettotalrefcount'):
  647.         raise Exception("Tracking reference leaks requires a debug build "
  648.                         "of Python")
  649.  
  650.     # Save current values for dash_R_cleanup() to restore.
  651.     fs = warnings.filters[:]
  652.     ps = copy_reg.dispatch_table.copy()
  653.     pic = sys.path_importer_cache.copy()
  654.     abcs = {}
  655.     modules = _abcoll, io
  656.     for abc in [getattr(mod, a) for mod in modules for a in mod.__all__]:
  657.         # XXX isinstance(abc, ABCMeta) leads to infinite recursion
  658.         if not hasattr(abc, '_abc_registry'):
  659.             continue
  660.         for obj in abc.__subclasses__() + [abc]:
  661.             abcs[obj] = obj._abc_registry.copy()
  662.  
  663.     if indirect_test:
  664.         def run_the_test():
  665.             indirect_test()
  666.     else:
  667.         def run_the_test():
  668.             imp.reload(the_module)
  669.  
  670.     deltas = []
  671.     nwarmup, ntracked, fname = huntrleaks
  672.     repcount = nwarmup + ntracked
  673.     print >> sys.stderr, "beginning", repcount, "repetitions"
  674.     print >> sys.stderr, ("1234567890"*(repcount//10 + 1))[:repcount]
  675.     dash_R_cleanup(fs, ps, pic, abcs)
  676.     for i in range(repcount):
  677.         rc = sys.gettotalrefcount()
  678.         run_the_test()
  679.         sys.stderr.write('.')
  680.         dash_R_cleanup(fs, ps, pic, abcs)
  681.         if i >= nwarmup:
  682.             deltas.append(sys.gettotalrefcount() - rc - 2)
  683.     print >> sys.stderr
  684.     if any(deltas):
  685.         msg = '%s leaked %s references, sum=%s' % (test, deltas, sum(deltas))
  686.         print >> sys.stderr, msg
  687.         refrep = open(fname, "a")
  688.         print >> refrep, msg
  689.         refrep.close()
  690.  
  691. def dash_R_cleanup(fs, ps, pic, abcs):
  692.     import gc, copy_reg
  693.     import _strptime, linecache
  694.     dircache = test_support.import_module('dircache', deprecated=True)
  695.     import urlparse, urllib, urllib2, mimetypes, doctest
  696.     import struct, filecmp
  697.     from distutils.dir_util import _path_created
  698.  
  699.     # Clear the warnings registry, so they can be displayed again
  700.     for mod in sys.modules.values():
  701.         if hasattr(mod, '__warningregistry__'):
  702.             del mod.__warningregistry__
  703.  
  704.     # Restore some original values.
  705.     warnings.filters[:] = fs
  706.     copy_reg.dispatch_table.clear()
  707.     copy_reg.dispatch_table.update(ps)
  708.     sys.path_importer_cache.clear()
  709.     sys.path_importer_cache.update(pic)
  710.  
  711.     # clear type cache
  712.     sys._clear_type_cache()
  713.  
  714.     # Clear ABC registries, restoring previously saved ABC registries.
  715.     for abc, registry in abcs.items():
  716.         abc._abc_registry = registry.copy()
  717.         abc._abc_cache.clear()
  718.         abc._abc_negative_cache.clear()
  719.  
  720.     # Clear assorted module caches.
  721.     _path_created.clear()
  722.     re.purge()
  723.     _strptime._regex_cache.clear()
  724.     urlparse.clear_cache()
  725.     urllib.urlcleanup()
  726.     urllib2.install_opener(None)
  727.     dircache.reset()
  728.     linecache.clearcache()
  729.     mimetypes._default_mime_types()
  730.     filecmp._cache.clear()
  731.     struct._clearcache()
  732.     doctest.master = None
  733.  
  734.     # Collect cyclic trash.
  735.     gc.collect()
  736.  
  737. def findtestdir():
  738.     if __name__ == '__main__':
  739.         file = sys.argv[0]
  740.     else:
  741.         file = __file__
  742.     testdir = os.path.dirname(file) or os.curdir
  743.     return testdir
  744.  
  745. def removepy(name):
  746.     if name.endswith(os.extsep + "py"):
  747.         name = name[:-3]
  748.     return name
  749.  
  750. def count(n, word):
  751.     if n == 1:
  752.         return "%d %s" % (n, word)
  753.     else:
  754.         return "%d %ss" % (n, word)
  755.  
  756. def printlist(x, width=70, indent=4):
  757.     """Print the elements of iterable x to stdout.
  758.  
  759.     Optional arg width (default 70) is the maximum line length.
  760.     Optional arg indent (default 4) is the number of blanks with which to
  761.     begin each line.
  762.     """
  763.  
  764.     from textwrap import fill
  765.     blanks = ' ' * indent
  766.     # Print the sorted list: 'x' may be a '--random' list or a set()
  767.     print fill(' '.join(str(elt) for elt in sorted(x)), width,
  768.                initial_indent=blanks, subsequent_indent=blanks)
  769.  
  770. # Map sys.platform to a string containing the basenames of tests
  771. # expected to be skipped on that platform.
  772. #
  773. # Special cases:
  774. #     test_pep277
  775. #         The _ExpectedSkips constructor adds this to the set of expected
  776. #         skips if not os.path.supports_unicode_filenames.
  777. #     test_socket_ssl
  778. #         Controlled by test_socket_ssl.skip_expected.  Requires the network
  779. #         resource, and a socket module with ssl support.
  780. #     test_timeout
  781. #         Controlled by test_timeout.skip_expected.  Requires the network
  782. #         resource and a socket module.
  783. #
  784. # Tests that are expected to be skipped everywhere except on one platform
  785. # are also handled separately.
  786.  
  787. _expectations = {
  788.     'win32':
  789.         """
  790.         test__locale
  791.         test_bsddb185
  792.         test_bsddb3
  793.         test_commands
  794.         test_crypt
  795.         test_curses
  796.         test_dbm
  797.         test_dl
  798.         test_fcntl
  799.         test_fork1
  800.         test_epoll
  801.         test_gdbm
  802.         test_grp
  803.         test_ioctl
  804.         test_largefile
  805.         test_kqueue
  806.         test_mhlib
  807.         test_openpty
  808.         test_ossaudiodev
  809.         test_pipes
  810.         test_poll
  811.         test_posix
  812.         test_pty
  813.         test_pwd
  814.         test_resource
  815.         test_signal
  816.         test_threadsignals
  817.         test_timing
  818.         test_wait3
  819.         test_wait4
  820.         """,
  821.     'linux2':
  822.         """
  823.         test_bsddb185
  824.         test_curses
  825.         test_dl
  826.         test_largefile
  827.         test_kqueue
  828.         test_ossaudiodev
  829.         """,
  830.    'mac':
  831.         """
  832.         test_atexit
  833.         test_bsddb
  834.         test_bsddb185
  835.         test_bsddb3
  836.         test_bz2
  837.         test_commands
  838.         test_crypt
  839.         test_curses
  840.         test_dbm
  841.         test_dl
  842.         test_fcntl
  843.         test_fork1
  844.         test_epoll
  845.         test_grp
  846.         test_ioctl
  847.         test_largefile
  848.         test_locale
  849.         test_kqueue
  850.         test_mmap
  851.         test_openpty
  852.         test_ossaudiodev
  853.         test_poll
  854.         test_popen
  855.         test_popen2
  856.         test_posix
  857.         test_pty
  858.         test_pwd
  859.         test_resource
  860.         test_signal
  861.         test_sundry
  862.         test_tarfile
  863.         test_timing
  864.         """,
  865.     'unixware7':
  866.         """
  867.         test_bsddb
  868.         test_bsddb185
  869.         test_dl
  870.         test_epoll
  871.         test_largefile
  872.         test_kqueue
  873.         test_minidom
  874.         test_openpty
  875.         test_pyexpat
  876.         test_sax
  877.         test_sundry
  878.         """,
  879.     'openunix8':
  880.         """
  881.         test_bsddb
  882.         test_bsddb185
  883.         test_dl
  884.         test_epoll
  885.         test_largefile
  886.         test_kqueue
  887.         test_minidom
  888.         test_openpty
  889.         test_pyexpat
  890.         test_sax
  891.         test_sundry
  892.         """,
  893.     'sco_sv3':
  894.         """
  895.         test_asynchat
  896.         test_bsddb
  897.         test_bsddb185
  898.         test_dl
  899.         test_fork1
  900.         test_epoll
  901.         test_gettext
  902.         test_largefile
  903.         test_locale
  904.         test_kqueue
  905.         test_minidom
  906.         test_openpty
  907.         test_pyexpat
  908.         test_queue
  909.         test_sax
  910.         test_sundry
  911.         test_thread
  912.         test_threaded_import
  913.         test_threadedtempfile
  914.         test_threading
  915.         """,
  916.     'riscos':
  917.         """
  918.         test_asynchat
  919.         test_atexit
  920.         test_bsddb
  921.         test_bsddb185
  922.         test_bsddb3
  923.         test_commands
  924.         test_crypt
  925.         test_dbm
  926.         test_dl
  927.         test_fcntl
  928.         test_fork1
  929.         test_epoll
  930.         test_gdbm
  931.         test_grp
  932.         test_largefile
  933.         test_locale
  934.         test_kqueue
  935.         test_mmap
  936.         test_openpty
  937.         test_poll
  938.         test_popen2
  939.         test_pty
  940.         test_pwd
  941.         test_strop
  942.         test_sundry
  943.         test_thread
  944.         test_threaded_import
  945.         test_threadedtempfile
  946.         test_threading
  947.         test_timing
  948.         """,
  949.     'darwin':
  950.         """
  951.         test__locale
  952.         test_bsddb
  953.         test_bsddb3
  954.         test_curses
  955.         test_epoll
  956.         test_gdbm
  957.         test_largefile
  958.         test_locale
  959.         test_kqueue
  960.         test_minidom
  961.         test_ossaudiodev
  962.         test_poll
  963.         """,
  964.     'sunos5':
  965.         """
  966.         test_bsddb
  967.         test_bsddb185
  968.         test_curses
  969.         test_dbm
  970.         test_epoll
  971.         test_kqueue
  972.         test_gdbm
  973.         test_gzip
  974.         test_openpty
  975.         test_zipfile
  976.         test_zlib
  977.         """,
  978.     'hp-ux11':
  979.         """
  980.         test_bsddb
  981.         test_bsddb185
  982.         test_curses
  983.         test_dl
  984.         test_epoll
  985.         test_gdbm
  986.         test_gzip
  987.         test_largefile
  988.         test_locale
  989.         test_kqueue
  990.         test_minidom
  991.         test_openpty
  992.         test_pyexpat
  993.         test_sax
  994.         test_zipfile
  995.         test_zlib
  996.         """,
  997.     'atheos':
  998.         """
  999.         test_bsddb185
  1000.         test_curses
  1001.         test_dl
  1002.         test_gdbm
  1003.         test_epoll
  1004.         test_largefile
  1005.         test_locale
  1006.         test_kqueue
  1007.         test_mhlib
  1008.         test_mmap
  1009.         test_poll
  1010.         test_popen2
  1011.         test_resource
  1012.         """,
  1013.     'cygwin':
  1014.         """
  1015.         test_bsddb185
  1016.         test_bsddb3
  1017.         test_curses
  1018.         test_dbm
  1019.         test_epoll
  1020.         test_ioctl
  1021.         test_kqueue
  1022.         test_largefile
  1023.         test_locale
  1024.         test_ossaudiodev
  1025.         test_socketserver
  1026.         """,
  1027.     'os2emx':
  1028.         """
  1029.         test_audioop
  1030.         test_bsddb185
  1031.         test_bsddb3
  1032.         test_commands
  1033.         test_curses
  1034.         test_dl
  1035.         test_epoll
  1036.         test_kqueue
  1037.         test_largefile
  1038.         test_mhlib
  1039.         test_mmap
  1040.         test_openpty
  1041.         test_ossaudiodev
  1042.         test_pty
  1043.         test_resource
  1044.         test_signal
  1045.         """,
  1046.     'freebsd4':
  1047.         """
  1048.         test_bsddb
  1049.         test_bsddb3
  1050.         test_epoll
  1051.         test_gdbm
  1052.         test_locale
  1053.         test_ossaudiodev
  1054.         test_pep277
  1055.         test_pty
  1056.         test_socket_ssl
  1057.         test_socketserver
  1058.         test_tcl
  1059.         test_timeout
  1060.         test_urllibnet
  1061.         test_multiprocessing
  1062.         """,
  1063.     'aix5':
  1064.         """
  1065.         test_bsddb
  1066.         test_bsddb185
  1067.         test_bsddb3
  1068.         test_bz2
  1069.         test_dl
  1070.         test_epoll
  1071.         test_gdbm
  1072.         test_gzip
  1073.         test_kqueue
  1074.         test_ossaudiodev
  1075.         test_tcl
  1076.         test_zipimport
  1077.         test_zlib
  1078.         """,
  1079.     'openbsd3':
  1080.         """
  1081.         test_bsddb
  1082.         test_bsddb3
  1083.         test_ctypes
  1084.         test_dl
  1085.         test_epoll
  1086.         test_gdbm
  1087.         test_locale
  1088.         test_normalization
  1089.         test_ossaudiodev
  1090.         test_pep277
  1091.         test_tcl
  1092.         test_multiprocessing
  1093.         """,
  1094.     'netbsd3':
  1095.         """
  1096.         test_bsddb
  1097.         test_bsddb185
  1098.         test_bsddb3
  1099.         test_ctypes
  1100.         test_curses
  1101.         test_dl
  1102.         test_epoll
  1103.         test_gdbm
  1104.         test_locale
  1105.         test_ossaudiodev
  1106.         test_pep277
  1107.         test_tcl
  1108.         test_multiprocessing
  1109.         """,
  1110. }
  1111. _expectations['freebsd5'] = _expectations['freebsd4']
  1112. _expectations['freebsd6'] = _expectations['freebsd4']
  1113. _expectations['freebsd7'] = _expectations['freebsd4']
  1114. _expectations['freebsd8'] = _expectations['freebsd4']
  1115.  
  1116. class _ExpectedSkips:
  1117.     def __init__(self):
  1118.         import os.path
  1119.         from test import test_timeout
  1120.  
  1121.         self.valid = False
  1122.         if sys.platform in _expectations:
  1123.             s = _expectations[sys.platform]
  1124.             self.expected = set(s.split())
  1125.  
  1126.             # expected to be skipped on every platform, even Linux
  1127.             self.expected.add('test_linuxaudiodev')
  1128.  
  1129.             if not os.path.supports_unicode_filenames:
  1130.                 self.expected.add('test_pep277')
  1131.  
  1132.             try:
  1133.                 from test import test_socket_ssl
  1134.             except ImportError:
  1135.                 pass
  1136.             else:
  1137.                 if test_socket_ssl.skip_expected:
  1138.                     self.expected.add('test_socket_ssl')
  1139.  
  1140.             if test_timeout.skip_expected:
  1141.                 self.expected.add('test_timeout')
  1142.  
  1143.             if sys.maxint == 9223372036854775807L:
  1144.                 self.expected.add('test_imageop')
  1145.  
  1146.             if not sys.platform in ("mac", "darwin"):
  1147.                 MAC_ONLY = ["test_macos", "test_macostools", "test_aepack",
  1148.                             "test_plistlib", "test_scriptpackages",
  1149.                             "test_applesingle"]
  1150.                 for skip in MAC_ONLY:
  1151.                     self.expected.add(skip)
  1152.             elif len(u'\0'.encode('unicode-internal')) == 4:
  1153.                 self.expected.add("test_macostools")
  1154.  
  1155.  
  1156.             if sys.platform != "win32":
  1157.                 # test_sqlite is only reliable on Windows where the library
  1158.                 # is distributed with Python
  1159.                 WIN_ONLY = ["test_unicode_file", "test_winreg",
  1160.                             "test_winsound", "test_startfile",
  1161.                             "test_sqlite"]
  1162.                 for skip in WIN_ONLY:
  1163.                     self.expected.add(skip)
  1164.  
  1165.             if sys.platform != 'irix':
  1166.                 IRIX_ONLY = ["test_imageop", "test_al", "test_cd", "test_cl",
  1167.                              "test_gl", "test_imgfile"]
  1168.                 for skip in IRIX_ONLY:
  1169.                     self.expected.add(skip)
  1170.  
  1171.             if sys.platform != 'sunos5':
  1172.                 self.expected.add('test_sunaudiodev')
  1173.                 self.expected.add('test_nis')
  1174.  
  1175.             if not sys.py3kwarning:
  1176.                 self.expected.add('test_py3kwarn')
  1177.  
  1178.             self.valid = True
  1179.  
  1180.     def isvalid(self):
  1181.         "Return true iff _ExpectedSkips knows about the current platform."
  1182.         return self.valid
  1183.  
  1184.     def getexpected(self):
  1185.         """Return set of test names we expect to skip on current platform.
  1186.  
  1187.         self.isvalid() must be true.
  1188.         """
  1189.  
  1190.         assert self.isvalid()
  1191.         return self.expected
  1192.  
  1193. if __name__ == '__main__':
  1194.     # Remove regrtest.py's own directory from the module search path.  This
  1195.     # prevents relative imports from working, and relative imports will screw
  1196.     # up the testing framework.  E.g. if both test.test_support and
  1197.     # test_support are imported, they will not contain the same globals, and
  1198.     # much of the testing framework relies on the globals in the
  1199.     # test.test_support module.
  1200.     mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
  1201.     i = len(sys.path)
  1202.     while i >= 0:
  1203.         i -= 1
  1204.         if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
  1205.             del sys.path[i]
  1206.     main()
  1207.