home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / test / regrtest.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2008-10-29  |  35.9 KB  |  935 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''Regression test.
  5.  
  6. This will find all modules whose name is "test_*" in the test
  7. directory, and run them.  Various command line options provide
  8. additional facilities.
  9.  
  10. Command line options:
  11.  
  12. -v: verbose    -- run tests in verbose mode with output to stdout
  13. -w: verbose2   -- re-run failed tests in verbose mode
  14. -q: quiet      -- don\'t print anything except if a test fails
  15. -g: generate   -- write the output file for a test instead of comparing it
  16. -x: exclude    -- arguments are tests to *exclude*
  17. -s: single     -- run only a single test (see below)
  18. -r: random     -- randomize test execution order
  19. -f: fromfile   -- read names of tests to run from a file (see below)
  20. -l: findleaks  -- if GC is available detect tests that leak memory
  21. -u: use        -- specify which special resource intensive tests to run
  22. -h: help       -- print this text and exit
  23. -t: threshold  -- call gc.set_threshold(N)
  24. -T: coverage   -- turn on code coverage using the trace module
  25. -D: coverdir   -- Directory where coverage files are put
  26. -N: nocoverdir -- Put coverage files alongside modules
  27. -L: runleaks   -- run the leaks(1) command just before exit
  28. -R: huntrleaks -- search for reference leaks (needs debug build, v. slow)
  29. -M: memlimit   -- run very large memory-consuming tests
  30.  
  31. If non-option arguments are present, they are names for tests to run,
  32. unless -x is given, in which case they are names for tests not to run.
  33. If no test names are given, all tests are run.
  34.  
  35. -v is incompatible with -g and does not compare test output files.
  36.  
  37. -T turns on code coverage tracing with the trace module.
  38.  
  39. -D specifies the directory where coverage files are put.
  40.  
  41. -N Put coverage files alongside modules.
  42.  
  43. -s means to run only a single test and exit.  This is useful when
  44. doing memory analysis on the Python interpreter (which tend to consume
  45. too many resources to run the full regression test non-stop).  The
  46. file /tmp/pynexttest is read to find the next test to run.  If this
  47. file is missing, the first test_*.py file in testdir or on the command
  48. line is used.  (actually tempfile.gettempdir() is used instead of
  49. /tmp).
  50.  
  51. -f reads the names of tests from the file given as f\'s argument, one
  52. or more test names per line.  Whitespace is ignored.  Blank lines and
  53. lines beginning with \'#\' are ignored.  This is especially useful for
  54. whittling down failures involving interactions among tests.
  55.  
  56. -L causes the leaks(1) command to be run just before exit if it exists.
  57. leaks(1) is available on Mac OS X and presumably on some other
  58. FreeBSD-derived systems.
  59.  
  60. -R runs each test several times and examines sys.gettotalrefcount() to
  61. see if the test appears to be leaking references.  The argument should
  62. be of the form stab:run:fname where \'stab\' is the number of times the
  63. test is run to let gettotalrefcount settle down, \'run\' is the number
  64. of times further it is run and \'fname\' is the name of the file the
  65. reports are written to.  These parameters all have defaults (5, 4 and
  66. "reflog.txt" respectively), so the minimal invocation is \'-R ::\'.
  67.  
  68. -M runs tests that require an exorbitant amount of memory. These tests
  69. typically try to ascertain containers keep working when containing more than
  70. 2 billion objects, which only works on 64-bit systems. There are also some
  71. tests that try to exhaust the address space of the process, which only makes
  72. sense on 32-bit systems with at least 2Gb of memory. The passed-in memlimit,
  73. which is a string in the form of \'2.5Gb\', determines howmuch memory the
  74. tests will limit themselves to (but they may go slightly over.) The number
  75. shouldn\'t be more memory than the machine has (including swap memory). You
  76. should also keep in mind that swap memory is generally much, much slower
  77. than RAM, and setting memlimit to all available RAM or higher will heavily
  78. tax the machine. On the other hand, it is no use running these tests with a
  79. limit of less than 2.5Gb, and many require more than 20Gb. Tests that expect
  80. to use more than memlimit memory will be skipped. The big-memory tests
  81. generally run very, very long.
  82.  
  83. -u is used to specify which special resource intensive tests to run,
  84. such as those requiring large file support or network connectivity.
  85. The argument is a comma-separated list of words indicating the
  86. resources to test.  Currently only the following are defined:
  87.  
  88.     all -       Enable all special resources.
  89.  
  90.     audio -     Tests that use the audio device.  (There are known
  91.                 cases of broken audio drivers that can crash Python or
  92.                 even the Linux kernel.)
  93.  
  94.     curses -    Tests that use curses and will modify the terminal\'s
  95.                 state and output modes.
  96.  
  97.     largefile - It is okay to run some test that may create huge
  98.                 files.  These tests can take a long time and may
  99.                 consume >2GB of disk space temporarily.
  100.  
  101.     network -   It is okay to run tests that use external network
  102.                 resource, e.g. testing SSL support for sockets.
  103.  
  104.     bsddb -     It is okay to run the bsddb testsuite, which takes
  105.                 a long time to complete.
  106.  
  107.     decimal -   Test the decimal module against a large suite that
  108.                 verifies compliance with standards.
  109.  
  110.     compiler -  Test the compiler package by compiling all the source
  111.                 in the standard library and test suite.  This takes
  112.                 a long time.  Enabling this resource also allows
  113.                 test_tokenize to verify round-trip lexing on every
  114.                 file in the test library.
  115.  
  116.     subprocess  Run all tests for the subprocess module.
  117.  
  118.     urlfetch -  It is okay to download files required on testing.
  119.  
  120. To enable all resources except one, use \'-uall,-<resource>\'.  For
  121. example, to run all the tests except for the bsddb tests, give the
  122. option \'-uall,-bsddb\'.
  123. '''
  124. import os
  125. import sys
  126. import getopt
  127. import random
  128. import warnings
  129. import re
  130. import cStringIO
  131. import traceback
  132. warnings.filterwarnings('ignore', 'hex/oct constants', FutureWarning, '.*test.test_grammar$')
  133. if sys.maxint > 2147483647:
  134.     warnings.filterwarnings('ignore', 'hex/oct constants', FutureWarning, '<string>')
  135.  
  136. for mod in ('ctypes', 'gzip', 'zipfile', 'tarfile', 'encodings.zlib_codec', 'test.test_zipimport', 'test.test_zlib', 'test.test_zipfile', 'test.test_codecs', 'test.string_tests'):
  137.     warnings.filterwarnings(module = '.*%s$' % (mod,), action = 'ignore', category = ImportWarning)
  138.  
  139. if sys.platform == 'darwin':
  140.     
  141.     try:
  142.         import resource
  143.     except ImportError:
  144.         pass
  145.  
  146.     (soft, hard) = resource.getrlimit(resource.RLIMIT_STACK)
  147.     newsoft = min(hard, max(soft, 1024 * 2048))
  148.     resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
  149.  
  150. from test import test_support
  151. RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb', 'decimal', 'compiler', 'subprocess', 'urlfetch')
  152.  
  153. def usage(code, msg = ''):
  154.     print __doc__
  155.     if msg:
  156.         print msg
  157.     
  158.     sys.exit(code)
  159.  
  160.  
  161. def main(tests = None, testdir = None, verbose = 0, quiet = False, generate = False, exclude = False, single = False, randomize = False, fromfile = None, findleaks = False, use_resources = None, trace = False, coverdir = 'coverage', runleaks = False, huntrleaks = False, verbose2 = False):
  162.     """Execute a test suite.
  163.  
  164.     This also parses command-line options and modifies its behavior
  165.     accordingly.
  166.  
  167.     tests -- a list of strings containing test names (optional)
  168.     testdir -- the directory in which to look for tests (optional)
  169.  
  170.     Users other than the Python test suite will certainly want to
  171.     specify testdir; if it's omitted, the directory containing the
  172.     Python test suite is searched for.
  173.  
  174.     If the tests argument is omitted, the tests listed on the
  175.     command-line will be used.  If that's empty, too, then all *.py
  176.     files beginning with test_ will be used.
  177.  
  178.     The other default arguments (verbose, quiet, generate, exclude, single,
  179.     randomize, findleaks, use_resources, trace and coverdir) allow programmers
  180.     calling main() directly to set the values that would normally be set by
  181.     flags on the command line.
  182.     """
  183.     test_support.record_original_stdout(sys.stdout)
  184.     
  185.     try:
  186.         (opts, args) = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:TD:NLR:wM:', [
  187.             'help',
  188.             'verbose',
  189.             'quiet',
  190.             'generate',
  191.             'exclude',
  192.             'single',
  193.             'random',
  194.             'fromfile',
  195.             'findleaks',
  196.             'use=',
  197.             'threshold=',
  198.             'trace',
  199.             'coverdir=',
  200.             'nocoverdir',
  201.             'runleaks',
  202.             'huntrleaks=',
  203.             'verbose2',
  204.             'memlimit='])
  205.     except getopt.error:
  206.         msg = None
  207.         usage(2, msg)
  208.  
  209.     if use_resources is None:
  210.         use_resources = []
  211.     
  212.     for o, a in opts:
  213.         if o in ('-h', '--help'):
  214.             usage(0)
  215.             continue
  216.         if o in ('-v', '--verbose'):
  217.             verbose += 1
  218.             continue
  219.         if o in ('-w', '--verbose2'):
  220.             verbose2 = True
  221.             continue
  222.         if o in ('-q', '--quiet'):
  223.             quiet = True
  224.             verbose = 0
  225.             continue
  226.         if o in ('-g', '--generate'):
  227.             generate = True
  228.             continue
  229.         if o in ('-x', '--exclude'):
  230.             exclude = True
  231.             continue
  232.         if o in ('-s', '--single'):
  233.             single = True
  234.             continue
  235.         if o in ('-r', '--randomize'):
  236.             randomize = True
  237.             continue
  238.         if o in ('-f', '--fromfile'):
  239.             fromfile = a
  240.             continue
  241.         if o in ('-l', '--findleaks'):
  242.             findleaks = True
  243.             continue
  244.         if o in ('-L', '--runleaks'):
  245.             runleaks = True
  246.             continue
  247.         if o in ('-t', '--threshold'):
  248.             import gc
  249.             gc.set_threshold(int(a))
  250.             continue
  251.         if o in ('-T', '--coverage'):
  252.             trace = True
  253.             continue
  254.         if o in ('-D', '--coverdir'):
  255.             coverdir = os.path.join(os.getcwd(), a)
  256.             continue
  257.         if o in ('-N', '--nocoverdir'):
  258.             coverdir = None
  259.             continue
  260.         if o in ('-R', '--huntrleaks'):
  261.             huntrleaks = a.split(':')
  262.             if len(huntrleaks) != 3:
  263.                 print a, huntrleaks
  264.                 usage(2, '-R takes three colon-separated arguments')
  265.             
  266.             if len(huntrleaks[0]) == 0:
  267.                 huntrleaks[0] = 5
  268.             else:
  269.                 huntrleaks[0] = int(huntrleaks[0])
  270.             if len(huntrleaks[1]) == 0:
  271.                 huntrleaks[1] = 4
  272.             else:
  273.                 huntrleaks[1] = int(huntrleaks[1])
  274.             if len(huntrleaks[2]) == 0:
  275.                 huntrleaks[2] = 'reflog.txt'
  276.             
  277.         len(huntrleaks[2]) == 0
  278.         if o in ('-M', '--memlimit'):
  279.             test_support.set_memlimit(a)
  280.             continue
  281.         if o in ('-u', '--use'):
  282.             u = [ x.lower() for x in a.split(',') ]
  283.             for r in u:
  284.                 remove = False
  285.                 if r[0] == '-':
  286.                     remove = True
  287.                     r = r[1:]
  288.                 
  289.                 if r not in RESOURCE_NAMES:
  290.                     usage(1, 'Invalid -u/--use option: ' + a)
  291.                 
  292.                 if remove:
  293.                     if r in use_resources:
  294.                         use_resources.remove(r)
  295.                     
  296.                 r in use_resources
  297.                 if r not in use_resources:
  298.                     use_resources.append(r)
  299.                     continue
  300.             
  301.     
  302.     if generate and verbose:
  303.         usage(2, "-g and -v don't go together!")
  304.     
  305.     if single and fromfile:
  306.         usage(2, "-s and -f don't go together!")
  307.     
  308.     good = []
  309.     bad = []
  310.     skipped = []
  311.     resource_denieds = []
  312.     if findleaks:
  313.         
  314.         try:
  315.             import gc
  316.         except ImportError:
  317.             print 'No GC available, disabling findleaks.'
  318.             findleaks = False
  319.  
  320.         found_garbage = []
  321.     
  322.     if single:
  323.         gettempdir = gettempdir
  324.         import tempfile
  325.         filename = os.path.join(gettempdir(), 'pynexttest')
  326.         
  327.         try:
  328.             fp = open(filename, 'r')
  329.             next = fp.read().strip()
  330.             tests = [
  331.                 next]
  332.             fp.close()
  333.         except IOError:
  334.             pass
  335.         except:
  336.             None<EXCEPTION MATCH>IOError
  337.         
  338.  
  339.     None<EXCEPTION MATCH>IOError
  340.     if fromfile:
  341.         tests = []
  342.         fp = open(fromfile)
  343.         for line in fp:
  344.             guts = line.split()
  345.             if guts and not guts[0].startswith('#'):
  346.                 tests.extend(guts)
  347.                 continue
  348.         
  349.         fp.close()
  350.     
  351.     if args:
  352.         args = map(removepy, args)
  353.     
  354.     if tests:
  355.         tests = map(removepy, tests)
  356.     
  357.     stdtests = STDTESTS[:]
  358.     nottests = NOTTESTS[:]
  359.     if exclude:
  360.         for arg in args:
  361.             if arg in stdtests:
  362.                 stdtests.remove(arg)
  363.                 continue
  364.         
  365.         nottests[:0] = args
  366.         args = []
  367.     
  368.     if not tests and args:
  369.         pass
  370.     tests = findtests(testdir, stdtests, nottests)
  371.     if single:
  372.         tests = tests[:1]
  373.     
  374.     if randomize:
  375.         random.shuffle(tests)
  376.     
  377.     if trace:
  378.         import trace
  379.         tracer = trace.Trace(ignoredirs = [
  380.             sys.prefix,
  381.             sys.exec_prefix], trace = False, count = True)
  382.     
  383.     test_support.verbose = verbose
  384.     test_support.use_resources = use_resources
  385.     save_modules = sys.modules.keys()
  386.     for test in tests:
  387.         if not quiet:
  388.             print test
  389.             sys.stdout.flush()
  390.         
  391.         if trace:
  392.             tracer.runctx('runtest(test, generate, verbose, quiet, testdir)', globals = globals(), locals = vars())
  393.         else:
  394.             
  395.             try:
  396.                 ok = runtest(test, generate, verbose, quiet, testdir, huntrleaks)
  397.             except KeyboardInterrupt:
  398.                 print 
  399.                 break
  400.             except:
  401.                 raise 
  402.  
  403.             if ok > 0:
  404.                 good.append(test)
  405.             elif ok == 0:
  406.                 bad.append(test)
  407.             else:
  408.                 skipped.append(test)
  409.                 if ok == -2:
  410.                     resource_denieds.append(test)
  411.                 
  412.         if findleaks:
  413.             gc.collect()
  414.             if gc.garbage:
  415.                 print 'Warning: test created', len(gc.garbage), 'uncollectable object(s).'
  416.                 found_garbage.extend(gc.garbage)
  417.                 del gc.garbage[:]
  418.             
  419.         
  420.         for module in sys.modules.keys():
  421.             if module not in save_modules and module.startswith('test.'):
  422.                 test_support.unload(module)
  423.                 continue
  424.         
  425.     
  426.     good.sort()
  427.     bad.sort()
  428.     skipped.sort()
  429.     if good and not quiet:
  430.         if not bad and not skipped and len(good) > 1:
  431.             print 'All',
  432.         
  433.         print count(len(good), 'test'), 'OK.'
  434.         if verbose:
  435.             print "CAUTION:  stdout isn't compared in verbose mode:"
  436.             print 'a test that passes in verbose mode may fail without it.'
  437.         
  438.     
  439.     if bad:
  440.         print count(len(bad), 'test'), 'failed:'
  441.         printlist(bad)
  442.     
  443.     if skipped and not quiet:
  444.         print count(len(skipped), 'test'), 'skipped:'
  445.         printlist(skipped)
  446.         e = _ExpectedSkips()
  447.         plat = sys.platform
  448.         if e.isvalid():
  449.             surprise = set(skipped) - e.getexpected() - set(resource_denieds)
  450.             if surprise:
  451.                 print count(len(surprise), 'skip'), 'unexpected on', plat + ':'
  452.                 printlist(surprise)
  453.             else:
  454.                 print 'Those skips are all expected on', plat + '.'
  455.         else:
  456.             print 'Ask someone to teach regrtest.py about which tests are'
  457.             print 'expected to get skipped on', plat + '.'
  458.     
  459.     if verbose2 and bad:
  460.         print 'Re-running failed tests in verbose mode'
  461.         for test in bad:
  462.             print 'Re-running test %r in verbose mode' % test
  463.             sys.stdout.flush()
  464.             
  465.             try:
  466.                 test_support.verbose = 1
  467.                 ok = runtest(test, generate, 1, quiet, testdir, huntrleaks)
  468.             continue
  469.             except KeyboardInterrupt:
  470.                 print 
  471.                 break
  472.                 continue
  473.                 raise 
  474.                 continue
  475.             
  476.  
  477.         
  478.     
  479.     if single:
  480.         alltests = findtests(testdir, stdtests, nottests)
  481.         for i in range(len(alltests)):
  482.             if tests[0] == alltests[i]:
  483.                 if i == len(alltests) - 1:
  484.                     os.unlink(filename)
  485.                 else:
  486.                     fp = open(filename, 'w')
  487.                     fp.write(alltests[i + 1] + '\n')
  488.                     fp.close()
  489.                 break
  490.                 continue
  491.         
  492.     
  493.     if trace:
  494.         r = tracer.results()
  495.         r.write_results(show_missing = True, summary = True, coverdir = coverdir)
  496.     
  497.     if runleaks:
  498.         os.system('leaks %d' % os.getpid())
  499.     
  500.     sys.exit(len(bad) > 0)
  501.  
  502. STDTESTS = [
  503.     'test_grammar',
  504.     'test_opcodes',
  505.     'test_operations',
  506.     'test_builtin',
  507.     'test_exceptions',
  508.     'test_types',
  509.     'test_unittest',
  510.     'test_doctest',
  511.     'test_doctest2']
  512. NOTTESTS = [
  513.     'test_support',
  514.     'test_future1',
  515.     'test_future2',
  516.     'test_future3']
  517.  
  518. def findtests(testdir = None, stdtests = STDTESTS, nottests = NOTTESTS):
  519.     '''Return a list of all applicable test modules.'''
  520.     if not testdir:
  521.         testdir = findtestdir()
  522.     
  523.     names = os.listdir(testdir)
  524.     tests = []
  525.     for name in names:
  526.         if name[:5] == 'test_' and name[-3:] == os.extsep + 'py':
  527.             modname = name[:-3]
  528.             if modname not in stdtests and modname not in nottests:
  529.                 tests.append(modname)
  530.             
  531.         modname not in nottests
  532.     
  533.     tests.sort()
  534.     return stdtests + tests
  535.  
  536.  
  537. def runtest(test, generate, verbose, quiet, testdir = None, huntrleaks = False):
  538.     """Run a single test.
  539.  
  540.     test -- the name of the test
  541.     generate -- if true, generate output, instead of running the test
  542.                 and comparing it to a previously created output file
  543.     verbose -- if true, print more messages
  544.     quiet -- if true, don't print 'skipped' messages (probably redundant)
  545.     testdir -- test directory
  546.     huntrleaks -- run multiple times to test for leaks; requires a debug
  547.                   build; a triple corresponding to -R's three arguments
  548.     Return:
  549.         -2  test skipped because resource denied
  550.         -1  test skipped for some other reason
  551.          0  test failed
  552.          1  test passed
  553.     """
  554.     
  555.     try:
  556.         return runtest_inner(test, generate, verbose, quiet, testdir, huntrleaks)
  557.     finally:
  558.         cleanup_test_droppings(test, verbose)
  559.  
  560.  
  561.  
  562. def runtest_inner(test, generate, verbose, quiet, testdir = None, huntrleaks = False):
  563.     test_support.unload(test)
  564.     if not testdir:
  565.         testdir = findtestdir()
  566.     
  567.     outputdir = os.path.join(testdir, 'output')
  568.     outputfile = os.path.join(outputdir, test)
  569.     if verbose:
  570.         cfp = None
  571.     else:
  572.         cfp = cStringIO.StringIO()
  573.     
  574.     try:
  575.         save_stdout = sys.stdout
  576.         
  577.         try:
  578.             if cfp:
  579.                 sys.stdout = cfp
  580.                 print test
  581.             
  582.             if test.startswith('test.'):
  583.                 abstest = test
  584.             else:
  585.                 abstest = 'test.' + test
  586.             the_package = __import__(abstest, globals(), locals(), [])
  587.             the_module = getattr(the_package, test)
  588.             indirect_test = getattr(the_module, 'test_main', None)
  589.             if indirect_test is not None:
  590.                 indirect_test()
  591.             
  592.             if huntrleaks:
  593.                 dash_R(the_module, test, indirect_test, huntrleaks)
  594.         finally:
  595.             sys.stdout = save_stdout
  596.  
  597.     except test_support.ResourceDenied:
  598.         msg = None
  599.         if not quiet:
  600.             print test, 'skipped --', msg
  601.             sys.stdout.flush()
  602.         
  603.         return -2
  604.     except (ImportError, test_support.TestSkipped):
  605.         msg = None
  606.         if not quiet:
  607.             print test, 'skipped --', msg
  608.             sys.stdout.flush()
  609.         
  610.         return -1
  611.     except KeyboardInterrupt:
  612.         raise 
  613.     except test_support.TestFailed:
  614.         msg = None
  615.         print 'test', test, 'failed --', msg
  616.         sys.stdout.flush()
  617.         return 0
  618.     except:
  619.         (type, value) = sys.exc_info()[:2]
  620.         print 'test', test, 'crashed --', str(type) + ':', value
  621.         sys.stdout.flush()
  622.         if verbose:
  623.             traceback.print_exc(file = sys.stdout)
  624.             sys.stdout.flush()
  625.         
  626.         return 0
  627.  
  628.     if not cfp:
  629.         return 1
  630.     
  631.     output = cfp.getvalue()
  632.     if generate:
  633.         if output == test + '\n':
  634.             if os.path.exists(outputfile):
  635.                 print 'output file', outputfile, 'is no longer needed; consider removing it'
  636.             else:
  637.                 return 1
  638.         
  639.         fp = open(outputfile, 'w')
  640.         fp.write(output)
  641.         fp.close()
  642.         return 1
  643.     
  644.     if os.path.exists(outputfile):
  645.         fp = open(outputfile, 'r')
  646.         expected = fp.read()
  647.         fp.close()
  648.     else:
  649.         expected = test + '\n'
  650.     if output == expected or huntrleaks:
  651.         return 1
  652.     
  653.     print 'test', test, 'produced unexpected output:'
  654.     sys.stdout.flush()
  655.     reportdiff(expected, output)
  656.     sys.stdout.flush()
  657.     return 0
  658.  
  659.  
  660. def cleanup_test_droppings(testname, verbose):
  661.     import shutil
  662.     for name in (test_support.TESTFN, 'db_home'):
  663.         if not os.path.exists(name):
  664.             continue
  665.         
  666.         if os.path.isdir(name):
  667.             kind = 'directory'
  668.             nuker = shutil.rmtree
  669.         elif os.path.isfile(name):
  670.             kind = 'file'
  671.             nuker = os.unlink
  672.         else:
  673.             raise SystemError('os.path says %r exists but is neither directory nor file' % name)
  674.         if verbose:
  675.             print '%r left behind %s %r' % (testname, kind, name)
  676.         
  677.         
  678.         try:
  679.             nuker(name)
  680.         continue
  681.         except Exception:
  682.             msg = None
  683.             print >>sys.stderr, "%r left behind %s %r and it couldn't be removed: %s" % (testname, kind, name, msg)
  684.             continue
  685.         
  686.  
  687.     
  688.  
  689.  
  690. def dash_R(the_module, test, indirect_test, huntrleaks):
  691.     import copy_reg
  692.     if not hasattr(sys, 'gettotalrefcount'):
  693.         raise Exception('Tracking reference leaks requires a debug build of Python')
  694.     
  695.     fs = warnings.filters[:]
  696.     ps = copy_reg.dispatch_table.copy()
  697.     pic = sys.path_importer_cache.copy()
  698.     deltas = []
  699.     (nwarmup, ntracked, fname) = huntrleaks
  700.     repcount = nwarmup + ntracked
  701.     print >>sys.stderr, 'beginning', repcount, 'repetitions'
  702.     print >>sys.stderr, '1234567890' * (repcount // 10 + 1)[:repcount]
  703.     dash_R_cleanup(fs, ps, pic)
  704.     for i in range(repcount):
  705.         rc = sys.gettotalrefcount()
  706.         run_the_test()
  707.         sys.stderr.write('.')
  708.         dash_R_cleanup(fs, ps, pic)
  709.         if i >= nwarmup:
  710.             deltas.append(sys.gettotalrefcount() - rc - 2)
  711.             continue
  712.     
  713.     print >>sys.stderr
  714.     if any(deltas):
  715.         print >>sys.stderr, test, 'leaked', deltas, 'references'
  716.         refrep = open(fname, 'a')
  717.         print >>refrep, test, 'leaked', deltas, 'references'
  718.         refrep.close()
  719.     
  720.  
  721.  
  722. def dash_R_cleanup(fs, ps, pic):
  723.     import gc
  724.     import copy_reg
  725.     import _strptime
  726.     import linecache
  727.     import dircache
  728.     import urlparse
  729.     import urllib
  730.     import urllib2
  731.     import mimetypes
  732.     import doctest
  733.     import struct
  734.     import filecmp
  735.     _path_created = _path_created
  736.     import distutils.dir_util
  737.     warnings.filters[:] = fs
  738.     copy_reg.dispatch_table.clear()
  739.     copy_reg.dispatch_table.update(ps)
  740.     sys.path_importer_cache.clear()
  741.     sys.path_importer_cache.update(pic)
  742.     _path_created.clear()
  743.     re.purge()
  744.     _strptime._regex_cache.clear()
  745.     urlparse.clear_cache()
  746.     urllib.urlcleanup()
  747.     urllib2.install_opener(None)
  748.     dircache.reset()
  749.     linecache.clearcache()
  750.     mimetypes._default_mime_types()
  751.     struct._cache.clear()
  752.     filecmp._cache.clear()
  753.     doctest.master = None
  754.     gc.collect()
  755.  
  756.  
  757. def reportdiff(expected, output):
  758.     import difflib
  759.     print '*' * 70
  760.     a = expected.splitlines(1)
  761.     b = output.splitlines(1)
  762.     sm = difflib.SequenceMatcher(a = a, b = b)
  763.     tuples = sm.get_opcodes()
  764.     
  765.     def pair(x0, x1):
  766.         x0 += 1
  767.         if x0 >= x1:
  768.             return 'line ' + str(x0)
  769.         else:
  770.             return 'lines %d-%d' % (x0, x1)
  771.  
  772.     for op, a0, a1, b0, b1 in tuples:
  773.         if op == 'equal':
  774.             continue
  775.         if op == 'delete':
  776.             print '***', pair(a0, a1), 'of expected output missing:'
  777.             for line in a[a0:a1]:
  778.                 print '-', line,
  779.             
  780.         if op == 'replace':
  781.             print '*** mismatch between', pair(a0, a1), 'of expected', 'output and', pair(b0, b1), 'of actual output:'
  782.             for line in difflib.ndiff(a[a0:a1], b[b0:b1]):
  783.                 print line,
  784.             
  785.         if op == 'insert':
  786.             print '***', pair(b0, b1), "of actual output doesn't appear", 'in expected output after line', str(a1) + ':'
  787.             for line in b[b0:b1]:
  788.                 print '+', line,
  789.             
  790.         print 'get_opcodes() returned bad tuple?!?!', (op, a0, a1, b0, b1)
  791.     
  792.     print '*' * 70
  793.  
  794.  
  795. def findtestdir():
  796.     if __name__ == '__main__':
  797.         file = sys.argv[0]
  798.     else:
  799.         file = __file__
  800.     if not os.path.dirname(file):
  801.         pass
  802.     testdir = os.curdir
  803.     return testdir
  804.  
  805.  
  806. def removepy(name):
  807.     if name.endswith(os.extsep + 'py'):
  808.         name = name[:-3]
  809.     
  810.     return name
  811.  
  812.  
  813. def count(n, word):
  814.     if n == 1:
  815.         return '%d %s' % (n, word)
  816.     else:
  817.         return '%d %ss' % (n, word)
  818.  
  819.  
  820. def printlist(x, width = 70, indent = 4):
  821.     '''Print the elements of iterable x to stdout.
  822.  
  823.     Optional arg width (default 70) is the maximum line length.
  824.     Optional arg indent (default 4) is the number of blanks with which to
  825.     begin each line.
  826.     '''
  827.     fill = fill
  828.     import textwrap
  829.     blanks = ' ' * indent
  830.     print fill(' '.join(map(str, x)), width, initial_indent = blanks, subsequent_indent = blanks)
  831.  
  832. _expectations = {
  833.     'win32': '\n        test__locale\n        test_applesingle\n        test_al\n        test_bsddb185\n        test_bsddb3\n        test_cd\n        test_cl\n        test_commands\n        test_crypt\n        test_curses\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_gdbm\n        test_gl\n        test_grp\n        test_imgfile\n        test_ioctl\n        test_largefile\n        test_linuxaudiodev\n        test_mhlib\n        test_nis\n        test_openpty\n        test_ossaudiodev\n        test_poll\n        test_posix\n        test_pty\n        test_pwd\n        test_resource\n        test_signal\n        test_sunaudiodev\n        test_threadsignals\n        test_timing\n        test_wait3\n        test_wait4\n        ',
  834.     'linux2': '\n        test_al\n        test_applesingle\n        test_bsddb185\n        test_cd\n        test_cl\n        test_curses\n        test_dl\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_nis\n        test_ntpath\n        test_ossaudiodev\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        ',
  835.     'mac': '\n        test_al\n        test_atexit\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_bz2\n        test_cd\n        test_cl\n        test_commands\n        test_crypt\n        test_curses\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_gl\n        test_grp\n        test_ioctl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_mmap\n        test_nis\n        test_ntpath\n        test_openpty\n        test_ossaudiodev\n        test_poll\n        test_popen\n        test_popen2\n        test_posix\n        test_pty\n        test_pwd\n        test_resource\n        test_signal\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        test_sundry\n        test_tarfile\n        test_timing\n        ',
  836.     'unixware7': '\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb185\n        test_cd\n        test_cl\n        test_dl\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_minidom\n        test_nis\n        test_ntpath\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_startfile\n        test_sqlite\n        test_sunaudiodev\n        test_sundry\n        ',
  837.     'openunix8': '\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb185\n        test_cd\n        test_cl\n        test_dl\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_minidom\n        test_nis\n        test_ntpath\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        test_sundry\n        ',
  838.     'sco_sv3': '\n        test_al\n        test_applesingle\n        test_asynchat\n        test_bsddb\n        test_bsddb185\n        test_cd\n        test_cl\n        test_dl\n        test_fork1\n        test_gettext\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_minidom\n        test_nis\n        test_ntpath\n        test_openpty\n        test_pyexpat\n        test_queue\n        test_sax\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        test_sundry\n        test_thread\n        test_threaded_import\n        test_threadedtempfile\n        test_threading\n        ',
  839.     'riscos': '\n        test_al\n        test_applesingle\n        test_asynchat\n        test_atexit\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_cd\n        test_cl\n        test_commands\n        test_crypt\n        test_dbm\n        test_dl\n        test_fcntl\n        test_fork1\n        test_gdbm\n        test_gl\n        test_grp\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_mmap\n        test_nis\n        test_ntpath\n        test_openpty\n        test_poll\n        test_popen2\n        test_pty\n        test_pwd\n        test_strop\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        test_sundry\n        test_thread\n        test_threaded_import\n        test_threadedtempfile\n        test_threading\n        test_timing\n        ',
  840.     'darwin': '\n        test__locale\n        test_al\n        test_bsddb\n        test_bsddb3\n        test_cd\n        test_cl\n        test_curses\n        test_gdbm\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_minidom\n        test_nis\n        test_ntpath\n        test_ossaudiodev\n        test_poll\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        ',
  841.     'sunos5': '\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb185\n        test_cd\n        test_cl\n        test_curses\n        test_dbm\n        test_gdbm\n        test_gl\n        test_gzip\n        test_imgfile\n        test_linuxaudiodev\n        test_openpty\n        test_sqlite\n        test_startfile\n        test_zipfile\n        test_zlib\n        ',
  842.     'hp-ux11': '\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb185\n        test_cd\n        test_cl\n        test_curses\n        test_dl\n        test_gdbm\n        test_gl\n        test_gzip\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_minidom\n        test_nis\n        test_ntpath\n        test_openpty\n        test_pyexpat\n        test_sax\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        test_zipfile\n        test_zlib\n        ',
  843.     'atheos': '\n        test_al\n        test_applesingle\n        test_bsddb185\n        test_cd\n        test_cl\n        test_curses\n        test_dl\n        test_gdbm\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_mhlib\n        test_mmap\n        test_nis\n        test_poll\n        test_popen2\n        test_resource\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        ',
  844.     'cygwin': '\n        test_al\n        test_applesingle\n        test_bsddb185\n        test_bsddb3\n        test_cd\n        test_cl\n        test_curses\n        test_dbm\n        test_gl\n        test_imgfile\n        test_ioctl\n        test_largefile\n        test_linuxaudiodev\n        test_locale\n        test_nis\n        test_ossaudiodev\n        test_socketserver\n        test_sqlite\n        test_sunaudiodev\n        ',
  845.     'os2emx': '\n        test_al\n        test_applesingle\n        test_audioop\n        test_bsddb185\n        test_bsddb3\n        test_cd\n        test_cl\n        test_commands\n        test_curses\n        test_dl\n        test_gl\n        test_imgfile\n        test_largefile\n        test_linuxaudiodev\n        test_mhlib\n        test_mmap\n        test_nis\n        test_openpty\n        test_ossaudiodev\n        test_pty\n        test_resource\n        test_signal\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        ',
  846.     'freebsd4': '\n        test_aepack\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb3\n        test_cd\n        test_cl\n        test_gdbm\n        test_gl\n        test_imgfile\n        test_linuxaudiodev\n        test_locale\n        test_macfs\n        test_macostools\n        test_nis\n        test_ossaudiodev\n        test_pep277\n        test_plistlib\n        test_pty\n        test_scriptpackages\n        test_socket_ssl\n        test_socketserver\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        test_tcl\n        test_timeout\n        test_unicode_file\n        test_urllibnet\n        test_winreg\n        test_winsound\n        ',
  847.     'aix5': '\n        test_aepack\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_bz2\n        test_cd\n        test_cl\n        test_dl\n        test_gdbm\n        test_gl\n        test_gzip\n        test_imgfile\n        test_linuxaudiodev\n        test_macfs\n        test_macostools\n        test_nis\n        test_ossaudiodev\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        test_tcl\n        test_winreg\n        test_winsound\n        test_zipimport\n        test_zlib\n        ',
  848.     'openbsd3': '\n        test_aepack\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb3\n        test_cd\n        test_cl\n        test_ctypes\n        test_dl\n        test_gdbm\n        test_gl\n        test_imgfile\n        test_linuxaudiodev\n        test_locale\n        test_macfs\n        test_macostools\n        test_nis\n        test_normalization\n        test_ossaudiodev\n        test_pep277\n        test_plistlib\n        test_scriptpackages\n        test_tcl\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        test_unicode_file\n        test_winreg\n        test_winsound\n        ',
  849.     'netbsd3': '\n        test_aepack\n        test_al\n        test_applesingle\n        test_bsddb\n        test_bsddb185\n        test_bsddb3\n        test_cd\n        test_cl\n        test_ctypes\n        test_curses\n        test_dl\n        test_gdbm\n        test_gl\n        test_imgfile\n        test_linuxaudiodev\n        test_locale\n        test_macfs\n        test_macostools\n        test_nis\n        test_ossaudiodev\n        test_pep277\n        test_sqlite\n        test_startfile\n        test_sunaudiodev\n        test_tcl\n        test_unicode_file\n        test_winreg\n        test_winsound\n        ' }
  850. _expectations['linux2-alpha'] = _expectations['linux2']
  851. _expectations['linux2-hppa'] = _expectations['linux2']
  852. _expectations['linux2-mips'] = _expectations['linux2']
  853. _expectations['linux2-sparc'] = _expectations['linux2']
  854. _expectations['freebsd5'] = _expectations['freebsd4']
  855. _expectations['freebsd6'] = _expectations['freebsd4']
  856. _expectations['freebsd7'] = _expectations['freebsd4']
  857.  
  858. class _ExpectedSkips:
  859.     
  860.     def __init__(self):
  861.         import os.path as os
  862.         test_socket_ssl = test_socket_ssl
  863.         import test
  864.         test_timeout = test_timeout
  865.         import test
  866.         self.valid = False
  867.         if sys.platform in _expectations:
  868.             s = _expectations[sys.platform]
  869.             self.expected = set(s.split())
  870.             if not os.path.supports_unicode_filenames:
  871.                 self.expected.add('test_pep277')
  872.             
  873.             if test_socket_ssl.skip_expected:
  874.                 self.expected.add('test_socket_ssl')
  875.             
  876.             if test_timeout.skip_expected:
  877.                 self.expected.add('test_timeout')
  878.             
  879.             if sys.maxint == 0x7FFFFFFFFFFFFFFFL:
  880.                 self.expected.add('test_rgbimg')
  881.                 self.expected.add('test_imageop')
  882.             
  883.             if sys.platform not in ('mac', 'darwin'):
  884.                 MAC_ONLY = [
  885.                     'test_macostools',
  886.                     'test_macfs',
  887.                     'test_aepack',
  888.                     'test_plistlib',
  889.                     'test_scriptpackages']
  890.                 for skip in MAC_ONLY:
  891.                     self.expected.add(skip)
  892.                 
  893.             
  894.             if sys.platform != 'win32':
  895.                 WIN_ONLY = [
  896.                     'test_unicode_file',
  897.                     'test_winreg',
  898.                     'test_winsound']
  899.                 for skip in WIN_ONLY:
  900.                     self.expected.add(skip)
  901.                 
  902.             
  903.             self.valid = True
  904.         
  905.  
  906.     
  907.     def isvalid(self):
  908.         '''Return true iff _ExpectedSkips knows about the current platform.'''
  909.         return self.valid
  910.  
  911.     
  912.     def getexpected(self):
  913.         '''Return set of test names we expect to skip on current platform.
  914.  
  915.         self.isvalid() must be true.
  916.         '''
  917.         if not self.isvalid():
  918.             raise AssertionError
  919.         return self.expected
  920.  
  921.  
  922. if __name__ == '__main__':
  923.     mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
  924.     i = pathlen = len(sys.path)
  925.     while i >= 0:
  926.         i -= 1
  927.         if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
  928.             del sys.path[i]
  929.         
  930.     if len(sys.path) == pathlen:
  931.         print 'Could not find %r in sys.path to remove it' % mydir
  932.     
  933.     main()
  934.  
  935.