PageRenderTime 99ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2/test/regrtest.py

https://bitbucket.org/kcr/pypy
Python | 1556 lines | 1467 code | 17 blank | 72 comment | 49 complexity | 6909059aca3396cb2db0f89f383d73e3 MD5 | raw file
Possible License(s): Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. #! /usr/bin/env python
  2. """
  3. Usage:
  4. python -m test.regrtest [options] [test_name1 [test_name2 ...]]
  5. python path/to/Lib/test/regrtest.py [options] [test_name1 [test_name2 ...]]
  6. If no arguments or options are provided, finds all files matching
  7. the pattern "test_*" in the Lib/test subdirectory and runs
  8. them in alphabetical order (but see -M and -u, below, for exceptions).
  9. For more rigorous testing, it is useful to use the following
  10. command line:
  11. python -E -tt -Wd -3 -m test.regrtest [options] [test_name1 ...]
  12. Options:
  13. -h/--help -- print this text and exit
  14. Verbosity
  15. -v/--verbose -- run tests in verbose mode with output to stdout
  16. -w/--verbose2 -- re-run failed tests in verbose mode
  17. -W/--verbose3 -- re-run failed tests in verbose mode immediately
  18. -q/--quiet -- no output unless one or more tests fail
  19. -S/--slow -- print the slowest 10 tests
  20. --header -- print header with interpreter info
  21. Selecting tests
  22. -r/--random -- randomize test execution order (see below)
  23. --randseed -- pass a random seed to reproduce a previous random run
  24. -f/--fromfile -- read names of tests to run from a file (see below)
  25. -x/--exclude -- arguments are tests to *exclude*
  26. -s/--single -- single step through a set of tests (see below)
  27. -u/--use RES1,RES2,...
  28. -- specify which special resource intensive tests to run
  29. -M/--memlimit LIMIT
  30. -- run very large memory-consuming tests
  31. Special runs
  32. -l/--findleaks -- if GC is available detect tests that leak memory
  33. -L/--runleaks -- run the leaks(1) command just before exit
  34. -R/--huntrleaks RUNCOUNTS
  35. -- search for reference leaks (needs debug build, v. slow)
  36. -j/--multiprocess PROCESSES
  37. -- run PROCESSES processes at once
  38. -T/--coverage -- turn on code coverage tracing using the trace module
  39. -D/--coverdir DIRECTORY
  40. -- Directory where coverage files are put
  41. -N/--nocoverdir -- Put coverage files alongside modules
  42. -t/--threshold THRESHOLD
  43. -- call gc.set_threshold(THRESHOLD)
  44. -F/--forever -- run the specified tests in a loop, until an error happens
  45. Additional Option Details:
  46. -r randomizes test execution order. You can use --randseed=int to provide a
  47. int seed value for the randomizer; this is useful for reproducing troublesome
  48. test orders.
  49. -s On the first invocation of regrtest using -s, the first test file found
  50. or the first test file given on the command line is run, and the name of
  51. the next test is recorded in a file named pynexttest. If run from the
  52. Python build directory, pynexttest is located in the 'build' subdirectory,
  53. otherwise it is located in tempfile.gettempdir(). On subsequent runs,
  54. the test in pynexttest is run, and the next test is written to pynexttest.
  55. When the last test has been run, pynexttest is deleted. In this way it
  56. is possible to single step through the test files. This is useful when
  57. doing memory analysis on the Python interpreter, which process tends to
  58. consume too many resources to run the full regression test non-stop.
  59. -f reads the names of tests from the file given as f's argument, one
  60. or more test names per line. Whitespace is ignored. Blank lines and
  61. lines beginning with '#' are ignored. This is especially useful for
  62. whittling down failures involving interactions among tests.
  63. -L causes the leaks(1) command to be run just before exit if it exists.
  64. leaks(1) is available on Mac OS X and presumably on some other
  65. FreeBSD-derived systems.
  66. -R runs each test several times and examines sys.gettotalrefcount() to
  67. see if the test appears to be leaking references. The argument should
  68. be of the form stab:run:fname where 'stab' is the number of times the
  69. test is run to let gettotalrefcount settle down, 'run' is the number
  70. of times further it is run and 'fname' is the name of the file the
  71. reports are written to. These parameters all have defaults (5, 4 and
  72. "reflog.txt" respectively), and the minimal invocation is '-R :'.
  73. -M runs tests that require an exorbitant amount of memory. These tests
  74. typically try to ascertain containers keep working when containing more than
  75. 2 billion objects, which only works on 64-bit systems. There are also some
  76. tests that try to exhaust the address space of the process, which only makes
  77. sense on 32-bit systems with at least 2Gb of memory. The passed-in memlimit,
  78. which is a string in the form of '2.5Gb', determines howmuch memory the
  79. tests will limit themselves to (but they may go slightly over.) The number
  80. shouldn't be more memory than the machine has (including swap memory). You
  81. should also keep in mind that swap memory is generally much, much slower
  82. than RAM, and setting memlimit to all available RAM or higher will heavily
  83. tax the machine. On the other hand, it is no use running these tests with a
  84. limit of less than 2.5Gb, and many require more than 20Gb. Tests that expect
  85. to use more than memlimit memory will be skipped. The big-memory tests
  86. generally run very, very long.
  87. -u is used to specify which special resource intensive tests to run,
  88. such as those requiring large file support or network connectivity.
  89. The argument is a comma-separated list of words indicating the
  90. resources to test. Currently only the following are defined:
  91. all - Enable all special resources.
  92. audio - Tests that use the audio device. (There are known
  93. cases of broken audio drivers that can crash Python or
  94. even the Linux kernel.)
  95. curses - Tests that use curses and will modify the terminal's
  96. state and output modes.
  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. network - It is okay to run tests that use external network
  101. resource, e.g. testing SSL support for sockets.
  102. bsddb - It is okay to run the bsddb testsuite, which takes
  103. a long time to complete.
  104. decimal - Test the decimal module against a large suite that
  105. verifies compliance with standards.
  106. cpu - Used for certain CPU-heavy tests.
  107. subprocess Run all tests for the subprocess module.
  108. urlfetch - It is okay to download files required on testing.
  109. gui - Run tests that require a running GUI.
  110. xpickle - Test pickle and cPickle against Python 2.4, 2.5 and 2.6 to
  111. test backwards compatibility. These tests take a long time
  112. to run.
  113. To enable all resources except one, use '-uall,-<resource>'. For
  114. example, to run all the tests except for the bsddb tests, give the
  115. option '-uall,-bsddb'.
  116. """
  117. import StringIO
  118. import getopt
  119. import json
  120. import os
  121. import random
  122. import re
  123. import sys
  124. import time
  125. import traceback
  126. import warnings
  127. import unittest
  128. import tempfile
  129. import imp
  130. import platform
  131. import sysconfig
  132. # Some times __path__ and __file__ are not absolute (e.g. while running from
  133. # Lib/) and, if we change the CWD to run the tests in a temporary dir, some
  134. # imports might fail. This affects only the modules imported before os.chdir().
  135. # These modules are searched first in sys.path[0] (so '' -- the CWD) and if
  136. # they are found in the CWD their __file__ and __path__ will be relative (this
  137. # happens before the chdir). All the modules imported after the chdir, are
  138. # not found in the CWD, and since the other paths in sys.path[1:] are absolute
  139. # (site.py absolutize them), the __file__ and __path__ will be absolute too.
  140. # Therefore it is necessary to absolutize manually the __file__ and __path__ of
  141. # the packages to prevent later imports to fail when the CWD is different.
  142. for module in sys.modules.itervalues():
  143. if hasattr(module, '__path__'):
  144. module.__path__ = [os.path.abspath(path) for path in module.__path__]
  145. if hasattr(module, '__file__'):
  146. module.__file__ = os.path.abspath(module.__file__)
  147. # MacOSX (a.k.a. Darwin) has a default stack size that is too small
  148. # for deeply recursive regular expressions. We see this as crashes in
  149. # the Python test suite when running test_re.py and test_sre.py. The
  150. # fix is to set the stack limit to 2048.
  151. # This approach may also be useful for other Unixy platforms that
  152. # suffer from small default stack limits.
  153. if sys.platform == 'darwin':
  154. try:
  155. import resource
  156. except ImportError:
  157. pass
  158. else:
  159. soft, hard = resource.getrlimit(resource.RLIMIT_STACK)
  160. newsoft = min(hard, max(soft, 1024*2048))
  161. resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
  162. # Test result constants.
  163. PASSED = 1
  164. FAILED = 0
  165. ENV_CHANGED = -1
  166. SKIPPED = -2
  167. RESOURCE_DENIED = -3
  168. INTERRUPTED = -4
  169. from test import test_support
  170. RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network', 'bsddb',
  171. 'decimal', 'cpu', 'subprocess', 'urlfetch', 'gui',
  172. 'xpickle')
  173. TEMPDIR = os.path.abspath(tempfile.gettempdir())
  174. def usage(code, msg=''):
  175. print __doc__
  176. if msg: print msg
  177. sys.exit(code)
  178. def main(tests=None, testdir=None, verbose=0, quiet=False,
  179. exclude=False, single=False, randomize=False, fromfile=None,
  180. findleaks=False, use_resources=None, trace=False, coverdir='coverage',
  181. runleaks=False, huntrleaks=False, verbose2=False, print_slow=False,
  182. random_seed=None, use_mp=None, verbose3=False, forever=False,
  183. header=False):
  184. """Execute a test suite.
  185. This also parses command-line options and modifies its behavior
  186. accordingly.
  187. tests -- a list of strings containing test names (optional)
  188. testdir -- the directory in which to look for tests (optional)
  189. Users other than the Python test suite will certainly want to
  190. specify testdir; if it's omitted, the directory containing the
  191. Python test suite is searched for.
  192. If the tests argument is omitted, the tests listed on the
  193. command-line will be used. If that's empty, too, then all *.py
  194. files beginning with test_ will be used.
  195. The other default arguments (verbose, quiet, exclude,
  196. single, randomize, findleaks, use_resources, trace, coverdir,
  197. print_slow, and random_seed) allow programmers calling main()
  198. directly to set the values that would normally be set by flags
  199. on the command line.
  200. """
  201. test_support.record_original_stdout(sys.stdout)
  202. try:
  203. opts, args = getopt.getopt(sys.argv[1:], 'hvqxsSrf:lu:t:TD:NLR:FwWM:j:',
  204. ['help', 'verbose', 'verbose2', 'verbose3', 'quiet',
  205. 'exclude', 'single', 'slow', 'random', 'fromfile', 'findleaks',
  206. 'use=', 'threshold=', 'trace', 'coverdir=', 'nocoverdir',
  207. 'runleaks', 'huntrleaks=', 'memlimit=', 'randseed=',
  208. 'multiprocess=', 'slaveargs=', 'forever', 'header'])
  209. except getopt.error, msg:
  210. usage(2, msg)
  211. # Defaults
  212. if random_seed is None:
  213. random_seed = random.randrange(10000000)
  214. if use_resources is None:
  215. use_resources = []
  216. for o, a in opts:
  217. if o in ('-h', '--help'):
  218. usage(0)
  219. elif o in ('-v', '--verbose'):
  220. verbose += 1
  221. elif o in ('-w', '--verbose2'):
  222. verbose2 = True
  223. elif o in ('-W', '--verbose3'):
  224. verbose3 = True
  225. elif o in ('-q', '--quiet'):
  226. quiet = True;
  227. verbose = 0
  228. elif o in ('-x', '--exclude'):
  229. exclude = True
  230. elif o in ('-s', '--single'):
  231. single = True
  232. elif o in ('-S', '--slow'):
  233. print_slow = True
  234. elif o in ('-r', '--randomize'):
  235. randomize = True
  236. elif o == '--randseed':
  237. random_seed = int(a)
  238. elif o in ('-f', '--fromfile'):
  239. fromfile = a
  240. elif o in ('-l', '--findleaks'):
  241. findleaks = True
  242. elif o in ('-L', '--runleaks'):
  243. runleaks = True
  244. elif o in ('-t', '--threshold'):
  245. import gc
  246. gc.set_threshold(int(a))
  247. elif o in ('-T', '--coverage'):
  248. trace = True
  249. elif o in ('-D', '--coverdir'):
  250. coverdir = os.path.join(os.getcwd(), a)
  251. elif o in ('-N', '--nocoverdir'):
  252. coverdir = None
  253. elif o in ('-R', '--huntrleaks'):
  254. huntrleaks = a.split(':')
  255. if len(huntrleaks) not in (2, 3):
  256. print a, huntrleaks
  257. usage(2, '-R takes 2 or 3 colon-separated arguments')
  258. if not huntrleaks[0]:
  259. huntrleaks[0] = 5
  260. else:
  261. huntrleaks[0] = int(huntrleaks[0])
  262. if not huntrleaks[1]:
  263. huntrleaks[1] = 4
  264. else:
  265. huntrleaks[1] = int(huntrleaks[1])
  266. if len(huntrleaks) == 2 or not huntrleaks[2]:
  267. huntrleaks[2:] = ["reflog.txt"]
  268. elif o in ('-M', '--memlimit'):
  269. test_support.set_memlimit(a)
  270. elif o in ('-u', '--use'):
  271. u = [x.lower() for x in a.split(',')]
  272. for r in u:
  273. if r == 'all':
  274. use_resources[:] = RESOURCE_NAMES
  275. continue
  276. remove = False
  277. if r[0] == '-':
  278. remove = True
  279. r = r[1:]
  280. if r not in RESOURCE_NAMES:
  281. usage(1, 'Invalid -u/--use option: ' + a)
  282. if remove:
  283. if r in use_resources:
  284. use_resources.remove(r)
  285. elif r not in use_resources:
  286. use_resources.append(r)
  287. elif o in ('-F', '--forever'):
  288. forever = True
  289. elif o in ('-j', '--multiprocess'):
  290. use_mp = int(a)
  291. elif o == '--header':
  292. header = True
  293. elif o == '--slaveargs':
  294. args, kwargs = json.loads(a)
  295. try:
  296. result = runtest(*args, **kwargs)
  297. except BaseException, e:
  298. result = INTERRUPTED, e.__class__.__name__
  299. print # Force a newline (just in case)
  300. print json.dumps(result)
  301. sys.exit(0)
  302. else:
  303. print >>sys.stderr, ("No handler for option {}. Please "
  304. "report this as a bug at http://bugs.python.org.").format(o)
  305. sys.exit(1)
  306. if single and fromfile:
  307. usage(2, "-s and -f don't go together!")
  308. if use_mp and trace:
  309. usage(2, "-T and -j don't go together!")
  310. if use_mp and findleaks:
  311. usage(2, "-l and -j don't go together!")
  312. good = []
  313. bad = []
  314. skipped = []
  315. resource_denieds = []
  316. environment_changed = []
  317. interrupted = False
  318. if findleaks:
  319. try:
  320. import gc
  321. except ImportError:
  322. print 'No GC available, disabling findleaks.'
  323. findleaks = False
  324. else:
  325. # Uncomment the line below to report garbage that is not
  326. # freeable by reference counting alone. By default only
  327. # garbage that is not collectable by the GC is reported.
  328. #gc.set_debug(gc.DEBUG_SAVEALL)
  329. found_garbage = []
  330. if single:
  331. filename = os.path.join(TEMPDIR, 'pynexttest')
  332. try:
  333. fp = open(filename, 'r')
  334. next_test = fp.read().strip()
  335. tests = [next_test]
  336. fp.close()
  337. except IOError:
  338. pass
  339. if fromfile:
  340. tests = []
  341. fp = open(os.path.join(test_support.SAVEDCWD, fromfile))
  342. for line in fp:
  343. guts = line.split() # assuming no test has whitespace in its name
  344. if guts and not guts[0].startswith('#'):
  345. tests.extend(guts)
  346. fp.close()
  347. # Strip .py extensions.
  348. removepy(args)
  349. removepy(tests)
  350. stdtests = STDTESTS[:]
  351. nottests = NOTTESTS.copy()
  352. if exclude:
  353. for arg in args:
  354. if arg in stdtests:
  355. stdtests.remove(arg)
  356. nottests.add(arg)
  357. args = []
  358. # For a partial run, we do not need to clutter the output.
  359. if verbose or header or not (quiet or single or tests or args):
  360. # Print basic platform information
  361. print "==", platform.python_implementation(), \
  362. " ".join(sys.version.split())
  363. print "== ", platform.platform(aliased=True), \
  364. "%s-endian" % sys.byteorder
  365. print "== ", os.getcwd()
  366. print "Testing with flags:", sys.flags
  367. alltests = findtests(testdir, stdtests, nottests)
  368. selected = tests or args or alltests
  369. if single:
  370. selected = selected[:1]
  371. try:
  372. next_single_test = alltests[alltests.index(selected[0])+1]
  373. except IndexError:
  374. next_single_test = None
  375. if randomize:
  376. random.seed(random_seed)
  377. print "Using random seed", random_seed
  378. random.shuffle(selected)
  379. if trace:
  380. import trace
  381. tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix],
  382. trace=False, count=True)
  383. test_times = []
  384. test_support.use_resources = use_resources
  385. save_modules = sys.modules.keys()
  386. def accumulate_result(test, result):
  387. ok, test_time = result
  388. test_times.append((test_time, test))
  389. if ok == PASSED:
  390. good.append(test)
  391. elif ok == FAILED:
  392. bad.append(test)
  393. elif ok == ENV_CHANGED:
  394. bad.append(test)
  395. environment_changed.append(test)
  396. elif ok == SKIPPED:
  397. skipped.append(test)
  398. elif ok == RESOURCE_DENIED:
  399. skipped.append(test)
  400. resource_denieds.append(test)
  401. if forever:
  402. def test_forever(tests=list(selected)):
  403. while True:
  404. for test in tests:
  405. yield test
  406. if bad:
  407. return
  408. tests = test_forever()
  409. else:
  410. tests = iter(selected)
  411. if use_mp:
  412. try:
  413. from threading import Thread
  414. except ImportError:
  415. print "Multiprocess option requires thread support"
  416. sys.exit(2)
  417. from Queue import Queue
  418. from subprocess import Popen, PIPE
  419. debug_output_pat = re.compile(r"\[\d+ refs\]$")
  420. output = Queue()
  421. def tests_and_args():
  422. for test in tests:
  423. args_tuple = (
  424. (test, verbose, quiet),
  425. dict(huntrleaks=huntrleaks, use_resources=use_resources)
  426. )
  427. yield (test, args_tuple)
  428. pending = tests_and_args()
  429. opt_args = test_support.args_from_interpreter_flags()
  430. base_cmd = [sys.executable] + opt_args + ['-m', 'test.regrtest']
  431. def work():
  432. # A worker thread.
  433. try:
  434. while True:
  435. try:
  436. test, args_tuple = next(pending)
  437. except StopIteration:
  438. output.put((None, None, None, None))
  439. return
  440. # -E is needed by some tests, e.g. test_import
  441. popen = Popen(base_cmd + ['--slaveargs', json.dumps(args_tuple)],
  442. stdout=PIPE, stderr=PIPE,
  443. universal_newlines=True,
  444. close_fds=(os.name != 'nt'))
  445. stdout, stderr = popen.communicate()
  446. # Strip last refcount output line if it exists, since it
  447. # comes from the shutdown of the interpreter in the subcommand.
  448. stderr = debug_output_pat.sub("", stderr)
  449. stdout, _, result = stdout.strip().rpartition("\n")
  450. if not result:
  451. output.put((None, None, None, None))
  452. return
  453. result = json.loads(result)
  454. if not quiet:
  455. stdout = test+'\n'+stdout
  456. output.put((test, stdout.rstrip(), stderr.rstrip(), result))
  457. except BaseException:
  458. output.put((None, None, None, None))
  459. raise
  460. workers = [Thread(target=work) for i in range(use_mp)]
  461. for worker in workers:
  462. worker.start()
  463. finished = 0
  464. try:
  465. while finished < use_mp:
  466. test, stdout, stderr, result = output.get()
  467. if test is None:
  468. finished += 1
  469. continue
  470. if stdout:
  471. print stdout
  472. if stderr:
  473. print >>sys.stderr, stderr
  474. if result[0] == INTERRUPTED:
  475. assert result[1] == 'KeyboardInterrupt'
  476. raise KeyboardInterrupt # What else?
  477. accumulate_result(test, result)
  478. except KeyboardInterrupt:
  479. interrupted = True
  480. pending.close()
  481. for worker in workers:
  482. worker.join()
  483. else:
  484. for test in tests:
  485. if not quiet:
  486. print test
  487. sys.stdout.flush()
  488. if trace:
  489. # If we're tracing code coverage, then we don't exit with status
  490. # if on a false return value from main.
  491. tracer.runctx('runtest(test, verbose, quiet)',
  492. globals=globals(), locals=vars())
  493. else:
  494. try:
  495. result = runtest(test, verbose, quiet, huntrleaks)
  496. accumulate_result(test, result)
  497. if verbose3 and result[0] == FAILED:
  498. print "Re-running test %r in verbose mode" % test
  499. runtest(test, True, quiet, huntrleaks)
  500. except KeyboardInterrupt:
  501. interrupted = True
  502. break
  503. except:
  504. raise
  505. if findleaks:
  506. gc.collect()
  507. if gc.garbage:
  508. print "Warning: test created", len(gc.garbage),
  509. print "uncollectable object(s)."
  510. # move the uncollectable objects somewhere so we don't see
  511. # them again
  512. found_garbage.extend(gc.garbage)
  513. del gc.garbage[:]
  514. # Unload the newly imported modules (best effort finalization)
  515. for module in sys.modules.keys():
  516. if module not in save_modules and module.startswith("test."):
  517. test_support.unload(module)
  518. if interrupted:
  519. # print a newline after ^C
  520. print
  521. print "Test suite interrupted by signal SIGINT."
  522. omitted = set(selected) - set(good) - set(bad) - set(skipped)
  523. print count(len(omitted), "test"), "omitted:"
  524. printlist(omitted)
  525. if good and not quiet:
  526. if not bad and not skipped and not interrupted and len(good) > 1:
  527. print "All",
  528. print count(len(good), "test"), "OK."
  529. if print_slow:
  530. test_times.sort(reverse=True)
  531. print "10 slowest tests:"
  532. for time, test in test_times[:10]:
  533. print "%s: %.1fs" % (test, time)
  534. if bad:
  535. bad = set(bad) - set(environment_changed)
  536. if bad:
  537. print count(len(bad), "test"), "failed:"
  538. printlist(bad)
  539. if environment_changed:
  540. print "{} altered the execution environment:".format(
  541. count(len(environment_changed), "test"))
  542. printlist(environment_changed)
  543. if skipped and not quiet:
  544. print count(len(skipped), "test"), "skipped:"
  545. printlist(skipped)
  546. e = _ExpectedSkips()
  547. plat = sys.platform
  548. if e.isvalid():
  549. surprise = set(skipped) - e.getexpected() - set(resource_denieds)
  550. if surprise:
  551. print count(len(surprise), "skip"), \
  552. "unexpected on", plat + ":"
  553. printlist(surprise)
  554. else:
  555. print "Those skips are all expected on", plat + "."
  556. else:
  557. print "Ask someone to teach regrtest.py about which tests are"
  558. print "expected to get skipped on", plat + "."
  559. if verbose2 and bad:
  560. print "Re-running failed tests in verbose mode"
  561. for test in bad:
  562. print "Re-running test %r in verbose mode" % test
  563. sys.stdout.flush()
  564. try:
  565. test_support.verbose = True
  566. ok = runtest(test, True, quiet, huntrleaks)
  567. except KeyboardInterrupt:
  568. # print a newline separate from the ^C
  569. print
  570. break
  571. except:
  572. raise
  573. if single:
  574. if next_single_test:
  575. with open(filename, 'w') as fp:
  576. fp.write(next_single_test + '\n')
  577. else:
  578. os.unlink(filename)
  579. if trace:
  580. r = tracer.results()
  581. r.write_results(show_missing=True, summary=True, coverdir=coverdir)
  582. if runleaks:
  583. os.system("leaks %d" % os.getpid())
  584. sys.exit(len(bad) > 0 or interrupted)
  585. STDTESTS = [
  586. 'test_grammar',
  587. 'test_opcodes',
  588. 'test_dict',
  589. 'test_builtin',
  590. 'test_exceptions',
  591. 'test_types',
  592. 'test_unittest',
  593. 'test_doctest',
  594. 'test_doctest2',
  595. ]
  596. NOTTESTS = {
  597. 'test_support',
  598. 'test_future1',
  599. 'test_future2',
  600. }
  601. def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
  602. """Return a list of all applicable test modules."""
  603. testdir = findtestdir(testdir)
  604. names = os.listdir(testdir)
  605. tests = []
  606. others = set(stdtests) | nottests
  607. for name in names:
  608. modname, ext = os.path.splitext(name)
  609. if modname[:5] == "test_" and ext == ".py" and modname not in others:
  610. tests.append(modname)
  611. return stdtests + sorted(tests)
  612. def runtest(test, verbose, quiet,
  613. huntrleaks=False, use_resources=None):
  614. """Run a single test.
  615. test -- the name of the test
  616. verbose -- if true, print more messages
  617. quiet -- if true, don't print 'skipped' messages (probably redundant)
  618. test_times -- a list of (time, test_name) pairs
  619. huntrleaks -- run multiple times to test for leaks; requires a debug
  620. build; a triple corresponding to -R's three arguments
  621. Returns one of the test result constants:
  622. INTERRUPTED KeyboardInterrupt when run under -j
  623. RESOURCE_DENIED test skipped because resource denied
  624. SKIPPED test skipped for some other reason
  625. ENV_CHANGED test failed because it changed the execution environment
  626. FAILED test failed
  627. PASSED test passed
  628. """
  629. test_support.verbose = verbose # Tell tests to be moderately quiet
  630. if use_resources is not None:
  631. test_support.use_resources = use_resources
  632. try:
  633. return runtest_inner(test, verbose, quiet, huntrleaks)
  634. finally:
  635. cleanup_test_droppings(test, verbose)
  636. # Unit tests are supposed to leave the execution environment unchanged
  637. # once they complete. But sometimes tests have bugs, especially when
  638. # tests fail, and the changes to environment go on to mess up other
  639. # tests. This can cause issues with buildbot stability, since tests
  640. # are run in random order and so problems may appear to come and go.
  641. # There are a few things we can save and restore to mitigate this, and
  642. # the following context manager handles this task.
  643. class saved_test_environment:
  644. """Save bits of the test environment and restore them at block exit.
  645. with saved_test_environment(testname, verbose, quiet):
  646. #stuff
  647. Unless quiet is True, a warning is printed to stderr if any of
  648. the saved items was changed by the test. The attribute 'changed'
  649. is initially False, but is set to True if a change is detected.
  650. If verbose is more than 1, the before and after state of changed
  651. items is also printed.
  652. """
  653. changed = False
  654. def __init__(self, testname, verbose=0, quiet=False):
  655. self.testname = testname
  656. self.verbose = verbose
  657. self.quiet = quiet
  658. # To add things to save and restore, add a name XXX to the resources list
  659. # and add corresponding get_XXX/restore_XXX functions. get_XXX should
  660. # return the value to be saved and compared against a second call to the
  661. # get function when test execution completes. restore_XXX should accept
  662. # the saved value and restore the resource using it. It will be called if
  663. # and only if a change in the value is detected.
  664. #
  665. # Note: XXX will have any '.' replaced with '_' characters when determining
  666. # the corresponding method names.
  667. resources = ('sys.argv', 'cwd', 'sys.stdin', 'sys.stdout', 'sys.stderr',
  668. 'os.environ', 'sys.path', 'asyncore.socket_map')
  669. def get_sys_argv(self):
  670. return id(sys.argv), sys.argv, sys.argv[:]
  671. def restore_sys_argv(self, saved_argv):
  672. sys.argv = saved_argv[1]
  673. sys.argv[:] = saved_argv[2]
  674. def get_cwd(self):
  675. return os.getcwd()
  676. def restore_cwd(self, saved_cwd):
  677. os.chdir(saved_cwd)
  678. def get_sys_stdout(self):
  679. return sys.stdout
  680. def restore_sys_stdout(self, saved_stdout):
  681. sys.stdout = saved_stdout
  682. def get_sys_stderr(self):
  683. return sys.stderr
  684. def restore_sys_stderr(self, saved_stderr):
  685. sys.stderr = saved_stderr
  686. def get_sys_stdin(self):
  687. return sys.stdin
  688. def restore_sys_stdin(self, saved_stdin):
  689. sys.stdin = saved_stdin
  690. def get_os_environ(self):
  691. return id(os.environ), os.environ, dict(os.environ)
  692. def restore_os_environ(self, saved_environ):
  693. os.environ = saved_environ[1]
  694. os.environ.clear()
  695. os.environ.update(saved_environ[2])
  696. def get_sys_path(self):
  697. return id(sys.path), sys.path, sys.path[:]
  698. def restore_sys_path(self, saved_path):
  699. sys.path = saved_path[1]
  700. sys.path[:] = saved_path[2]
  701. def get_asyncore_socket_map(self):
  702. asyncore = sys.modules.get('asyncore')
  703. # XXX Making a copy keeps objects alive until __exit__ gets called.
  704. return asyncore and asyncore.socket_map.copy() or {}
  705. def restore_asyncore_socket_map(self, saved_map):
  706. asyncore = sys.modules.get('asyncore')
  707. if asyncore is not None:
  708. asyncore.close_all(ignore_all=True)
  709. asyncore.socket_map.update(saved_map)
  710. def resource_info(self):
  711. for name in self.resources:
  712. method_suffix = name.replace('.', '_')
  713. get_name = 'get_' + method_suffix
  714. restore_name = 'restore_' + method_suffix
  715. yield name, getattr(self, get_name), getattr(self, restore_name)
  716. def __enter__(self):
  717. self.saved_values = dict((name, get()) for name, get, restore
  718. in self.resource_info())
  719. return self
  720. def __exit__(self, exc_type, exc_val, exc_tb):
  721. saved_values = self.saved_values
  722. del self.saved_values
  723. for name, get, restore in self.resource_info():
  724. current = get()
  725. original = saved_values.pop(name)
  726. # Check for changes to the resource's value
  727. if current != original:
  728. self.changed = True
  729. restore(original)
  730. if not self.quiet:
  731. print >>sys.stderr, (
  732. "Warning -- {} was modified by {}".format(
  733. name, self.testname))
  734. if self.verbose > 1:
  735. print >>sys.stderr, (
  736. " Before: {}\n After: {} ".format(
  737. original, current))
  738. # XXX (ncoghlan): for most resources (e.g. sys.path) identity
  739. # matters at least as much as value. For others (e.g. cwd),
  740. # identity is irrelevant. Should we add a mechanism to check
  741. # for substitution in the cases where it matters?
  742. return False
  743. def runtest_inner(test, verbose, quiet, huntrleaks=False):
  744. test_support.unload(test)
  745. if verbose:
  746. capture_stdout = None
  747. else:
  748. capture_stdout = StringIO.StringIO()
  749. test_time = 0.0
  750. refleak = False # True if the test leaked references.
  751. try:
  752. save_stdout = sys.stdout
  753. try:
  754. if capture_stdout:
  755. sys.stdout = capture_stdout
  756. if test.startswith('test.'):
  757. abstest = test
  758. else:
  759. # Always import it from the test package
  760. abstest = 'test.' + test
  761. with saved_test_environment(test, verbose, quiet) as environment:
  762. start_time = time.time()
  763. the_package = __import__(abstest, globals(), locals(), [])
  764. the_module = getattr(the_package, test)
  765. # Old tests run to completion simply as a side-effect of
  766. # being imported. For tests based on unittest or doctest,
  767. # explicitly invoke their test_main() function (if it exists).
  768. indirect_test = getattr(the_module, "test_main", None)
  769. if indirect_test is not None:
  770. indirect_test()
  771. if huntrleaks:
  772. refleak = dash_R(the_module, test, indirect_test,
  773. huntrleaks)
  774. test_time = time.time() - start_time
  775. finally:
  776. sys.stdout = save_stdout
  777. except test_support.ResourceDenied, msg:
  778. if not quiet:
  779. print test, "skipped --", msg
  780. sys.stdout.flush()
  781. return RESOURCE_DENIED, test_time
  782. except unittest.SkipTest, msg:
  783. if not quiet:
  784. print test, "skipped --", msg
  785. sys.stdout.flush()
  786. return SKIPPED, test_time
  787. except KeyboardInterrupt:
  788. raise
  789. except test_support.TestFailed, msg:
  790. print >>sys.stderr, "test", test, "failed --", msg
  791. sys.stderr.flush()
  792. return FAILED, test_time
  793. except:
  794. type, value = sys.exc_info()[:2]
  795. print >>sys.stderr, "test", test, "crashed --", str(type) + ":", value
  796. sys.stderr.flush()
  797. if verbose:
  798. traceback.print_exc(file=sys.stderr)
  799. sys.stderr.flush()
  800. return FAILED, test_time
  801. else:
  802. if refleak:
  803. return FAILED, test_time
  804. if environment.changed:
  805. return ENV_CHANGED, test_time
  806. # Except in verbose mode, tests should not print anything
  807. if verbose or huntrleaks:
  808. return PASSED, test_time
  809. output = capture_stdout.getvalue()
  810. if not output:
  811. return PASSED, test_time
  812. print "test", test, "produced unexpected output:"
  813. print "*" * 70
  814. print output
  815. print "*" * 70
  816. sys.stdout.flush()
  817. return FAILED, test_time
  818. def cleanup_test_droppings(testname, verbose):
  819. import shutil
  820. import stat
  821. import gc
  822. # First kill any dangling references to open files etc.
  823. gc.collect()
  824. # Try to clean up junk commonly left behind. While tests shouldn't leave
  825. # any files or directories behind, when a test fails that can be tedious
  826. # for it to arrange. The consequences can be especially nasty on Windows,
  827. # since if a test leaves a file open, it cannot be deleted by name (while
  828. # there's nothing we can do about that here either, we can display the
  829. # name of the offending test, which is a real help).
  830. for name in (test_support.TESTFN,
  831. "db_home",
  832. ):
  833. if not os.path.exists(name):
  834. continue
  835. if os.path.isdir(name):
  836. kind, nuker = "directory", shutil.rmtree
  837. elif os.path.isfile(name):
  838. kind, nuker = "file", os.unlink
  839. else:
  840. raise SystemError("os.path says %r exists but is neither "
  841. "directory nor file" % name)
  842. if verbose:
  843. print "%r left behind %s %r" % (testname, kind, name)
  844. try:
  845. # if we have chmod, fix possible permissions problems
  846. # that might prevent cleanup
  847. if (hasattr(os, 'chmod')):
  848. os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
  849. nuker(name)
  850. except Exception, msg:
  851. print >> sys.stderr, ("%r left behind %s %r and it couldn't be "
  852. "removed: %s" % (testname, kind, name, msg))
  853. def dash_R(the_module, test, indirect_test, huntrleaks):
  854. """Run a test multiple times, looking for reference leaks.
  855. Returns:
  856. False if the test didn't leak references; True if we detected refleaks.
  857. """
  858. # This code is hackish and inelegant, but it seems to do the job.
  859. import copy_reg, _abcoll, _pyio
  860. if not hasattr(sys, 'gettotalrefcount'):
  861. raise Exception("Tracking reference leaks requires a debug build "
  862. "of Python")
  863. # Save current values for dash_R_cleanup() to restore.
  864. fs = warnings.filters[:]
  865. ps = copy_reg.dispatch_table.copy()
  866. pic = sys.path_importer_cache.copy()
  867. try:
  868. import zipimport
  869. except ImportError:
  870. zdc = None # Run unmodified on platforms without zipimport support
  871. else:
  872. zdc = zipimport._zip_directory_cache.copy()
  873. abcs = {}
  874. modules = _abcoll, _pyio
  875. for abc in [getattr(mod, a) for mod in modules for a in mod.__all__]:
  876. # XXX isinstance(abc, ABCMeta) leads to infinite recursion
  877. if not hasattr(abc, '_abc_registry'):
  878. continue
  879. for obj in abc.__subclasses__() + [abc]:
  880. abcs[obj] = obj._abc_registry.copy()
  881. if indirect_test:
  882. def run_the_test():
  883. indirect_test()
  884. else:
  885. def run_the_test():
  886. imp.reload(the_module)
  887. deltas = []
  888. nwarmup, ntracked, fname = huntrleaks
  889. fname = os.path.join(test_support.SAVEDCWD, fname)
  890. repcount = nwarmup + ntracked
  891. print >> sys.stderr, "beginning", repcount, "repetitions"
  892. print >> sys.stderr, ("1234567890"*(repcount//10 + 1))[:repcount]
  893. dash_R_cleanup(fs, ps, pic, zdc, abcs)
  894. for i in range(repcount):
  895. rc_before = sys.gettotalrefcount()
  896. run_the_test()
  897. sys.stderr.write('.')
  898. dash_R_cleanup(fs, ps, pic, zdc, abcs)
  899. rc_after = sys.gettotalrefcount()
  900. if i >= nwarmup:
  901. deltas.append(rc_after - rc_before)
  902. print >> sys.stderr
  903. if any(deltas):
  904. msg = '%s leaked %s references, sum=%s' % (test, deltas, sum(deltas))
  905. print >> sys.stderr, msg
  906. with open(fname, "a") as refrep:
  907. print >> refrep, msg
  908. refrep.flush()
  909. return True
  910. return False
  911. def dash_R_cleanup(fs, ps, pic, zdc, abcs):
  912. import gc, copy_reg
  913. import _strptime, linecache
  914. dircache = test_support.import_module('dircache', deprecated=True)
  915. import urlparse, urllib, urllib2, mimetypes, doctest
  916. import struct, filecmp
  917. from distutils.dir_util import _path_created
  918. # Clear the warnings registry, so they can be displayed again
  919. for mod in sys.modules.values():
  920. if hasattr(mod, '__warningregistry__'):
  921. del mod.__warningregistry__
  922. # Restore some original values.
  923. warnings.filters[:] = fs
  924. copy_reg.dispatch_table.clear()
  925. copy_reg.dispatch_table.update(ps)
  926. sys.path_importer_cache.clear()
  927. sys.path_importer_cache.update(pic)
  928. try:
  929. import zipimport
  930. except ImportError:
  931. pass # Run unmodified on platforms without zipimport support
  932. else:
  933. zipimport._zip_directory_cache.clear()
  934. zipimport._zip_directory_cache.update(zdc)
  935. # clear type cache
  936. sys._clear_type_cache()
  937. # Clear ABC registries, restoring previously saved ABC registries.
  938. for abc, registry in abcs.items():
  939. abc._abc_registry = registry.copy()
  940. abc._abc_cache.clear()
  941. abc._abc_negative_cache.clear()
  942. # Clear assorted module caches.
  943. _path_created.clear()
  944. re.purge()
  945. _strptime._regex_cache.clear()
  946. urlparse.clear_cache()
  947. urllib.urlcleanup()
  948. urllib2.install_opener(None)
  949. dircache.reset()
  950. linecache.clearcache()
  951. mimetypes._default_mime_types()
  952. filecmp._cache.clear()
  953. struct._clearcache()
  954. doctest.master = None
  955. try:
  956. import ctypes
  957. except ImportError:
  958. # Don't worry about resetting the cache if ctypes is not supported
  959. pass
  960. else:
  961. ctypes._reset_cache()
  962. # Collect cyclic trash.
  963. gc.collect()
  964. def findtestdir(path=None):
  965. return path or os.path.dirname(__file__) or os.curdir
  966. def removepy(names):
  967. if not names:
  968. return
  969. for idx, name in enumerate(names):
  970. basename, ext = os.path.splitext(name)
  971. if ext == '.py':
  972. names[idx] = basename
  973. def count(n, word):
  974. if n == 1:
  975. return "%d %s" % (n, word)
  976. else:
  977. return "%d %ss" % (n, word)
  978. def printlist(x, width=70, indent=4):
  979. """Print the elements of iterable x to stdout.
  980. Optional arg width (default 70) is the maximum line length.
  981. Optional arg indent (default 4) is the number of blanks with which to
  982. begin each line.
  983. """
  984. from textwrap import fill
  985. blanks = ' ' * indent
  986. # Print the sorted list: 'x' may be a '--random' list or a set()
  987. print fill(' '.join(str(elt) for elt in sorted(x)), width,
  988. initial_indent=blanks, subsequent_indent=blanks)
  989. # Map sys.platform to a string containing the basenames of tests
  990. # expected to be skipped on that platform.
  991. #
  992. # Special cases:
  993. # test_pep277
  994. # The _ExpectedSkips constructor adds this to the set of expected
  995. # skips if not os.path.supports_unicode_filenames.
  996. # test_timeout
  997. # Controlled by test_timeout.skip_expected. Requires the network
  998. # resource and a socket module.
  999. #
  1000. # Tests that are expected to be skipped everywhere except on one platform
  1001. # are also handled separately.
  1002. _expectations = {
  1003. 'win32':
  1004. """
  1005. test__locale
  1006. test_bsddb185
  1007. test_bsddb3
  1008. test_commands
  1009. test_crypt
  1010. test_curses
  1011. test_dbm
  1012. test_dl
  1013. test_fcntl
  1014. test_fork1
  1015. test_epoll
  1016. test_gdbm
  1017. test_grp
  1018. test_ioctl
  1019. test_largefile
  1020. test_kqueue
  1021. test_mhlib
  1022. test_openpty
  1023. test_ossaudiodev
  1024. test_pipes
  1025. test_poll
  1026. test_posix
  1027. test_pty
  1028. test_pwd
  1029. test_resource
  1030. test_signal
  1031. test_threadsignals
  1032. test_timing
  1033. test_wait3
  1034. test_wait4
  1035. """,
  1036. 'linux2':
  1037. """
  1038. test_bsddb185
  1039. test_curses
  1040. test_dl
  1041. test_largefile
  1042. test_kqueue
  1043. test_ossaudiodev
  1044. """,
  1045. 'unixware7':
  1046. """
  1047. test_bsddb
  1048. test_bsddb185
  1049. test_dl
  1050. test_epoll
  1051. test_largefile
  1052. test_kqueue
  1053. test_minidom
  1054. test_openpty
  1055. test_pyexpat
  1056. test_sax
  1057. test_sundry
  1058. """,
  1059. 'openunix8':
  1060. """
  1061. test_bsddb
  1062. test_bsddb185
  1063. test_dl
  1064. test_epoll
  1065. test_largefile
  1066. test_kqueue
  1067. test_minidom
  1068. test_openpty
  1069. test_pyexpat
  1070. test_sax
  1071. test_sundry
  1072. """,
  1073. 'sco_sv3':
  1074. """
  1075. test_asynchat
  1076. test_bsddb
  1077. test_bsddb185
  1078. test_dl
  1079. test_fork1
  1080. test_epoll
  1081. test_gettext
  1082. test_largefile
  1083. test_locale
  1084. test_kqueue
  1085. test_minidom
  1086. test_openpty
  1087. test_pyexpat
  1088. test_queue
  1089. test_sax
  1090. test_sundry
  1091. test_thread
  1092. test_threaded_import
  1093. test_threadedtempfile
  1094. test_threading
  1095. """,
  1096. 'riscos':
  1097. """
  1098. test_asynchat
  1099. test_atexit
  1100. test_bsddb
  1101. test_bsddb185
  1102. test_bsddb3
  1103. test_commands
  1104. test_crypt
  1105. test_dbm
  1106. test_dl
  1107. test_fcntl
  1108. test_fork1
  1109. test_epoll
  1110. test_gdbm
  1111. test_grp
  1112. test_largefile
  1113. test_locale
  1114. test_kqueue
  1115. test_mmap
  1116. test_openpty
  1117. test_poll
  1118. test_popen2
  1119. test_pty
  1120. test_pwd
  1121. test_strop
  1122. test_sundry
  1123. test_thread
  1124. test_threaded_import
  1125. test_threadedtempfile
  1126. test_threading
  1127. test_timing
  1128. """,
  1129. 'darwin':
  1130. """
  1131. test__locale
  1132. test_bsddb
  1133. test_bsddb3
  1134. test_curses
  1135. test_epoll
  1136. test_gdb
  1137. test_gdbm
  1138. test_largefile
  1139. test_locale
  1140. test_kqueue
  1141. test_minidom
  1142. test_ossaudiodev
  1143. test_poll
  1144. """,
  1145. 'sunos5':
  1146. """
  1147. test_bsddb
  1148. test_bsddb185
  1149. test_curses
  1150. test_dbm
  1151. test_epoll
  1152. test_kqueue
  1153. test_gdbm
  1154. test_gzip
  1155. test_openpty
  1156. test_zipfile
  1157. test_zlib
  1158. """,
  1159. 'hp-ux11':
  1160. """
  1161. test_bsddb
  1162. test_bsddb185
  1163. test_curses
  1164. test_dl
  1165. test_epoll
  1166. test_gdbm
  1167. test_gzip
  1168. test_largefile
  1169. test_locale
  1170. test_kqueue
  1171. test_minidom
  1172. test_openpty
  1173. test_pyexpat
  1174. test_sax
  1175. test_zipfile
  1176. test_zlib
  1177. """,
  1178. 'atheos':
  1179. """
  1180. test_bsddb185
  1181. test_curses
  1182. test_dl
  1183. test_gdbm
  1184. test_epoll
  1185. test_largefile
  1186. test_locale
  1187. test_kqueue
  1188. test_mhlib
  1189. test_mmap
  1190. test_poll
  1191. test_popen2
  1192. test_resource
  1193. """,
  1194. 'cygwin':
  1195. """
  1196. test_bsddb185
  1197. test_bsddb3
  1198. test_curses
  1199. test_dbm
  1200. test_epoll
  1201. test_ioctl
  1202. test_kqueue
  1203. test_largefile
  1204. test_locale
  1205. test_ossaudiodev
  1206. test_socketserver
  1207. """,
  1208. 'os2emx':
  1209. """
  1210. test_audioop
  1211. test_bsddb185
  1212. test_bsddb3
  1213. test_commands
  1214. test_curses
  1215. test_dl
  1216. test_epoll
  1217. test_kqueue
  1218. test_largefile
  1219. test_mhlib
  1220. test_mmap
  1221. test_openpty
  1222. test_ossaudiodev
  1223. test_pty
  1224. test_resource
  1225. test_signal
  1226. """,
  1227. 'freebsd4':
  1228. """
  1229. test_bsddb
  1230. test_bsddb3
  1231. test_epoll
  1232. test_gdbm
  1233. test_locale
  1234. test_ossaudiodev
  1235. test_pep277
  1236. test_pty
  1237. test_socketserver
  1238. test_tcl
  1239. test_tk
  1240. test_ttk_guionly
  1241. test_ttk_textonly
  1242. test_timeout
  1243. test_urllibnet
  1244. test_multiprocessing
  1245. """,
  1246. 'aix5':
  1247. """
  1248. test_bsddb
  1249. test_bsddb185
  1250. test_bsddb3
  1251. test_bz2
  1252. test_dl
  1253. test_epoll
  1254. test_gdbm
  1255. test_gzip
  1256. test_kqueue
  1257. test_ossaudiodev
  1258. test_tcl
  1259. test_tk
  1260. test_ttk_guionly
  1261. test_ttk_textonly
  1262. test_zipimport
  1263. test_zlib
  1264. """,
  1265. 'openbsd4':
  1266. """
  1267. test_ascii_formatd
  1268. test_bsddb
  1269. test_bsddb3
  1270. test_ctypes
  1271. test_dl
  1272. test_epoll
  1273. test_gdbm
  1274. test_locale
  1275. test_normalization
  1276. test_ossaudiodev
  1277. test_pep277
  1278. test_tcl
  1279. test_tk
  1280. test_ttk_guionly
  1281. test_ttk_textonly
  1282. test_multiprocessing
  1283. """,
  1284. 'openbsd5':
  1285. """
  1286. test_ascii_formatd
  1287. test_bsddb
  1288. test_bsddb3
  1289. test_ctypes
  1290. test_dl
  1291. test_epoll
  1292. test_gdbm
  1293. test_locale
  1294. test_normalization
  1295. test_ossaudiodev
  1296. test_pep277
  1297. test_tcl
  1298. test_tk
  1299. test_ttk_guionly
  1300. test_ttk_textonly
  1301. test_multiprocessing
  1302. """,
  1303. 'netbsd3':
  1304. """
  1305. test_ascii_formatd
  1306. test_bsddb
  1307. test_bsddb185
  1308. test_bsddb3
  1309. test_ctypes
  1310. test_curses
  1311. test_dl
  1312. test_epoll
  1313. test_gdbm
  1314. test_locale
  1315. test_ossaudiodev
  1316. test_pep277
  1317. test_tcl
  1318. test_tk
  1319. test_ttk_guionly
  1320. test_ttk_textonly
  1321. test_multiprocessing
  1322. """,
  1323. }
  1324. _expectations['freebsd5'] = _expectations['freebsd4']
  1325. _expectations['freebsd6'] = _expectations['freebsd4']
  1326. _expectations['freebsd7'] = _expectations['freebsd4']
  1327. _expectations['freebsd8'] = _expectations['freebsd4']
  1328. class _ExpectedSkips:
  1329. def __init__(self):
  1330. import os.path
  1331. from test import test_timeout
  1332. self.valid = False
  1333. if sys.platform in _expectations:
  1334. s = _expectations[sys.platform]
  1335. self.expected = set(s.split())
  1336. # expected to be skipped on every platform, even Linux
  1337. self.expected.add('test_linuxaudiodev')
  1338. if not os.path.supports_unicode_filenames:
  1339. self.expected.add('test_pep277')
  1340. if test_timeout.skip_expected:
  1341. self.expected.add('test_timeout')
  1342. if sys.maxint == 9223372036854775807L:
  1343. self.expected.add('test_imageop')
  1344. if sys.platform != "darwin":
  1345. MAC_ONLY = ["test_macos", "test_macostools", "test_aepack",
  1346. "test_plistlib", "test_scriptpackages",
  1347. "test_applesingle"]
  1348. for skip in MAC_ONLY:
  1349. self.expected.add(skip)
  1350. elif len(u'\0'.encode('unicode-internal')) == 4:
  1351. self.expected.add("test_macostools")
  1352. if sys.platform != "win32":
  1353. # test_sqlite is only reliable on Windows where the library
  1354. # is distributed with Python
  1355. WIN_ONLY = ["test_unicode_file", "test_winreg",
  1356. "test_winsound", "test_startfile",
  1357. "test_sqlite", "test_msilib"]
  1358. for skip in WIN_ONLY:

Large files files are truncated, but you can click here to view the full file