regrtest.py 54 KB

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