PageRenderTime 59ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/varialus/jyjy
Python | 1549 lines | 1518 code | 9 blank | 22 comment | 40 complexity | 52ab95977cf0d8a4d3653ec27dda9569 MD5 | raw file

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. # Collect cyclic trash.
  956. gc.collect()
  957. def findtestdir(path=None):
  958. return path or os.path.dirname(__file__) or os.curdir
  959. def removepy(names):
  960. if not names:
  961. return
  962. for idx, name in enumerate(names):
  963. basename, ext = os.path.splitext(name)
  964. if ext == '.py':
  965. names[idx] = basename
  966. def count(n, word):
  967. if n == 1:
  968. return "%d %s" % (n, word)
  969. else:
  970. return "%d %ss" % (n, word)
  971. def printlist(x, width=70, indent=4):
  972. """Print the elements of iterable x to stdout.
  973. Optional arg width (default 70) is the maximum line length.
  974. Optional arg indent (default 4) is the number of blanks with which to
  975. begin each line.
  976. """
  977. from textwrap import fill
  978. blanks = ' ' * indent
  979. # Print the sorted list: 'x' may be a '--random' list or a set()
  980. print fill(' '.join(str(elt) for elt in sorted(x)), width,
  981. initial_indent=blanks, subsequent_indent=blanks)
  982. # Map sys.platform to a string containing the basenames of tests
  983. # expected to be skipped on that platform.
  984. #
  985. # Special cases:
  986. # test_pep277
  987. # The _ExpectedSkips constructor adds this to the set of expected
  988. # skips if not os.path.supports_unicode_filenames.
  989. # test_timeout
  990. # Controlled by test_timeout.skip_expected. Requires the network
  991. # resource and a socket module.
  992. #
  993. # Tests that are expected to be skipped everywhere except on one platform
  994. # are also handled separately.
  995. _expectations = {
  996. 'win32':
  997. """
  998. test__locale
  999. test_bsddb185
  1000. test_bsddb3
  1001. test_commands
  1002. test_crypt
  1003. test_curses
  1004. test_dbm
  1005. test_dl
  1006. test_fcntl
  1007. test_fork1
  1008. test_epoll
  1009. test_gdbm
  1010. test_grp
  1011. test_ioctl
  1012. test_largefile
  1013. test_kqueue
  1014. test_mhlib
  1015. test_openpty
  1016. test_ossaudiodev
  1017. test_pipes
  1018. test_poll
  1019. test_posix
  1020. test_pty
  1021. test_pwd
  1022. test_resource
  1023. test_signal
  1024. test_threadsignals
  1025. test_timing
  1026. test_wait3
  1027. test_wait4
  1028. """,
  1029. 'linux2':
  1030. """
  1031. test_bsddb185
  1032. test_curses
  1033. test_dl
  1034. test_largefile
  1035. test_kqueue
  1036. test_ossaudiodev
  1037. """,
  1038. 'unixware7':
  1039. """
  1040. test_bsddb
  1041. test_bsddb185
  1042. test_dl
  1043. test_epoll
  1044. test_largefile
  1045. test_kqueue
  1046. test_minidom
  1047. test_openpty
  1048. test_pyexpat
  1049. test_sax
  1050. test_sundry
  1051. """,
  1052. 'openunix8':
  1053. """
  1054. test_bsddb
  1055. test_bsddb185
  1056. test_dl
  1057. test_epoll
  1058. test_largefile
  1059. test_kqueue
  1060. test_minidom
  1061. test_openpty
  1062. test_pyexpat
  1063. test_sax
  1064. test_sundry
  1065. """,
  1066. 'sco_sv3':
  1067. """
  1068. test_asynchat
  1069. test_bsddb
  1070. test_bsddb185
  1071. test_dl
  1072. test_fork1
  1073. test_epoll
  1074. test_gettext
  1075. test_largefile
  1076. test_locale
  1077. test_kqueue
  1078. test_minidom
  1079. test_openpty
  1080. test_pyexpat
  1081. test_queue
  1082. test_sax
  1083. test_sundry
  1084. test_thread
  1085. test_threaded_import
  1086. test_threadedtempfile
  1087. test_threading
  1088. """,
  1089. 'riscos':
  1090. """
  1091. test_asynchat
  1092. test_atexit
  1093. test_bsddb
  1094. test_bsddb185
  1095. test_bsddb3
  1096. test_commands
  1097. test_crypt
  1098. test_dbm
  1099. test_dl
  1100. test_fcntl
  1101. test_fork1
  1102. test_epoll
  1103. test_gdbm
  1104. test_grp
  1105. test_largefile
  1106. test_locale
  1107. test_kqueue
  1108. test_mmap
  1109. test_openpty
  1110. test_poll
  1111. test_popen2
  1112. test_pty
  1113. test_pwd
  1114. test_strop
  1115. test_sundry
  1116. test_thread
  1117. test_threaded_import
  1118. test_threadedtempfile
  1119. test_threading
  1120. test_timing
  1121. """,
  1122. 'darwin':
  1123. """
  1124. test__locale
  1125. test_bsddb
  1126. test_bsddb3
  1127. test_curses
  1128. test_epoll
  1129. test_gdb
  1130. test_gdbm
  1131. test_largefile
  1132. test_locale
  1133. test_kqueue
  1134. test_minidom
  1135. test_ossaudiodev
  1136. test_poll
  1137. """,
  1138. 'sunos5':
  1139. """
  1140. test_bsddb
  1141. test_bsddb185
  1142. test_curses
  1143. test_dbm
  1144. test_epoll
  1145. test_kqueue
  1146. test_gdbm
  1147. test_gzip
  1148. test_openpty
  1149. test_zipfile
  1150. test_zlib
  1151. """,
  1152. 'hp-ux11':
  1153. """
  1154. test_bsddb
  1155. test_bsddb185
  1156. test_curses
  1157. test_dl
  1158. test_epoll
  1159. test_gdbm
  1160. test_gzip
  1161. test_largefile
  1162. test_locale
  1163. test_kqueue
  1164. test_minidom
  1165. test_openpty
  1166. test_pyexpat
  1167. test_sax
  1168. test_zipfile
  1169. test_zlib
  1170. """,
  1171. 'atheos':
  1172. """
  1173. test_bsddb185
  1174. test_curses
  1175. test_dl
  1176. test_gdbm
  1177. test_epoll
  1178. test_largefile
  1179. test_locale
  1180. test_kqueue
  1181. test_mhlib
  1182. test_mmap
  1183. test_poll
  1184. test_popen2
  1185. test_resource
  1186. """,
  1187. 'cygwin':
  1188. """
  1189. test_bsddb185
  1190. test_bsddb3
  1191. test_curses
  1192. test_dbm
  1193. test_epoll
  1194. test_ioctl
  1195. test_kqueue
  1196. test_largefile
  1197. test_locale
  1198. test_ossaudiodev
  1199. test_socketserver
  1200. """,
  1201. 'os2emx':
  1202. """
  1203. test_audioop
  1204. test_bsddb185
  1205. test_bsddb3
  1206. test_commands
  1207. test_curses
  1208. test_dl
  1209. test_epoll
  1210. test_kqueue
  1211. test_largefile
  1212. test_mhlib
  1213. test_mmap
  1214. test_openpty
  1215. test_ossaudiodev
  1216. test_pty
  1217. test_resource
  1218. test_signal
  1219. """,
  1220. 'freebsd4':
  1221. """
  1222. test_bsddb
  1223. test_bsddb3
  1224. test_epoll
  1225. test_gdbm
  1226. test_locale
  1227. test_ossaudiodev
  1228. test_pep277
  1229. test_pty
  1230. test_socketserver
  1231. test_tcl
  1232. test_tk
  1233. test_ttk_guionly
  1234. test_ttk_textonly
  1235. test_timeout
  1236. test_urllibnet
  1237. test_multiprocessing
  1238. """,
  1239. 'aix5':
  1240. """
  1241. test_bsddb
  1242. test_bsddb185
  1243. test_bsddb3
  1244. test_bz2
  1245. test_dl
  1246. test_epoll
  1247. test_gdbm
  1248. test_gzip
  1249. test_kqueue
  1250. test_ossaudiodev
  1251. test_tcl
  1252. test_tk
  1253. test_ttk_guionly
  1254. test_ttk_textonly
  1255. test_zipimport
  1256. test_zlib
  1257. """,
  1258. 'openbsd4':
  1259. """
  1260. test_ascii_formatd
  1261. test_bsddb
  1262. test_bsddb3
  1263. test_ctypes
  1264. test_dl
  1265. test_epoll
  1266. test_gdbm
  1267. test_locale
  1268. test_normalization
  1269. test_ossaudiodev
  1270. test_pep277
  1271. test_tcl
  1272. test_tk
  1273. test_ttk_guionly
  1274. test_ttk_textonly
  1275. test_multiprocessing
  1276. """,
  1277. 'openbsd5':
  1278. """
  1279. test_ascii_formatd
  1280. test_bsddb
  1281. test_bsddb3
  1282. test_ctypes
  1283. test_dl
  1284. test_epoll
  1285. test_gdbm
  1286. test_locale
  1287. test_normalization
  1288. test_ossaudiodev
  1289. test_pep277
  1290. test_tcl
  1291. test_tk
  1292. test_ttk_guionly
  1293. test_ttk_textonly
  1294. test_multiprocessing
  1295. """,
  1296. 'netbsd3':
  1297. """
  1298. test_ascii_formatd
  1299. test_bsddb
  1300. test_bsddb185
  1301. test_bsddb3
  1302. test_ctypes
  1303. test_curses
  1304. test_dl
  1305. test_epoll
  1306. test_gdbm
  1307. test_locale
  1308. test_ossaudiodev
  1309. test_pep277
  1310. test_tcl
  1311. test_tk
  1312. test_ttk_guionly
  1313. test_ttk_textonly
  1314. test_multiprocessing
  1315. """,
  1316. }
  1317. _expectations['freebsd5'] = _expectations['freebsd4']
  1318. _expectations['freebsd6'] = _expectations['freebsd4']
  1319. _expectations['freebsd7'] = _expectations['freebsd4']
  1320. _expectations['freebsd8'] = _expectations['freebsd4']
  1321. class _ExpectedSkips:
  1322. def __init__(self):
  1323. import os.path
  1324. from test import test_timeout
  1325. self.valid = False
  1326. if sys.platform in _expectations:
  1327. s = _expectations[sys.platform]
  1328. self.expected = set(s.split())
  1329. # expected to be skipped on every platform, even Linux
  1330. self.expected.add('test_linuxaudiodev')
  1331. if not os.path.supports_unicode_filenames:
  1332. self.expected.add('test_pep277')
  1333. if test_timeout.skip_expected:
  1334. self.expected.add('test_timeout')
  1335. if sys.maxint == 9223372036854775807L:
  1336. self.expected.add('test_imageop')
  1337. if sys.platform != "darwin":
  1338. MAC_ONLY = ["test_macos", "test_macostools", "test_aepack",
  1339. "test_plistlib", "test_scriptpackages",
  1340. "test_applesingle"]
  1341. for skip in MAC_ONLY:
  1342. self.expected.add(skip)
  1343. elif len(u'\0'.encode('unicode-internal')) == 4:
  1344. self.expected.add("test_macostools")
  1345. if sys.platform != "win32":
  1346. # test_sqlite is only reliable on Windows where the library
  1347. # is distributed with Python
  1348. WIN_ONLY = ["test_unicode_file", "test_winreg",
  1349. "test_winsound", "test_startfile",
  1350. "test_sqlite", "test_msilib"]
  1351. for skip in WIN_ONLY:
  1352. self.expected.add(skip)
  1353. if sys.platform != 'irix':
  1354. IRIX_ONLY = ["test_imageop", "test_al", "test_cd", "test_cl",

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