blob: b49e66be3768e1279f38e33c04b0cf7e7f7634b0 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Guido van Rossum152494a1996-12-20 03:12:20 +00002
R. David Murray0ba81e02010-04-26 17:02:32 +00003"""
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -08004Script to run Python regression tests.
Guido van Rossum152494a1996-12-20 03:12:20 +00005
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -08006Run this script with -h or --help for documentation.
7"""
8
Victor Stinner0cca00b2015-09-23 23:16:47 +02009USAGE = """\
10python -m test [options] [test_name1 [test_name2 ...]]
11python path/to/Lib/test/regrtest.py [options] [test_name1 [test_name2 ...]]
12"""
13
14DESCRIPTION = """\
15Run Python regression tests.
16
17If no arguments or options are provided, finds all files matching
18the pattern "test_*" in the Lib/test subdirectory and runs
19them in alphabetical order (but see -M and -u, below, for exceptions).
20
21For more rigorous testing, it is useful to use the following
22command line:
23
24python -E -Wd -m test [options] [test_name1 ...]
25"""
26
27EPILOG = """\
28Additional option details:
29
30-r randomizes test execution order. You can use --randseed=int to provide a
31int seed value for the randomizer; this is useful for reproducing troublesome
32test orders.
33
34-s On the first invocation of regrtest using -s, the first test file found
35or the first test file given on the command line is run, and the name of
36the next test is recorded in a file named pynexttest. If run from the
37Python build directory, pynexttest is located in the 'build' subdirectory,
38otherwise it is located in tempfile.gettempdir(). On subsequent runs,
39the test in pynexttest is run, and the next test is written to pynexttest.
40When the last test has been run, pynexttest is deleted. In this way it
41is possible to single step through the test files. This is useful when
42doing memory analysis on the Python interpreter, which process tends to
43consume too many resources to run the full regression test non-stop.
44
45-S is used to continue running tests after an aborted run. It will
46maintain the order a standard run (ie, this assumes -r is not used).
47This is useful after the tests have prematurely stopped for some external
48reason and you want to start running from where you left off rather
49than starting from the beginning.
50
51-f reads the names of tests from the file given as f's argument, one
52or more test names per line. Whitespace is ignored. Blank lines and
53lines beginning with '#' are ignored. This is especially useful for
54whittling down failures involving interactions among tests.
55
56-L causes the leaks(1) command to be run just before exit if it exists.
57leaks(1) is available on Mac OS X and presumably on some other
58FreeBSD-derived systems.
59
60-R runs each test several times and examines sys.gettotalrefcount() to
61see if the test appears to be leaking references. The argument should
62be of the form stab:run:fname where 'stab' is the number of times the
63test is run to let gettotalrefcount settle down, 'run' is the number
64of times further it is run and 'fname' is the name of the file the
65reports are written to. These parameters all have defaults (5, 4 and
66"reflog.txt" respectively), and the minimal invocation is '-R :'.
67
68-M runs tests that require an exorbitant amount of memory. These tests
69typically try to ascertain containers keep working when containing more than
702 billion objects, which only works on 64-bit systems. There are also some
71tests that try to exhaust the address space of the process, which only makes
72sense on 32-bit systems with at least 2Gb of memory. The passed-in memlimit,
73which is a string in the form of '2.5Gb', determines howmuch memory the
74tests will limit themselves to (but they may go slightly over.) The number
75shouldn't be more memory than the machine has (including swap memory). You
76should also keep in mind that swap memory is generally much, much slower
77than RAM, and setting memlimit to all available RAM or higher will heavily
78tax the machine. On the other hand, it is no use running these tests with a
79limit of less than 2.5Gb, and many require more than 20Gb. Tests that expect
80to use more than memlimit memory will be skipped. The big-memory tests
81generally run very, very long.
82
83-u is used to specify which special resource intensive tests to run,
84such as those requiring large file support or network connectivity.
85The argument is a comma-separated list of words indicating the
86resources to test. Currently only the following are defined:
87
88 all - Enable all special resources.
89
90 none - Disable all special resources (this is the default).
91
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
96 curses - Tests that use curses and will modify the terminal's
97 state and output modes.
98
99 largefile - It is okay to run some test that may create huge
100 files. These tests can take a long time and may
101 consume >2GB of disk space temporarily.
102
103 network - It is okay to run tests that use external network
104 resource, e.g. testing SSL support for sockets.
105
106 decimal - Test the decimal module against a large suite that
107 verifies compliance with standards.
108
109 cpu - Used for certain CPU-heavy tests.
110
111 subprocess Run all tests for the subprocess module.
112
113 urlfetch - It is okay to download files required on testing.
114
115 gui - Run tests that require a running GUI.
116
117To enable all resources except one, use '-uall,-<resource>'. For
118example, to run all the tests except for the gui tests, give the
119option '-uall,-gui'.
120"""
121
Nick Coghlanbe7e49f2012-07-20 23:40:09 +1000122# We import importlib *ASAP* in order to test #15386
123import importlib
124
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -0800125import argparse
Brett Cannon45071902010-06-14 22:22:54 +0000126import builtins
Victor Stinner024e37a2011-03-31 01:31:06 +0200127import faulthandler
Victor Stinner8313d6a2011-06-29 15:22:26 +0200128import io
Antoine Pitrou88909542009-06-29 13:54:42 +0000129import json
Brett Cannon49e835b2013-04-01 14:11:37 -0400130import locale
Victor Stinner8313d6a2011-06-29 15:22:26 +0200131import logging
Christian Heimesb186d002008-03-18 15:15:01 +0000132import os
Victor Stinner8313d6a2011-06-29 15:22:26 +0200133import platform
Skip Montanaroab1c7912000-06-30 16:39:27 +0000134import random
Thomas Wouters9ada3d62006-04-21 09:47:09 +0000135import re
Éric Araujoff913062011-11-29 16:45:07 +0100136import shutil
Victor Stinnercb41cda2011-07-13 23:47:21 +0200137import signal
Christian Heimesb186d002008-03-18 15:15:01 +0000138import sys
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000139import sysconfig
Victor Stinner8313d6a2011-06-29 15:22:26 +0200140import tempfile
141import time
142import traceback
143import unittest
144import warnings
145from inspect import isabstract
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000146
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200147try:
148 import threading
Brett Cannon260fbe82013-07-04 18:16:15 -0400149except ImportError:
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200150 threading = None
151try:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +0100152 import _multiprocessing, multiprocessing.process
Brett Cannon260fbe82013-07-04 18:16:15 -0400153except ImportError:
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200154 multiprocessing = None
155
Florent Xicluna64fb18e2010-03-06 14:43:34 +0000156
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000157# Some times __path__ and __file__ are not absolute (e.g. while running from
158# Lib/) and, if we change the CWD to run the tests in a temporary dir, some
159# imports might fail. This affects only the modules imported before os.chdir().
160# These modules are searched first in sys.path[0] (so '' -- the CWD) and if
161# they are found in the CWD their __file__ and __path__ will be relative (this
162# happens before the chdir). All the modules imported after the chdir, are
163# not found in the CWD, and since the other paths in sys.path[1:] are absolute
164# (site.py absolutize them), the __file__ and __path__ will be absolute too.
165# Therefore it is necessary to absolutize manually the __file__ and __path__ of
166# the packages to prevent later imports to fail when the CWD is different.
167for module in sys.modules.values():
168 if hasattr(module, '__path__'):
169 module.__path__ = [os.path.abspath(path) for path in module.__path__]
170 if hasattr(module, '__file__'):
171 module.__file__ = os.path.abspath(module.__file__)
172
Guido van Rossumdc15c272002-08-12 21:55:51 +0000173
Guido van Rossumbb484652002-12-02 09:56:21 +0000174# MacOSX (a.k.a. Darwin) has a default stack size that is too small
175# for deeply recursive regular expressions. We see this as crashes in
176# the Python test suite when running test_re.py and test_sre.py. The
177# fix is to set the stack limit to 2048.
178# This approach may also be useful for other Unixy platforms that
179# suffer from small default stack limits.
180if sys.platform == 'darwin':
181 try:
182 import resource
Brett Cannon260fbe82013-07-04 18:16:15 -0400183 except ImportError:
Guido van Rossumbb484652002-12-02 09:56:21 +0000184 pass
185 else:
186 soft, hard = resource.getrlimit(resource.RLIMIT_STACK)
187 newsoft = min(hard, max(soft, 1024*2048))
188 resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
189
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000190# Test result constants.
191PASSED = 1
192FAILED = 0
193ENV_CHANGED = -1
194SKIPPED = -2
195RESOURCE_DENIED = -3
196INTERRUPTED = -4
Victor Stinner4b739882011-03-31 18:02:36 +0200197CHILD_ERROR = -5 # error in a child process
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000198
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000199from test import support
Fred Drake3a15dac2002-04-11 16:39:16 +0000200
Victor Stinner0cca00b2015-09-23 23:16:47 +0200201RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network',
202 'decimal', 'cpu', 'subprocess', 'urlfetch', 'gui')
203
Chris Jerdonek517e9252013-02-27 09:02:53 -0800204# When tests are run from the Python build directory, it is best practice
205# to keep the test files in a subfolder. This eases the cleanup of leftover
206# files using the "make distclean" command.
207if sysconfig.is_python_build():
208 TEMPDIR = os.path.join(sysconfig.get_config_var('srcdir'), 'build')
209else:
210 TEMPDIR = tempfile.gettempdir()
211TEMPDIR = os.path.abspath(TEMPDIR)
Fred Drake3a15dac2002-04-11 16:39:16 +0000212
Victor Stinner0cca00b2015-09-23 23:16:47 +0200213class _ArgParser(argparse.ArgumentParser):
214
215 def error(self, message):
216 super().error(message + "\nPass -h or --help for complete help.")
217
218def _create_parser():
219 # Set prog to prevent the uninformative "__main__.py" from displaying in
220 # error messages when using "python -m test ...".
221 parser = _ArgParser(prog='regrtest.py',
222 usage=USAGE,
223 description=DESCRIPTION,
224 epilog=EPILOG,
225 add_help=False,
226 formatter_class=argparse.RawDescriptionHelpFormatter)
227
228 # Arguments with this clause added to its help are described further in
229 # the epilog's "Additional option details" section.
230 more_details = ' See the section at bottom for more details.'
231
232 group = parser.add_argument_group('General options')
233 # We add help explicitly to control what argument group it renders under.
234 group.add_argument('-h', '--help', action='help',
235 help='show this help message and exit')
236 group.add_argument('--timeout', metavar='TIMEOUT', type=float,
237 help='dump the traceback and exit if a test takes '
238 'more than TIMEOUT seconds; disabled if TIMEOUT '
239 'is negative or equals to zero')
240 group.add_argument('--wait', action='store_true',
241 help='wait for user input, e.g., allow a debugger '
242 'to be attached')
243 group.add_argument('--slaveargs', metavar='ARGS')
244 group.add_argument('-S', '--start', metavar='START',
245 help='the name of the test at which to start.' +
246 more_details)
247
248 group = parser.add_argument_group('Verbosity')
249 group.add_argument('-v', '--verbose', action='count',
250 help='run tests in verbose mode with output to stdout')
251 group.add_argument('-w', '--verbose2', action='store_true',
252 help='re-run failed tests in verbose mode')
253 group.add_argument('-W', '--verbose3', action='store_true',
254 help='display test output on failure')
255 group.add_argument('-q', '--quiet', action='store_true',
256 help='no output unless one or more tests fail')
257 group.add_argument('-o', '--slow', action='store_true', dest='print_slow',
258 help='print the slowest 10 tests')
259 group.add_argument('--header', action='store_true',
260 help='print header with interpreter info')
261
262 group = parser.add_argument_group('Selecting tests')
263 group.add_argument('-r', '--randomize', action='store_true',
264 help='randomize test execution order.' + more_details)
265 group.add_argument('--randseed', metavar='SEED',
266 dest='random_seed', type=int,
267 help='pass a random seed to reproduce a previous '
268 'random run')
269 group.add_argument('-f', '--fromfile', metavar='FILE',
270 help='read names of tests to run from a file.' +
271 more_details)
272 group.add_argument('-x', '--exclude', action='store_true',
273 help='arguments are tests to *exclude*')
274 group.add_argument('-s', '--single', action='store_true',
275 help='single step through a set of tests.' +
276 more_details)
277 group.add_argument('-m', '--match', metavar='PAT',
278 dest='match_tests',
279 help='match test cases and methods with glob pattern PAT')
280 group.add_argument('-G', '--failfast', action='store_true',
281 help='fail as soon as a test fails (only with -v or -W)')
282 group.add_argument('-u', '--use', metavar='RES1,RES2,...',
283 action='append', type=resources_list,
284 help='specify which special resource intensive tests '
285 'to run.' + more_details)
286 group.add_argument('-M', '--memlimit', metavar='LIMIT',
287 help='run very large memory-consuming tests.' +
288 more_details)
289 group.add_argument('--testdir', metavar='DIR',
290 type=relative_filename,
291 help='execute test files in the specified directory '
292 '(instead of the Python stdlib test suite)')
293
294 group = parser.add_argument_group('Special runs')
295 group.add_argument('-l', '--findleaks', action='store_true',
296 help='if GC is available detect tests that leak memory')
297 group.add_argument('-L', '--runleaks', action='store_true',
298 help='run the leaks(1) command just before exit.' +
299 more_details)
300 group.add_argument('-R', '--huntrleaks', metavar='RUNCOUNTS',
301 type=huntrleaks,
302 help='search for reference leaks (needs debug build, '
303 'very slow).' + more_details)
304 group.add_argument('-j', '--multiprocess', metavar='PROCESSES',
305 dest='use_mp', type=int,
306 help='run PROCESSES processes at once')
307 group.add_argument('-T', '--coverage', action='store_true',
308 dest='trace',
309 help='turn on code coverage tracing using the trace '
310 'module')
311 group.add_argument('-D', '--coverdir', metavar='DIR',
312 type=relative_filename,
313 help='directory where coverage files are put')
314 group.add_argument('-N', '--nocoverdir',
315 action='store_const', const=None, dest='coverdir',
316 help='put coverage files alongside modules')
317 group.add_argument('-t', '--threshold', metavar='THRESHOLD',
318 type=int,
319 help='call gc.set_threshold(THRESHOLD)')
320 group.add_argument('-n', '--nowindows', action='store_true',
321 help='suppress error message boxes on Windows')
322 group.add_argument('-F', '--forever', action='store_true',
323 help='run the specified tests in a loop, until an '
324 'error happens')
325
326 parser.add_argument('args', nargs=argparse.REMAINDER,
327 help=argparse.SUPPRESS)
328
329 return parser
330
331def relative_filename(string):
332 # CWD is replaced with a temporary dir before calling main(), so we
333 # join it with the saved CWD so it ends up where the user expects.
334 return os.path.join(support.SAVEDCWD, string)
335
336def huntrleaks(string):
337 args = string.split(':')
338 if len(args) not in (2, 3):
339 raise argparse.ArgumentTypeError(
340 'needs 2 or 3 colon-separated arguments')
341 nwarmup = int(args[0]) if args[0] else 5
342 ntracked = int(args[1]) if args[1] else 4
343 fname = args[2] if len(args) > 2 and args[2] else 'reflog.txt'
344 return nwarmup, ntracked, fname
345
346def resources_list(string):
347 u = [x.lower() for x in string.split(',')]
348 for r in u:
349 if r == 'all' or r == 'none':
350 continue
351 if r[0] == '-':
352 r = r[1:]
353 if r not in RESOURCE_NAMES:
354 raise argparse.ArgumentTypeError('invalid resource: ' + r)
355 return u
356
357def _parse_args(args, **kwargs):
358 # Defaults
359 ns = argparse.Namespace(testdir=None, verbose=0, quiet=False,
360 exclude=False, single=False, randomize=False, fromfile=None,
361 findleaks=False, use_resources=None, trace=False, coverdir='coverage',
362 runleaks=False, huntrleaks=False, verbose2=False, print_slow=False,
363 random_seed=None, use_mp=None, verbose3=False, forever=False,
364 header=False, failfast=False, match_tests=None)
365 for k, v in kwargs.items():
366 if not hasattr(ns, k):
367 raise TypeError('%r is an invalid keyword argument '
368 'for this function' % k)
369 setattr(ns, k, v)
370 if ns.use_resources is None:
371 ns.use_resources = []
372
373 parser = _create_parser()
374 parser.parse_args(args=args, namespace=ns)
375
376 if ns.single and ns.fromfile:
377 parser.error("-s and -f don't go together!")
378 if ns.use_mp and ns.trace:
379 parser.error("-T and -j don't go together!")
380 if ns.use_mp and ns.findleaks:
381 parser.error("-l and -j don't go together!")
382 if ns.use_mp and ns.memlimit:
383 parser.error("-M and -j don't go together!")
384 if ns.failfast and not (ns.verbose or ns.verbose3):
385 parser.error("-G/--failfast needs either -v or -W")
386
387 if ns.quiet:
388 ns.verbose = 0
389 if ns.timeout is not None:
390 if hasattr(faulthandler, 'dump_traceback_later'):
391 if ns.timeout <= 0:
392 ns.timeout = None
393 else:
394 print("Warning: The timeout option requires "
395 "faulthandler.dump_traceback_later")
396 ns.timeout = None
397 if ns.use_mp is not None:
398 if ns.use_mp <= 0:
399 # Use all cores + extras for tests that like to sleep
400 ns.use_mp = 2 + (os.cpu_count() or 1)
401 if ns.use_mp == 1:
402 ns.use_mp = None
403 if ns.use:
404 for a in ns.use:
405 for r in a:
406 if r == 'all':
407 ns.use_resources[:] = RESOURCE_NAMES
408 continue
409 if r == 'none':
410 del ns.use_resources[:]
411 continue
412 remove = False
413 if r[0] == '-':
414 remove = True
415 r = r[1:]
416 if remove:
417 if r in ns.use_resources:
418 ns.use_resources.remove(r)
419 elif r not in ns.use_resources:
420 ns.use_resources.append(r)
421 if ns.random_seed is not None:
422 ns.randomize = True
423
424 return ns
425
426
Eli Bendersky7f5c22c2013-09-02 08:57:21 -0700427def run_test_in_subprocess(testname, ns):
428 """Run the given test in a subprocess with --slaveargs.
429
430 ns is the option Namespace parsed from command-line arguments. regrtest
431 is invoked in a subprocess with the --slaveargs argument; when the
432 subprocess exits, its return code, stdout and stderr are returned as a
433 3-tuple.
434 """
435 from subprocess import Popen, PIPE
436 base_cmd = ([sys.executable] + support.args_from_interpreter_flags() +
437 ['-X', 'faulthandler', '-m', 'test.regrtest'])
438
439 slaveargs = (
440 (testname, ns.verbose, ns.quiet),
441 dict(huntrleaks=ns.huntrleaks,
442 use_resources=ns.use_resources,
Eli Benderskye8de2962013-09-02 17:01:10 -0700443 output_on_failure=ns.verbose3,
Eli Bendersky7f5c22c2013-09-02 08:57:21 -0700444 timeout=ns.timeout, failfast=ns.failfast,
445 match_tests=ns.match_tests))
446 # Running the child from the same working directory as regrtest's original
447 # invocation ensures that TEMPDIR for the child is the same when
448 # sysconfig.is_python_build() is true. See issue 15300.
449 popen = Popen(base_cmd + ['--slaveargs', json.dumps(slaveargs)],
450 stdout=PIPE, stderr=PIPE,
451 universal_newlines=True,
452 close_fds=(os.name != 'nt'),
453 cwd=support.SAVEDCWD)
454 stdout, stderr = popen.communicate()
455 retcode = popen.wait()
456 return retcode, stdout, stderr
457
458
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300459def main(tests=None, **kwargs):
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000460 """Execute a test suite.
461
Thomas Wouters7e474022000-07-16 12:04:32 +0000462 This also parses command-line options and modifies its behavior
Fred Drake004d5e62000-10-23 17:22:08 +0000463 accordingly.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000464
465 tests -- a list of strings containing test names (optional)
466 testdir -- the directory in which to look for tests (optional)
467
468 Users other than the Python test suite will certainly want to
469 specify testdir; if it's omitted, the directory containing the
Fred Drake004d5e62000-10-23 17:22:08 +0000470 Python test suite is searched for.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000471
472 If the tests argument is omitted, the tests listed on the
473 command-line will be used. If that's empty, too, then all *.py
474 files beginning with test_ will be used.
Skip Montanaroab1c7912000-06-30 16:39:27 +0000475
Antoine Pitrou88909542009-06-29 13:54:42 +0000476 The other default arguments (verbose, quiet, exclude,
Collin Winterfd12f492009-03-29 04:05:05 +0000477 single, randomize, findleaks, use_resources, trace, coverdir,
478 print_slow, and random_seed) allow programmers calling main()
479 directly to set the values that would normally be set by flags
480 on the command line.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000481 """
Victor Stinnercb41cda2011-07-13 23:47:21 +0200482 # Display the Python traceback on fatal errors (e.g. segfault)
Victor Stinner3c18f252011-05-22 15:27:14 +0200483 faulthandler.enable(all_threads=True)
484
Victor Stinnercb41cda2011-07-13 23:47:21 +0200485 # Display the Python traceback on SIGALRM or SIGUSR1 signal
486 signals = []
487 if hasattr(signal, 'SIGALRM'):
488 signals.append(signal.SIGALRM)
489 if hasattr(signal, 'SIGUSR1'):
490 signals.append(signal.SIGUSR1)
491 for signum in signals:
492 faulthandler.register(signum, chain=True)
493
Victor Stinner1802d3f2010-05-19 17:11:19 +0000494 replace_stdout()
495
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000496 support.record_original_stdout(sys.stdout)
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -0800497
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300498 ns = _parse_args(sys.argv[1:], **kwargs)
Barry Warsaw08fca522001-08-20 22:33:46 +0000499
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300500 if ns.huntrleaks:
501 # Avoid false positives due to various caches
502 # filling slowly with random data:
503 warm_caches()
504 if ns.memlimit is not None:
505 support.set_memlimit(ns.memlimit)
506 if ns.threshold is not None:
507 import gc
508 gc.set_threshold(ns.threshold)
509 if ns.nowindows:
510 import msvcrt
511 msvcrt.SetErrorMode(msvcrt.SEM_FAILCRITICALERRORS|
512 msvcrt.SEM_NOALIGNMENTFAULTEXCEPT|
513 msvcrt.SEM_NOGPFAULTERRORBOX|
514 msvcrt.SEM_NOOPENFILEERRORBOX)
515 try:
516 msvcrt.CrtSetReportMode
517 except AttributeError:
518 # release build
519 pass
R. David Murray35768ad2009-11-15 00:23:21 +0000520 else:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300521 for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]:
522 msvcrt.CrtSetReportMode(m, msvcrt.CRTDBG_MODE_FILE)
523 msvcrt.CrtSetReportFile(m, msvcrt.CRTDBG_FILE_STDERR)
524 if ns.wait:
525 input("Press any key to continue...")
526
527 if ns.slaveargs is not None:
528 args, kwargs = json.loads(ns.slaveargs)
Andrew Svetlov8913a6c2013-09-01 07:58:41 +0300529 if kwargs.get('huntrleaks'):
530 unittest.BaseTestSuite._cleanup = False
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300531 try:
532 result = runtest(*args, **kwargs)
533 except KeyboardInterrupt:
534 result = INTERRUPTED, ''
535 except BaseException as e:
536 traceback.print_exc()
537 result = CHILD_ERROR, str(e)
538 sys.stdout.flush()
539 print() # Force a newline (just in case)
540 print(json.dumps(result))
541 sys.exit(0)
Barry Warsaw08fca522001-08-20 22:33:46 +0000542
Guido van Rossum152494a1996-12-20 03:12:20 +0000543 good = []
544 bad = []
545 skipped = []
Fred Drake9a0db072003-02-03 15:19:30 +0000546 resource_denieds = []
Nick Coghlan6ead5522009-10-18 13:19:33 +0000547 environment_changed = []
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000548 interrupted = False
Barry Warsawe11e3de1999-01-28 19:51:51 +0000549
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300550 if ns.findleaks:
Barry Warsawa873b032000-08-03 15:50:37 +0000551 try:
552 import gc
Brett Cannon260fbe82013-07-04 18:16:15 -0400553 except ImportError:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000554 print('No GC available, disabling findleaks.')
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300555 ns.findleaks = False
Barry Warsawa873b032000-08-03 15:50:37 +0000556 else:
Neil Schemenauer8a00abc2000-10-13 01:32:42 +0000557 # Uncomment the line below to report garbage that is not
558 # freeable by reference counting alone. By default only
559 # garbage that is not collectable by the GC is reported.
560 #gc.set_debug(gc.DEBUG_SAVEALL)
Neil Schemenauerd569f232000-09-22 15:29:28 +0000561 found_garbage = []
Barry Warsawa873b032000-08-03 15:50:37 +0000562
Andrew Svetlov8913a6c2013-09-01 07:58:41 +0300563 if ns.huntrleaks:
564 unittest.BaseTestSuite._cleanup = False
565
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300566 if ns.single:
Florent Xiclunaec882212010-08-09 16:56:43 +0000567 filename = os.path.join(TEMPDIR, 'pynexttest')
Barry Warsawe11e3de1999-01-28 19:51:51 +0000568 try:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300569 with open(filename, 'r') as fp:
570 next_test = fp.read().strip()
571 tests = [next_test]
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200572 except OSError:
Barry Warsawe11e3de1999-01-28 19:51:51 +0000573 pass
Tim Petersc5000df2002-06-02 21:42:01 +0000574
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300575 if ns.fromfile:
Tim Petersc5000df2002-06-02 21:42:01 +0000576 tests = []
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300577 with open(os.path.join(support.SAVEDCWD, ns.fromfile)) as fp:
578 count_pat = re.compile(r'\[\s*\d+/\s*\d+\]')
579 for line in fp:
580 line = count_pat.sub('', line)
581 guts = line.split() # assuming no test has whitespace in its name
582 if guts and not guts[0].startswith('#'):
583 tests.extend(guts)
Tim Petersc5000df2002-06-02 21:42:01 +0000584
585 # Strip .py extensions.
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300586 removepy(ns.args)
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000587 removepy(tests)
Tim Petersc5000df2002-06-02 21:42:01 +0000588
Guido van Rossum6c74fea1998-08-25 12:29:08 +0000589 stdtests = STDTESTS[:]
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000590 nottests = NOTTESTS.copy()
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300591 if ns.exclude:
592 for arg in ns.args:
Guido van Rossum6c74fea1998-08-25 12:29:08 +0000593 if arg in stdtests:
594 stdtests.remove(arg)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000595 nottests.add(arg)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300596 ns.args = []
Florent Xicluna0e62a142010-03-06 17:34:48 +0000597
598 # For a partial run, we do not need to clutter the output.
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300599 if ns.verbose or ns.header or not (ns.quiet or ns.single or tests or ns.args):
Florent Xicluna0e62a142010-03-06 17:34:48 +0000600 # Print basic platform information
601 print("==", platform.python_implementation(), *sys.version.split())
Florent Xiclunaec882212010-08-09 16:56:43 +0000602 print("== ", platform.platform(aliased=True),
603 "%s-endian" % sys.byteorder)
Christian Heimes985ecdc2013-11-20 11:46:18 +0100604 print("== ", "hash algorithm:", sys.hash_info.algorithm,
605 "64bit" if sys.maxsize > 2**32 else "32bit")
Florent Xicluna0e62a142010-03-06 17:34:48 +0000606 print("== ", os.getcwd())
Antoine Pitrou3c4402f2011-01-03 20:38:52 +0000607 print("Testing with flags:", sys.flags)
Florent Xicluna0e62a142010-03-06 17:34:48 +0000608
R David Murrayb588f8d2011-03-24 14:42:58 -0400609 # if testdir is set, then we are not running the python tests suite, so
610 # don't add default tests to be executed or skipped (pass empty values)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300611 if ns.testdir:
612 alltests = findtests(ns.testdir, list(), set())
R David Murrayb588f8d2011-03-24 14:42:58 -0400613 else:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300614 alltests = findtests(ns.testdir, stdtests, nottests)
R David Murrayb588f8d2011-03-24 14:42:58 -0400615
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300616 selected = tests or ns.args or alltests
617 if ns.single:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000618 selected = selected[:1]
R. David Murrayef1992b2009-12-16 15:19:27 +0000619 try:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000620 next_single_test = alltests[alltests.index(selected[0])+1]
R. David Murrayef1992b2009-12-16 15:19:27 +0000621 except IndexError:
622 next_single_test = None
R David Murrayc3bf78a2012-10-27 17:07:05 -0400623 # Remove all the selected tests that precede start if it's set.
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300624 if ns.start:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000625 try:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300626 del selected[:selected.index(ns.start)]
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000627 except ValueError:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300628 print("Couldn't find starting test (%s), using all tests" % ns.start)
629 if ns.randomize:
630 if ns.random_seed is None:
631 ns.random_seed = random.randrange(10000000)
632 random.seed(ns.random_seed)
633 print("Using random seed", ns.random_seed)
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000634 random.shuffle(selected)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300635 if ns.trace:
Georg Brandl33c28812009-04-01 23:07:29 +0000636 import trace, tempfile
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100637 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,
Georg Brandl33c28812009-04-01 23:07:29 +0000638 tempfile.gettempdir()],
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000639 trace=False, count=True)
R. David Murray7dc72cc2009-11-14 16:13:02 +0000640
Christian Heimesb186d002008-03-18 15:15:01 +0000641 test_times = []
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300642 support.verbose = ns.verbose # Tell tests to be moderately quiet
643 support.use_resources = ns.use_resources
Guido van Rossum5796d262000-04-21 21:35:06 +0000644 save_modules = sys.modules.keys()
Antoine Pitrou88909542009-06-29 13:54:42 +0000645
646 def accumulate_result(test, result):
647 ok, test_time = result
648 test_times.append((test_time, test))
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000649 if ok == PASSED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000650 good.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000651 elif ok == FAILED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000652 bad.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000653 elif ok == ENV_CHANGED:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000654 environment_changed.append(test)
655 elif ok == SKIPPED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000656 skipped.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000657 elif ok == RESOURCE_DENIED:
658 skipped.append(test)
659 resource_denieds.append(test)
Antoine Pitrou88909542009-06-29 13:54:42 +0000660
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300661 if ns.forever:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000662 def test_forever(tests=list(selected)):
R. David Murray7dc72cc2009-11-14 16:13:02 +0000663 while True:
664 for test in tests:
665 yield test
666 if bad:
667 return
668 tests = test_forever()
Georg Brandle8e02e32010-08-03 07:56:50 +0000669 test_count = ''
670 test_count_width = 3
R. David Murray7dc72cc2009-11-14 16:13:02 +0000671 else:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000672 tests = iter(selected)
Georg Brandle8e02e32010-08-03 07:56:50 +0000673 test_count = '/{}'.format(len(selected))
674 test_count_width = len(test_count) - 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000675
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300676 if ns.use_mp:
Victor Stinner45df8202010-04-28 22:31:17 +0000677 try:
678 from threading import Thread
Brett Cannon260fbe82013-07-04 18:16:15 -0400679 except ImportError:
Victor Stinner45df8202010-04-28 22:31:17 +0000680 print("Multiprocess option requires thread support")
681 sys.exit(2)
Georg Brandl1b37e872010-03-14 10:45:50 +0000682 from queue import Queue
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100683 debug_output_pat = re.compile(r"\[\d+ refs, \d+ blocks\]$")
Antoine Pitrou88909542009-06-29 13:54:42 +0000684 output = Queue()
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200685 pending = MultiprocessTests(tests)
Antoine Pitrou88909542009-06-29 13:54:42 +0000686 def work():
687 # A worker thread.
Neal Norwitz14ca3272006-02-28 18:05:43 +0000688 try:
Antoine Pitrou88909542009-06-29 13:54:42 +0000689 while True:
690 try:
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200691 test = next(pending)
R. David Murray7dc72cc2009-11-14 16:13:02 +0000692 except StopIteration:
R. David Murray27144602009-10-19 15:26:16 +0000693 output.put((None, None, None, None))
Antoine Pitrou88909542009-06-29 13:54:42 +0000694 return
Eli Bendersky7f5c22c2013-09-02 08:57:21 -0700695 retcode, stdout, stderr = run_test_in_subprocess(test, ns)
R. David Murray27144602009-10-19 15:26:16 +0000696 # Strip last refcount output line if it exists, since it
697 # comes from the shutdown of the interpreter in the subcommand.
698 stderr = debug_output_pat.sub("", stderr)
699 stdout, _, result = stdout.strip().rpartition("\n")
Victor Stinner4b739882011-03-31 18:02:36 +0200700 if retcode != 0:
701 result = (CHILD_ERROR, "Exit code %s" % retcode)
702 output.put((test, stdout.rstrip(), stderr.rstrip(), result))
703 return
R. David Murray7dc72cc2009-11-14 16:13:02 +0000704 if not result:
705 output.put((None, None, None, None))
706 return
Antoine Pitrou88909542009-06-29 13:54:42 +0000707 result = json.loads(result)
R. David Murray27144602009-10-19 15:26:16 +0000708 output.put((test, stdout.rstrip(), stderr.rstrip(), result))
Antoine Pitrou88909542009-06-29 13:54:42 +0000709 except BaseException:
R. David Murray27144602009-10-19 15:26:16 +0000710 output.put((None, None, None, None))
Neal Norwitz14ca3272006-02-28 18:05:43 +0000711 raise
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300712 workers = [Thread(target=work) for i in range(ns.use_mp)]
Antoine Pitrou88909542009-06-29 13:54:42 +0000713 for worker in workers:
714 worker.start()
715 finished = 0
Georg Brandldee7b852010-08-02 18:59:52 +0000716 test_index = 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000717 try:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300718 while finished < ns.use_mp:
R. David Murray7dc72cc2009-11-14 16:13:02 +0000719 test, stdout, stderr, result = output.get()
720 if test is None:
721 finished += 1
722 continue
Victor Stinnera2a895c2011-05-23 23:14:05 +0200723 accumulate_result(test, result)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300724 if not ns.quiet:
Ezio Melotti84f75c62011-05-24 01:00:10 +0300725 fmt = "[{1:{0}}{2}/{3}] {4}" if bad else "[{1:{0}}{2}] {4}"
726 print(fmt.format(
Victor Stinnera2a895c2011-05-23 23:14:05 +0200727 test_count_width, test_index, test_count,
728 len(bad), test))
R. David Murray7dc72cc2009-11-14 16:13:02 +0000729 if stdout:
730 print(stdout)
731 if stderr:
732 print(stderr, file=sys.stderr)
Antoine Pitrou82372582012-06-27 17:41:07 +0200733 sys.stdout.flush()
734 sys.stderr.flush()
R. David Murray7dc72cc2009-11-14 16:13:02 +0000735 if result[0] == INTERRUPTED:
Victor Stinner29650112012-08-08 22:37:26 +0200736 raise KeyboardInterrupt
Victor Stinner4b739882011-03-31 18:02:36 +0200737 if result[0] == CHILD_ERROR:
Victor Stinner571e8fd2011-05-01 22:57:43 +0200738 raise Exception("Child error on {}: {}".format(test, result[1]))
Georg Brandldee7b852010-08-02 18:59:52 +0000739 test_index += 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000740 except KeyboardInterrupt:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000741 interrupted = True
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200742 pending.interrupted = True
Antoine Pitrou88909542009-06-29 13:54:42 +0000743 for worker in workers:
744 worker.join()
745 else:
Georg Brandldee7b852010-08-02 18:59:52 +0000746 for test_index, test in enumerate(tests, 1):
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300747 if not ns.quiet:
Ezio Melotti84f75c62011-05-24 01:00:10 +0300748 fmt = "[{1:{0}}{2}/{3}] {4}" if bad else "[{1:{0}}{2}] {4}"
749 print(fmt.format(
Victor Stinnera2a895c2011-05-23 23:14:05 +0200750 test_count_width, test_index, test_count, len(bad), test))
Antoine Pitrou88909542009-06-29 13:54:42 +0000751 sys.stdout.flush()
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300752 if ns.trace:
Antoine Pitrou88909542009-06-29 13:54:42 +0000753 # If we're tracing code coverage, then we don't exit with status
754 # if on a false return value from main.
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300755 tracer.runctx('runtest(test, ns.verbose, ns.quiet, timeout=ns.timeout)',
Antoine Pitrou88909542009-06-29 13:54:42 +0000756 globals=globals(), locals=vars())
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000757 else:
Antoine Pitrou88909542009-06-29 13:54:42 +0000758 try:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300759 result = runtest(test, ns.verbose, ns.quiet,
Eli Benderskye8de2962013-09-02 17:01:10 -0700760 ns.huntrleaks,
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300761 output_on_failure=ns.verbose3,
762 timeout=ns.timeout, failfast=ns.failfast,
763 match_tests=ns.match_tests)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000764 accumulate_result(test, result)
Antoine Pitrou88909542009-06-29 13:54:42 +0000765 except KeyboardInterrupt:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000766 interrupted = True
Antoine Pitrou88909542009-06-29 13:54:42 +0000767 break
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300768 if ns.findleaks:
Antoine Pitrou88909542009-06-29 13:54:42 +0000769 gc.collect()
770 if gc.garbage:
771 print("Warning: test created", len(gc.garbage), end=' ')
772 print("uncollectable object(s).")
773 # move the uncollectable objects somewhere so we don't see
774 # them again
775 found_garbage.extend(gc.garbage)
776 del gc.garbage[:]
777 # Unload the newly imported modules (best effort finalization)
778 for module in sys.modules.keys():
779 if module not in save_modules and module.startswith("test."):
780 support.unload(module)
Jeremy Hylton7a1ea0e2001-10-17 13:45:28 +0000781
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000782 if interrupted:
783 # print a newline after ^C
784 print()
785 print("Test suite interrupted by signal SIGINT.")
786 omitted = set(selected) - set(good) - set(bad) - set(skipped)
787 print(count(len(omitted), "test"), "omitted:")
788 printlist(omitted)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300789 if good and not ns.quiet:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000790 if not bad and not skipped and not interrupted and len(good) > 1:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000791 print("All", end=' ')
792 print(count(len(good), "test"), "OK.")
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300793 if ns.print_slow:
Christian Heimesb186d002008-03-18 15:15:01 +0000794 test_times.sort(reverse=True)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000795 print("10 slowest tests:")
Christian Heimesb186d002008-03-18 15:15:01 +0000796 for time, test in test_times[:10]:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000797 print("%s: %.1fs" % (test, time))
Guido van Rossum152494a1996-12-20 03:12:20 +0000798 if bad:
Zachary Ware9a47ed82015-08-08 22:03:27 -0500799 print(count(len(bad), "test"), "failed:")
800 printlist(bad)
Vinay Sajipf9596182012-03-02 01:01:13 +0000801 if environment_changed:
802 print("{} altered the execution environment:".format(
803 count(len(environment_changed), "test")))
804 printlist(environment_changed)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300805 if skipped and not ns.quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000806 print(count(len(skipped), "test"), "skipped:")
Tim Petersa45da922001-08-12 03:45:50 +0000807 printlist(skipped)
Barry Warsawe11e3de1999-01-28 19:51:51 +0000808
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300809 if ns.verbose2 and bad:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000810 print("Re-running failed tests in verbose mode")
Zachary Ware920a3352015-08-04 21:54:54 -0500811 for test in bad[:]:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000812 print("Re-running test %r in verbose mode" % test)
Tim Peters922dd7d2006-03-10 23:37:10 +0000813 sys.stdout.flush()
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000814 try:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300815 ns.verbose = True
Eli Benderskye8de2962013-09-02 17:01:10 -0700816 ok = runtest(test, True, ns.quiet, ns.huntrleaks,
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300817 timeout=ns.timeout)
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000818 except KeyboardInterrupt:
819 # print a newline separate from the ^C
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000820 print()
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000821 break
Zachary Ware920a3352015-08-04 21:54:54 -0500822 else:
823 if ok[0] in {PASSED, ENV_CHANGED, SKIPPED, RESOURCE_DENIED}:
824 bad.remove(test)
825 else:
826 if bad:
827 print(count(len(bad), 'test'), "failed again:")
828 printlist(bad)
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000829
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300830 if ns.single:
R. David Murrayef1992b2009-12-16 15:19:27 +0000831 if next_single_test:
832 with open(filename, 'w') as fp:
833 fp.write(next_single_test + '\n')
Barry Warsawe11e3de1999-01-28 19:51:51 +0000834 else:
835 os.unlink(filename)
836
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300837 if ns.trace:
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000838 r = tracer.results()
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300839 r.write_results(show_missing=True, summary=True, coverdir=ns.coverdir)
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000840
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300841 if ns.runleaks:
Skip Montanaro0179a182004-06-06 15:53:18 +0000842 os.system("leaks %d" % os.getpid())
843
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000844 sys.exit(len(bad) > 0 or interrupted)
Barry Warsaw08fca522001-08-20 22:33:46 +0000845
Guido van Rossum152494a1996-12-20 03:12:20 +0000846
R David Murrayb588f8d2011-03-24 14:42:58 -0400847# small set of tests to determine if we have a basically functioning interpreter
848# (i.e. if any of these fail, then anything else is likely to follow)
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000849STDTESTS = [
Guido van Rossum152494a1996-12-20 03:12:20 +0000850 'test_grammar',
851 'test_opcodes',
Guido van Rossumd8faa362007-04-27 19:54:29 +0000852 'test_dict',
Guido van Rossum152494a1996-12-20 03:12:20 +0000853 'test_builtin',
854 'test_exceptions',
855 'test_types',
Collin Winter7afaa882007-03-08 19:54:43 +0000856 'test_unittest',
857 'test_doctest',
858 'test_doctest2',
Eli Benderskyd18a0472011-07-27 20:21:45 +0300859 'test_support'
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000860]
Guido van Rossum152494a1996-12-20 03:12:20 +0000861
R David Murrayb588f8d2011-03-24 14:42:58 -0400862# set of tests that we don't want to be executed when using regrtest
R David Murray57648302011-03-24 14:57:05 -0400863NOTTESTS = set()
Guido van Rossum152494a1996-12-20 03:12:20 +0000864
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000865def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
Guido van Rossum152494a1996-12-20 03:12:20 +0000866 """Return a list of all applicable test modules."""
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000867 testdir = findtestdir(testdir)
Guido van Rossum152494a1996-12-20 03:12:20 +0000868 names = os.listdir(testdir)
869 tests = []
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000870 others = set(stdtests) | nottests
Guido van Rossum152494a1996-12-20 03:12:20 +0000871 for name in names:
R David Murray661720e2011-03-21 15:14:34 -0400872 mod, ext = os.path.splitext(name)
873 if mod[:5] == "test_" and ext in (".py", "") and mod not in others:
874 tests.append(mod)
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000875 return stdtests + sorted(tests)
Guido van Rossum152494a1996-12-20 03:12:20 +0000876
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200877# We do not use a generator so multiple threads can call next().
878class MultiprocessTests(object):
879
880 """A thread-safe iterator over tests for multiprocess mode."""
881
882 def __init__(self, tests):
883 self.interrupted = False
884 self.lock = threading.Lock()
885 self.tests = tests
886
887 def __iter__(self):
888 return self
889
890 def __next__(self):
891 with self.lock:
892 if self.interrupted:
893 raise StopIteration('tests interrupted')
894 return next(self.tests)
895
Victor Stinnerf58087b2010-05-02 17:24:51 +0000896def replace_stdout():
897 """Set stdout encoder error handler to backslashreplace (as stderr error
898 handler) to avoid UnicodeEncodeError when printing a traceback"""
Victor Stinner4b2b43d2011-01-05 03:54:26 +0000899 import atexit
900
Victor Stinnerf58087b2010-05-02 17:24:51 +0000901 stdout = sys.stdout
902 sys.stdout = open(stdout.fileno(), 'w',
903 encoding=stdout.encoding,
Victor Stinner4b2b43d2011-01-05 03:54:26 +0000904 errors="backslashreplace",
Victor Stinnerbe621032011-05-25 02:01:55 +0200905 closefd=False,
906 newline='\n')
Victor Stinner4b2b43d2011-01-05 03:54:26 +0000907
908 def restore_stdout():
909 sys.stdout.close()
910 sys.stdout = stdout
911 atexit.register(restore_stdout)
Victor Stinnerf58087b2010-05-02 17:24:51 +0000912
Antoine Pitrou88909542009-06-29 13:54:42 +0000913def runtest(test, verbose, quiet,
Eli Benderskye8de2962013-09-02 17:01:10 -0700914 huntrleaks=False, use_resources=None,
Antoine Pitrouf83e4ac2011-07-29 23:57:10 +0200915 output_on_failure=False, failfast=False, match_tests=None,
916 timeout=None):
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000917 """Run a single test.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000918
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000919 test -- the name of the test
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000920 verbose -- if true, print more messages
Trent Mickf29f47b2000-08-11 19:02:59 +0000921 quiet -- if true, don't print 'skipped' messages (probably redundant)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000922 huntrleaks -- run multiple times to test for leaks; requires a debug
923 build; a triple corresponding to -R's three arguments
Eli Benderskye5eebed2013-09-02 16:52:25 -0700924 use_resources -- list of extra resources to use
Victor Stinner8313d6a2011-06-29 15:22:26 +0200925 output_on_failure -- if true, display test output on failure
Victor Stinner0cc8d592011-03-31 18:10:13 +0200926 timeout -- dump the traceback and exit if a test takes more than
927 timeout seconds
Eli Benderskye5eebed2013-09-02 16:52:25 -0700928 failfast, match_tests -- See regrtest command-line flags for these.
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000929
Eli Benderskye5eebed2013-09-02 16:52:25 -0700930 Returns the tuple result, test_time, where result is one of the constants:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000931 INTERRUPTED KeyboardInterrupt when run under -j
932 RESOURCE_DENIED test skipped because resource denied
933 SKIPPED test skipped for some other reason
934 ENV_CHANGED test failed because it changed the execution environment
935 FAILED test failed
936 PASSED test passed
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000937 """
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000938
Antoine Pitrou88909542009-06-29 13:54:42 +0000939 if use_resources is not None:
940 support.use_resources = use_resources
Victor Stinner30196882011-06-03 12:53:26 +0200941 use_timeout = (timeout is not None)
Victor Stinner7d648a02011-03-31 18:27:50 +0200942 if use_timeout:
Victor Stinner4de701b2013-06-17 20:27:10 +0200943 faulthandler.dump_traceback_later(timeout, exit=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000944 try:
Antoine Pitroub9c73e82011-07-29 23:53:38 +0200945 support.match_tests = match_tests
Antoine Pitrou216a3bc2011-07-23 22:33:39 +0200946 if failfast:
947 support.failfast = True
Victor Stinner8313d6a2011-06-29 15:22:26 +0200948 if output_on_failure:
Victor Stinnerea95de72011-06-29 15:34:48 +0200949 support.verbose = True
950
951 # Reuse the same instance to all calls to runtest(). Some
952 # tests keep a reference to sys.stdout or sys.stderr
953 # (eg. test_argparse).
Victor Stinner8313d6a2011-06-29 15:22:26 +0200954 if runtest.stringio is None:
Victor Stinnerfcc2a212011-06-29 20:01:29 +0200955 stream = io.StringIO()
956 runtest.stringio = stream
957 else:
958 stream = runtest.stringio
959 stream.seek(0)
960 stream.truncate()
Victor Stinner8313d6a2011-06-29 15:22:26 +0200961
962 orig_stdout = sys.stdout
Victor Stinnera7c33e52011-06-29 13:00:54 +0200963 orig_stderr = sys.stderr
Victor Stinner8313d6a2011-06-29 15:22:26 +0200964 try:
Victor Stinnerea95de72011-06-29 15:34:48 +0200965 sys.stdout = stream
966 sys.stderr = stream
Victor Stinner8313d6a2011-06-29 15:22:26 +0200967 result = runtest_inner(test, verbose, quiet, huntrleaks,
Eli Benderskye8de2962013-09-02 17:01:10 -0700968 display_failure=False)
Victor Stinner8313d6a2011-06-29 15:22:26 +0200969 if result[0] == FAILED:
Victor Stinnerea95de72011-06-29 15:34:48 +0200970 output = stream.getvalue()
Victor Stinner8313d6a2011-06-29 15:22:26 +0200971 orig_stderr.write(output)
972 orig_stderr.flush()
973 finally:
974 sys.stdout = orig_stdout
975 sys.stderr = orig_stderr
Victor Stinnera7c33e52011-06-29 13:00:54 +0200976 else:
Victor Stinnerea95de72011-06-29 15:34:48 +0200977 support.verbose = verbose # Tell tests to be moderately quiet
Eli Benderskye8de2962013-09-02 17:01:10 -0700978 result = runtest_inner(test, verbose, quiet, huntrleaks,
Victor Stinnera7c33e52011-06-29 13:00:54 +0200979 display_failure=not verbose)
Antoine Pitrou293954d2011-03-23 23:01:49 +0100980 return result
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000981 finally:
Victor Stinner7d648a02011-03-31 18:27:50 +0200982 if use_timeout:
Victor Stinner934676a2013-06-17 20:35:08 +0200983 faulthandler.cancel_dump_traceback_later()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000984 cleanup_test_droppings(test, verbose)
Victor Stinner8313d6a2011-06-29 15:22:26 +0200985runtest.stringio = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000986
Nick Coghlan6ead5522009-10-18 13:19:33 +0000987# Unit tests are supposed to leave the execution environment unchanged
988# once they complete. But sometimes tests have bugs, especially when
989# tests fail, and the changes to environment go on to mess up other
990# tests. This can cause issues with buildbot stability, since tests
991# are run in random order and so problems may appear to come and go.
992# There are a few things we can save and restore to mitigate this, and
993# the following context manager handles this task.
994
995class saved_test_environment:
996 """Save bits of the test environment and restore them at block exit.
997
998 with saved_test_environment(testname, verbose, quiet):
999 #stuff
1000
1001 Unless quiet is True, a warning is printed to stderr if any of
1002 the saved items was changed by the test. The attribute 'changed'
1003 is initially False, but is set to True if a change is detected.
1004
1005 If verbose is more than 1, the before and after state of changed
1006 items is also printed.
1007 """
1008
1009 changed = False
1010
1011 def __init__(self, testname, verbose=0, quiet=False):
1012 self.testname = testname
1013 self.verbose = verbose
1014 self.quiet = quiet
1015
1016 # To add things to save and restore, add a name XXX to the resources list
1017 # and add corresponding get_XXX/restore_XXX functions. get_XXX should
1018 # return the value to be saved and compared against a second call to the
1019 # get function when test execution completes. restore_XXX should accept
1020 # the saved value and restore the resource using it. It will be called if
1021 # and only if a change in the value is detected.
1022 #
1023 # Note: XXX will have any '.' replaced with '_' characters when determining
1024 # the corresponding method names.
1025
1026 resources = ('sys.argv', 'cwd', 'sys.stdin', 'sys.stdout', 'sys.stderr',
Brett Cannon29c0e4f2010-03-20 22:22:57 +00001027 'os.environ', 'sys.path', 'sys.path_hooks', '__import__',
Nick Coghlan7bd5dbe2010-12-05 07:17:25 +00001028 'warnings.filters', 'asyncore.socket_map',
Ezio Melotti45763d02011-03-20 15:34:28 +02001029 'logging._handlers', 'logging._handlerList', 'sys.gettrace',
Richard Oudkerk83d7dea2013-08-29 12:51:11 +01001030 'sys.warnoptions',
1031 # multiprocessing.process._cleanup() may release ref
1032 # to a thread, so check processes first.
1033 'multiprocessing.process._dangling', 'threading._dangling',
Éric Araujoec177c12012-06-24 03:27:43 -04001034 'sysconfig._CONFIG_VARS', 'sysconfig._INSTALL_SCHEMES',
Serhiy Storchakaa3a100b2015-03-30 01:28:02 +03001035 'files', 'locale', 'warnings.showwarning',
Éric Araujo28df8de2011-09-19 05:10:45 +02001036 )
Nick Coghlan6ead5522009-10-18 13:19:33 +00001037
1038 def get_sys_argv(self):
1039 return id(sys.argv), sys.argv, sys.argv[:]
1040 def restore_sys_argv(self, saved_argv):
1041 sys.argv = saved_argv[1]
1042 sys.argv[:] = saved_argv[2]
1043
1044 def get_cwd(self):
1045 return os.getcwd()
1046 def restore_cwd(self, saved_cwd):
1047 os.chdir(saved_cwd)
1048
1049 def get_sys_stdout(self):
1050 return sys.stdout
1051 def restore_sys_stdout(self, saved_stdout):
1052 sys.stdout = saved_stdout
1053
1054 def get_sys_stderr(self):
1055 return sys.stderr
1056 def restore_sys_stderr(self, saved_stderr):
1057 sys.stderr = saved_stderr
1058
1059 def get_sys_stdin(self):
1060 return sys.stdin
1061 def restore_sys_stdin(self, saved_stdin):
1062 sys.stdin = saved_stdin
1063
1064 def get_os_environ(self):
1065 return id(os.environ), os.environ, dict(os.environ)
1066 def restore_os_environ(self, saved_environ):
1067 os.environ = saved_environ[1]
1068 os.environ.clear()
1069 os.environ.update(saved_environ[2])
1070
1071 def get_sys_path(self):
1072 return id(sys.path), sys.path, sys.path[:]
1073 def restore_sys_path(self, saved_path):
1074 sys.path = saved_path[1]
1075 sys.path[:] = saved_path[2]
1076
Brett Cannon055470a2010-02-19 15:57:10 +00001077 def get_sys_path_hooks(self):
1078 return id(sys.path_hooks), sys.path_hooks, sys.path_hooks[:]
1079 def restore_sys_path_hooks(self, saved_hooks):
1080 sys.path_hooks = saved_hooks[1]
1081 sys.path_hooks[:] = saved_hooks[2]
1082
Brett Cannon31f59292011-02-21 19:29:56 +00001083 def get_sys_gettrace(self):
1084 return sys.gettrace()
1085 def restore_sys_gettrace(self, trace_fxn):
1086 sys.settrace(trace_fxn)
1087
Brett Cannon055470a2010-02-19 15:57:10 +00001088 def get___import__(self):
Brett Cannon45071902010-06-14 22:22:54 +00001089 return builtins.__import__
Brett Cannon055470a2010-02-19 15:57:10 +00001090 def restore___import__(self, import_):
Brett Cannon45071902010-06-14 22:22:54 +00001091 builtins.__import__ = import_
Brett Cannon055470a2010-02-19 15:57:10 +00001092
Brett Cannon29c0e4f2010-03-20 22:22:57 +00001093 def get_warnings_filters(self):
1094 return id(warnings.filters), warnings.filters, warnings.filters[:]
1095 def restore_warnings_filters(self, saved_filters):
1096 warnings.filters = saved_filters[1]
1097 warnings.filters[:] = saved_filters[2]
1098
Antoine Pitroub14ac8c2010-08-16 00:28:05 +00001099 def get_asyncore_socket_map(self):
1100 asyncore = sys.modules.get('asyncore')
Antoine Pitrouaa879652010-10-29 11:54:38 +00001101 # XXX Making a copy keeps objects alive until __exit__ gets called.
1102 return asyncore and asyncore.socket_map.copy() or {}
Antoine Pitroub14ac8c2010-08-16 00:28:05 +00001103 def restore_asyncore_socket_map(self, saved_map):
1104 asyncore = sys.modules.get('asyncore')
1105 if asyncore is not None:
Antoine Pitrouaa879652010-10-29 11:54:38 +00001106 asyncore.close_all(ignore_all=True)
Antoine Pitroub14ac8c2010-08-16 00:28:05 +00001107 asyncore.socket_map.update(saved_map)
1108
Éric Araujoff913062011-11-29 16:45:07 +01001109 def get_shutil_archive_formats(self):
1110 # we could call get_archives_formats() but that only returns the
1111 # registry keys; we want to check the values too (the functions that
1112 # are registered)
1113 return shutil._ARCHIVE_FORMATS, shutil._ARCHIVE_FORMATS.copy()
1114 def restore_shutil_archive_formats(self, saved):
1115 shutil._ARCHIVE_FORMATS = saved[0]
1116 shutil._ARCHIVE_FORMATS.clear()
1117 shutil._ARCHIVE_FORMATS.update(saved[1])
1118
1119 def get_shutil_unpack_formats(self):
1120 return shutil._UNPACK_FORMATS, shutil._UNPACK_FORMATS.copy()
1121 def restore_shutil_unpack_formats(self, saved):
1122 shutil._UNPACK_FORMATS = saved[0]
1123 shutil._UNPACK_FORMATS.clear()
1124 shutil._UNPACK_FORMATS.update(saved[1])
1125
Nick Coghlan7d819752010-12-05 06:45:03 +00001126 def get_logging__handlers(self):
1127 # _handlers is a WeakValueDictionary
Nick Coghlan7bd5dbe2010-12-05 07:17:25 +00001128 return id(logging._handlers), logging._handlers, logging._handlers.copy()
Nick Coghlan7d819752010-12-05 06:45:03 +00001129 def restore_logging__handlers(self, saved_handlers):
1130 # Can't easily revert the logging state
1131 pass
1132
Nick Coghlan7bd5dbe2010-12-05 07:17:25 +00001133 def get_logging__handlerList(self):
1134 # _handlerList is a list of weakrefs to handlers
1135 return id(logging._handlerList), logging._handlerList, logging._handlerList[:]
1136 def restore_logging__handlerList(self, saved_handlerList):
1137 # Can't easily revert the logging state
1138 pass
1139
Ezio Melotti0123e052011-03-20 15:09:26 +02001140 def get_sys_warnoptions(self):
1141 return id(sys.warnoptions), sys.warnoptions, sys.warnoptions[:]
1142 def restore_sys_warnoptions(self, saved_options):
1143 sys.warnoptions = saved_options[1]
1144 sys.warnoptions[:] = saved_options[2]
1145
Antoine Pitrouc081c0c2011-07-15 22:12:24 +02001146 # Controlling dangling references to Thread objects can make it easier
1147 # to track reference leaks.
1148 def get_threading__dangling(self):
1149 if not threading:
1150 return None
1151 # This copies the weakrefs without making any strong reference
1152 return threading._dangling.copy()
1153 def restore_threading__dangling(self, saved):
1154 if not threading:
1155 return
1156 threading._dangling.clear()
1157 threading._dangling.update(saved)
1158
1159 # Same for Process objects
1160 def get_multiprocessing_process__dangling(self):
1161 if not multiprocessing:
1162 return None
Richard Oudkerk83d7dea2013-08-29 12:51:11 +01001163 # Unjoined process objects can survive after process exits
1164 multiprocessing.process._cleanup()
Antoine Pitrouc081c0c2011-07-15 22:12:24 +02001165 # This copies the weakrefs without making any strong reference
1166 return multiprocessing.process._dangling.copy()
1167 def restore_multiprocessing_process__dangling(self, saved):
1168 if not multiprocessing:
1169 return
1170 multiprocessing.process._dangling.clear()
1171 multiprocessing.process._dangling.update(saved)
1172
Éric Araujo28df8de2011-09-19 05:10:45 +02001173 def get_sysconfig__CONFIG_VARS(self):
1174 # make sure the dict is initialized
1175 sysconfig.get_config_var('prefix')
1176 return (id(sysconfig._CONFIG_VARS), sysconfig._CONFIG_VARS,
1177 dict(sysconfig._CONFIG_VARS))
1178 def restore_sysconfig__CONFIG_VARS(self, saved):
1179 sysconfig._CONFIG_VARS = saved[1]
1180 sysconfig._CONFIG_VARS.clear()
1181 sysconfig._CONFIG_VARS.update(saved[2])
1182
Éric Araujoec177c12012-06-24 03:27:43 -04001183 def get_sysconfig__INSTALL_SCHEMES(self):
1184 return (id(sysconfig._INSTALL_SCHEMES), sysconfig._INSTALL_SCHEMES,
1185 sysconfig._INSTALL_SCHEMES.copy())
1186 def restore_sysconfig__INSTALL_SCHEMES(self, saved):
1187 sysconfig._INSTALL_SCHEMES = saved[1]
1188 sysconfig._INSTALL_SCHEMES.clear()
1189 sysconfig._INSTALL_SCHEMES.update(saved[2])
Éric Araujo28df8de2011-09-19 05:10:45 +02001190
Serhiy Storchakaa3a100b2015-03-30 01:28:02 +03001191 def get_files(self):
1192 return sorted(fn + ('/' if os.path.isdir(fn) else '')
1193 for fn in os.listdir())
1194 def restore_files(self, saved_value):
1195 fn = support.TESTFN
1196 if fn not in saved_value and (fn + '/') not in saved_value:
1197 if os.path.isfile(fn):
1198 support.unlink(fn)
1199 elif os.path.isdir(fn):
1200 support.rmtree(fn)
Éric Araujo28df8de2011-09-19 05:10:45 +02001201
Victor Stinnerd9ccf7f2013-06-17 20:40:05 +02001202 _lc = [getattr(locale, lc) for lc in dir(locale)
Victor Stinner546ccf02013-06-17 21:28:14 +02001203 if lc.startswith('LC_')]
Brett Cannon49e835b2013-04-01 14:11:37 -04001204 def get_locale(self):
1205 pairings = []
1206 for lc in self._lc:
1207 try:
Victor Stinner546ccf02013-06-17 21:28:14 +02001208 pairings.append((lc, locale.setlocale(lc, None)))
Victor Stinnerd9ccf7f2013-06-17 20:40:05 +02001209 except (TypeError, ValueError):
Brett Cannon49e835b2013-04-01 14:11:37 -04001210 continue
1211 return pairings
1212 def restore_locale(self, saved):
1213 for lc, setting in saved:
1214 locale.setlocale(lc, setting)
1215
Brett Cannon6d26eba2013-06-16 15:20:48 -04001216 def get_warnings_showwarning(self):
1217 return warnings.showwarning
1218 def restore_warnings_showwarning(self, fxn):
1219 warnings.showwarning = fxn
1220
Nick Coghlan6ead5522009-10-18 13:19:33 +00001221 def resource_info(self):
1222 for name in self.resources:
1223 method_suffix = name.replace('.', '_')
1224 get_name = 'get_' + method_suffix
1225 restore_name = 'restore_' + method_suffix
1226 yield name, getattr(self, get_name), getattr(self, restore_name)
1227
1228 def __enter__(self):
1229 self.saved_values = dict((name, get()) for name, get, restore
1230 in self.resource_info())
1231 return self
1232
1233 def __exit__(self, exc_type, exc_val, exc_tb):
Antoine Pitrouaa879652010-10-29 11:54:38 +00001234 saved_values = self.saved_values
1235 del self.saved_values
Nick Coghlan6ead5522009-10-18 13:19:33 +00001236 for name, get, restore in self.resource_info():
1237 current = get()
Antoine Pitrouaa879652010-10-29 11:54:38 +00001238 original = saved_values.pop(name)
Nick Coghlan6ead5522009-10-18 13:19:33 +00001239 # Check for changes to the resource's value
1240 if current != original:
1241 self.changed = True
1242 restore(original)
1243 if not self.quiet:
1244 print("Warning -- {} was modified by {}".format(
1245 name, self.testname),
1246 file=sys.stderr)
1247 if self.verbose > 1:
1248 print(" Before: {}\n After: {} ".format(
1249 original, current),
1250 file=sys.stderr)
1251 return False
1252
1253
Victor Stinnera7c33e52011-06-29 13:00:54 +02001254def runtest_inner(test, verbose, quiet,
Eli Benderskye8de2962013-09-02 17:01:10 -07001255 huntrleaks=False, display_failure=True):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001256 support.unload(test)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001257
Antoine Pitrou88909542009-06-29 13:54:42 +00001258 test_time = 0.0
Collin Wintera5503d52009-05-15 01:20:21 +00001259 refleak = False # True if the test leaked references.
Guido van Rossum152494a1996-12-20 03:12:20 +00001260 try:
R. David Murray0bc11ae2009-10-18 22:18:17 +00001261 if test.startswith('test.'):
1262 abstest = test
1263 else:
1264 # Always import it from the test package
1265 abstest = 'test.' + test
1266 with saved_test_environment(test, verbose, quiet) as environment:
1267 start_time = time.time()
Brett Cannon613cf252012-11-14 13:42:51 -05001268 the_module = importlib.import_module(abstest)
R David Murray78fc25c2012-04-09 08:55:42 -04001269 # If the test has a test_main, that will run the appropriate
1270 # tests. If not, use normal unittest test loading.
1271 test_runner = getattr(the_module, "test_main", None)
1272 if test_runner is None:
Zachary Ware69fb6a42014-08-04 11:15:10 -05001273 def test_runner():
1274 loader = unittest.TestLoader()
1275 tests = loader.loadTestsFromModule(the_module)
Victor Stinner5d575392015-01-06 14:05:03 +01001276 for error in loader.errors:
1277 print(error, file=sys.stderr)
1278 if loader.errors:
1279 raise Exception("errors while loading tests")
Zachary Ware69fb6a42014-08-04 11:15:10 -05001280 support.run_unittest(tests)
R David Murray78fc25c2012-04-09 08:55:42 -04001281 test_runner()
R. David Murray0bc11ae2009-10-18 22:18:17 +00001282 if huntrleaks:
Eli Benderskye5eebed2013-09-02 16:52:25 -07001283 refleak = dash_R(the_module, test, test_runner, huntrleaks)
R. David Murray0bc11ae2009-10-18 22:18:17 +00001284 test_time = time.time() - start_time
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001285 except support.ResourceDenied as msg:
Fred Drake9a0db072003-02-03 15:19:30 +00001286 if not quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001287 print(test, "skipped --", msg)
Fred Drake9a0db072003-02-03 15:19:30 +00001288 sys.stdout.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001289 return RESOURCE_DENIED, test_time
R. David Murraya21e4ca2009-03-31 23:16:50 +00001290 except unittest.SkipTest as msg:
Trent Mickf29f47b2000-08-11 19:02:59 +00001291 if not quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001292 print(test, "skipped --", msg)
Guido van Rossum3cda93e2002-09-13 21:28:03 +00001293 sys.stdout.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001294 return SKIPPED, test_time
Fred Drakefe5c22a2000-08-18 16:04:05 +00001295 except KeyboardInterrupt:
1296 raise
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001297 except support.TestFailed as msg:
Victor Stinnera7c33e52011-06-29 13:00:54 +02001298 if display_failure:
1299 print("test", test, "failed --", msg, file=sys.stderr)
1300 else:
1301 print("test", test, "failed", file=sys.stderr)
R. David Murray11cabcf2010-09-29 01:08:05 +00001302 sys.stderr.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001303 return FAILED, test_time
Guido van Rossum9e48b271997-07-16 01:56:13 +00001304 except:
Antoine Pitrou779a5b02011-03-21 19:55:16 +01001305 msg = traceback.format_exc()
1306 print("test", test, "crashed --", msg, file=sys.stderr)
R. David Murray11cabcf2010-09-29 01:08:05 +00001307 sys.stderr.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001308 return FAILED, test_time
Guido van Rossum152494a1996-12-20 03:12:20 +00001309 else:
Collin Wintera5503d52009-05-15 01:20:21 +00001310 if refleak:
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001311 return FAILED, test_time
Nick Coghlan6ead5522009-10-18 13:19:33 +00001312 if environment.changed:
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001313 return ENV_CHANGED, test_time
1314 return PASSED, test_time
Guido van Rossum0fcca4e2001-09-21 20:31:52 +00001315
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001316def cleanup_test_droppings(testname, verbose):
1317 import shutil
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001318 import stat
Antoine Pitrouc14efc42010-10-29 19:34:45 +00001319 import gc
1320
1321 # First kill any dangling references to open files etc.
1322 # This can also issue some ResourceWarnings which would otherwise get
Antoine Pitrou2b40efd2010-10-29 19:36:37 +00001323 # triggered during the following test run, and possibly produce failures.
Antoine Pitrouc14efc42010-10-29 19:34:45 +00001324 gc.collect()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001325
1326 # Try to clean up junk commonly left behind. While tests shouldn't leave
1327 # any files or directories behind, when a test fails that can be tedious
1328 # for it to arrange. The consequences can be especially nasty on Windows,
1329 # since if a test leaves a file open, it cannot be deleted by name (while
1330 # there's nothing we can do about that here either, we can display the
1331 # name of the offending test, which is a real help).
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001332 for name in (support.TESTFN,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001333 "db_home",
1334 ):
1335 if not os.path.exists(name):
1336 continue
1337
1338 if os.path.isdir(name):
1339 kind, nuker = "directory", shutil.rmtree
1340 elif os.path.isfile(name):
1341 kind, nuker = "file", os.unlink
1342 else:
1343 raise SystemError("os.path says %r exists but is neither "
1344 "directory nor file" % name)
1345
1346 if verbose:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001347 print("%r left behind %s %r" % (testname, kind, name))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001348 try:
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001349 # if we have chmod, fix possible permissions problems
1350 # that might prevent cleanup
1351 if (hasattr(os, 'chmod')):
1352 os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001353 nuker(name)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001354 except Exception as msg:
1355 print(("%r left behind %s %r and it couldn't be "
1356 "removed: %s" % (testname, kind, name, msg)), file=sys.stderr)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001357
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001358def dash_R(the_module, test, indirect_test, huntrleaks):
Collin Wintera5503d52009-05-15 01:20:21 +00001359 """Run a test multiple times, looking for reference leaks.
1360
1361 Returns:
1362 False if the test didn't leak references; True if we detected refleaks.
1363 """
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001364 # This code is hackish and inelegant, but it seems to do the job.
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001365 import copyreg
1366 import collections.abc
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001367
1368 if not hasattr(sys, 'gettotalrefcount'):
1369 raise Exception("Tracking reference leaks requires a debug build "
1370 "of Python")
1371
1372 # Save current values for dash_R_cleanup() to restore.
1373 fs = warnings.filters[:]
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001374 ps = copyreg.dispatch_table.copy()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001375 pic = sys.path_importer_cache.copy()
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001376 try:
1377 import zipimport
Brett Cannon260fbe82013-07-04 18:16:15 -04001378 except ImportError:
Benjamin Petersoncf626032014-02-16 14:52:01 -05001379 zdc = None # Run unmodified on platforms without zipimport support
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001380 else:
1381 zdc = zipimport._zip_directory_cache.copy()
Christian Heimes93852662007-12-01 12:22:32 +00001382 abcs = {}
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001383 for abc in [getattr(collections.abc, a) for a in collections.abc.__all__]:
Christian Heimesbe5b30b2008-03-03 19:18:51 +00001384 if not isabstract(abc):
Christian Heimes93852662007-12-01 12:22:32 +00001385 continue
1386 for obj in abc.__subclasses__() + [abc]:
1387 abcs[obj] = obj._abc_registry.copy()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001388
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001389 nwarmup, ntracked, fname = huntrleaks
Ezio Melotti184bdfb2010-02-18 09:37:05 +00001390 fname = os.path.join(support.SAVEDCWD, fname)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001391 repcount = nwarmup + ntracked
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001392 rc_deltas = [0] * repcount
1393 alloc_deltas = [0] * repcount
1394
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001395 print("beginning", repcount, "repetitions", file=sys.stderr)
1396 print(("1234567890"*(repcount//10 + 1))[:repcount], file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +00001397 sys.stderr.flush()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001398 for i in range(repcount):
R David Murray14d080e2013-01-12 11:34:38 -05001399 indirect_test()
Benjamin Petersonf617fa82014-02-16 14:53:55 -05001400 alloc_after, rc_after = dash_R_cleanup(fs, ps, pic, zdc, abcs)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001401 sys.stderr.write('.')
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001402 sys.stderr.flush()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001403 if i >= nwarmup:
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001404 rc_deltas[i] = rc_after - rc_before
1405 alloc_deltas[i] = alloc_after - alloc_before
1406 alloc_before, rc_before = alloc_after, rc_after
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001407 print(file=sys.stderr)
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001408 # These checkers return False on success, True on failure
1409 def check_rc_deltas(deltas):
1410 return any(deltas)
1411 def check_alloc_deltas(deltas):
1412 # At least 1/3rd of 0s
1413 if 3 * deltas.count(0) < len(deltas):
1414 return True
1415 # Nothing else than 1s, 0s and -1s
1416 if not set(deltas) <= {1,0,-1}:
1417 return True
1418 return False
1419 failed = False
1420 for deltas, item_name, checker in [
1421 (rc_deltas, 'references', check_rc_deltas),
1422 (alloc_deltas, 'memory blocks', check_alloc_deltas)]:
1423 if checker(deltas):
1424 msg = '%s leaked %s %s, sum=%s' % (
1425 test, deltas[nwarmup:], item_name, sum(deltas))
1426 print(msg, file=sys.stderr)
1427 sys.stderr.flush()
1428 with open(fname, "a") as refrep:
1429 print(msg, file=refrep)
1430 refrep.flush()
1431 failed = True
1432 return failed
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001433
Benjamin Petersoncf626032014-02-16 14:52:01 -05001434def dash_R_cleanup(fs, ps, pic, zdc, abcs):
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001435 import gc, copyreg
Brett Cannonf4fd9932008-05-10 21:11:46 +00001436 import _strptime, linecache
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001437 import urllib.parse, urllib.request, mimetypes, doctest
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001438 import struct, filecmp, collections.abc
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001439 from distutils.dir_util import _path_created
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001440 from weakref import WeakSet
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001441
Christian Heimesdae2a892008-04-19 00:55:37 +00001442 # Clear the warnings registry, so they can be displayed again
1443 for mod in sys.modules.values():
1444 if hasattr(mod, '__warningregistry__'):
1445 del mod.__warningregistry__
1446
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001447 # Restore some original values.
1448 warnings.filters[:] = fs
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001449 copyreg.dispatch_table.clear()
1450 copyreg.dispatch_table.update(ps)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001451 sys.path_importer_cache.clear()
1452 sys.path_importer_cache.update(pic)
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001453 try:
1454 import zipimport
Brett Cannon260fbe82013-07-04 18:16:15 -04001455 except ImportError:
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001456 pass # Run unmodified on platforms without zipimport support
1457 else:
1458 zipimport._zip_directory_cache.clear()
1459 zipimport._zip_directory_cache.update(zdc)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001460
Christian Heimes26855632008-01-27 23:50:43 +00001461 # clear type cache
Christian Heimes15ebc882008-02-04 18:48:49 +00001462 sys._clear_type_cache()
Christian Heimes26855632008-01-27 23:50:43 +00001463
Guido van Rossum3de862d2007-08-18 00:10:33 +00001464 # Clear ABC registries, restoring previously saved ABC registries.
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001465 for abc in [getattr(collections.abc, a) for a in collections.abc.__all__]:
Christian Heimesbe5b30b2008-03-03 19:18:51 +00001466 if not isabstract(abc):
Christian Heimes941973a2007-11-30 21:53:03 +00001467 continue
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001468 for obj in abc.__subclasses__() + [abc]:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001469 obj._abc_registry = abcs.get(obj, WeakSet()).copy()
Guido van Rossumc1e315d2007-08-20 19:29:24 +00001470 obj._abc_cache.clear()
1471 obj._abc_negative_cache.clear()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001472
Antoine Pitrou046467c2009-10-30 18:30:35 +00001473 # Flush standard output, so that buffered data is sent to the OS and
1474 # associated Python objects are reclaimed.
1475 for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__):
1476 if stream is not None:
1477 stream.flush()
1478
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001479 # Clear assorted module caches.
1480 _path_created.clear()
1481 re.purge()
1482 _strptime._regex_cache.clear()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001483 urllib.parse.clear_cache()
1484 urllib.request.urlcleanup()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001485 linecache.clearcache()
1486 mimetypes._default_mime_types()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001487 filecmp._cache.clear()
Christian Heimesa34706f2008-01-04 03:06:10 +00001488 struct._clearcache()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001489 doctest.master = None
Meador Inge11e38132011-11-25 22:33:32 -06001490 try:
1491 import ctypes
Brett Cannon260fbe82013-07-04 18:16:15 -04001492 except ImportError:
Meador Inge11e38132011-11-25 22:33:32 -06001493 # Don't worry about resetting the cache if ctypes is not supported
1494 pass
1495 else:
1496 ctypes._reset_cache()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001497
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001498 # Collect cyclic trash and read memory statistics immediately after.
1499 func1 = sys.getallocatedblocks
1500 func2 = sys.gettotalrefcount
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001501 gc.collect()
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001502 return func1(), func2()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001503
Stefan Krah5c3ddc82012-08-17 23:09:48 +02001504def warm_caches():
1505 # char cache
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001506 s = bytes(range(256))
1507 for i in range(256):
1508 s[i:i+1]
Stefan Krah5c3ddc82012-08-17 23:09:48 +02001509 # unicode cache
1510 x = [chr(i) for i in range(256)]
1511 # int cache
1512 x = list(range(-5, 257))
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001513
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001514def findtestdir(path=None):
1515 return path or os.path.dirname(__file__) or os.curdir
Guido van Rossum152494a1996-12-20 03:12:20 +00001516
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001517def removepy(names):
1518 if not names:
1519 return
1520 for idx, name in enumerate(names):
1521 basename, ext = os.path.splitext(name)
1522 if ext == '.py':
1523 names[idx] = basename
Tim Petersc5000df2002-06-02 21:42:01 +00001524
Guido van Rossum152494a1996-12-20 03:12:20 +00001525def count(n, word):
1526 if n == 1:
Guido van Rossum41360a41998-03-26 19:42:58 +00001527 return "%d %s" % (n, word)
Guido van Rossum152494a1996-12-20 03:12:20 +00001528 else:
Guido van Rossum41360a41998-03-26 19:42:58 +00001529 return "%d %ss" % (n, word)
Guido van Rossum152494a1996-12-20 03:12:20 +00001530
Tim Petersa45da922001-08-12 03:45:50 +00001531def printlist(x, width=70, indent=4):
Tim Peters7c7efe92002-08-23 17:55:54 +00001532 """Print the elements of iterable x to stdout.
Tim Petersa45da922001-08-12 03:45:50 +00001533
1534 Optional arg width (default 70) is the maximum line length.
1535 Optional arg indent (default 4) is the number of blanks with which to
1536 begin each line.
1537 """
1538
Tim Petersba78bc42002-07-04 19:45:06 +00001539 from textwrap import fill
1540 blanks = ' ' * indent
Florent Xiclunafd1b0932010-03-28 00:25:02 +00001541 # Print the sorted list: 'x' may be a '--random' list or a set()
1542 print(fill(' '.join(str(elt) for elt in sorted(x)), width,
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001543 initial_indent=blanks, subsequent_indent=blanks))
Tim Petersa45da922001-08-12 03:45:50 +00001544
Tim Petersb5b7b782001-08-12 01:20:39 +00001545
Chris Jerdonek517e9252013-02-27 09:02:53 -08001546def main_in_temp_cwd():
1547 """Run main() in a temporary working directory."""
Michael Foord3ab34cc2010-12-03 12:27:40 +00001548 if sysconfig.is_python_build():
Antoine Pitrouee429342011-04-16 18:53:59 +02001549 try:
Michael Foord3ab34cc2010-12-03 12:27:40 +00001550 os.mkdir(TEMPDIR)
Florent Xicluna68f71a32011-10-28 16:06:23 +02001551 except FileExistsError:
1552 pass
Michael Foord3ab34cc2010-12-03 12:27:40 +00001553
1554 # Define a writable temp dir that will be used as cwd while running
1555 # the tests. The name of the dir includes the pid to allow parallel
1556 # testing (see the -j option).
Chris Jerdonek517e9252013-02-27 09:02:53 -08001557 test_cwd = 'test_python_{}'.format(os.getpid())
1558 test_cwd = os.path.join(TEMPDIR, test_cwd)
Michael Foord3ab34cc2010-12-03 12:27:40 +00001559
Chris Jerdonek517e9252013-02-27 09:02:53 -08001560 # Run the tests in a context manager that temporarily changes the CWD to a
1561 # temporary and writable directory. If it's not possible to create or
1562 # change the CWD, the original CWD will be used. The original CWD is
1563 # available from support.SAVEDCWD.
1564 with support.temp_cwd(test_cwd, quiet=True):
1565 main()
1566
Nick Coghlan4c4c0f22010-12-03 07:44:33 +00001567
Guido van Rossum152494a1996-12-20 03:12:20 +00001568if __name__ == '__main__':
Nick Coghlan4c4c0f22010-12-03 07:44:33 +00001569 # Remove regrtest.py's own directory from the module search path. Despite
1570 # the elimination of implicit relative imports, this is still needed to
1571 # ensure that submodules of the test package do not inappropriately appear
1572 # as top-level modules even when people (or buildbots!) invoke regrtest.py
1573 # directly instead of using the -m switch
1574 mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
1575 i = len(sys.path)
1576 while i >= 0:
1577 i -= 1
1578 if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
1579 del sys.path[i]
1580
Florent Xiclunadc69e722010-09-13 16:35:02 +00001581 # findtestdir() gets the dirname out of __file__, so we have to make it
1582 # absolute before changing the working directory.
1583 # For example __file__ may be relative when running trace or profile.
1584 # See issue #9323.
1585 __file__ = os.path.abspath(__file__)
1586
1587 # sanity check
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001588 assert __file__ == os.path.abspath(sys.argv[0])
Ezio Melotti184bdfb2010-02-18 09:37:05 +00001589
Chris Jerdonek517e9252013-02-27 09:02:53 -08001590 main_in_temp_cwd()