blob: 45b454116fe3ece2dae4ec341520a869b61418ac [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
9USAGE = """\
Georg Brandlbe41a482011-01-05 21:47:47 +000010python -m test [options] [test_name1 [test_name2 ...]]
R. David Murray0ba81e02010-04-26 17:02:32 +000011python path/to/Lib/test/regrtest.py [options] [test_name1 [test_name2 ...]]
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -080012"""
Guido van Rossum152494a1996-12-20 03:12:20 +000013
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -080014DESCRIPTION = """\
15Run Python regression tests.
R. David Murray0ba81e02010-04-26 17:02:32 +000016
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
Georg Brandlbe41a482011-01-05 21:47:47 +000024python -E -Wd -m test [options] [test_name1 ...]
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -080025"""
R. David Murray0ba81e02010-04-26 17:02:32 +000026
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -080027EPILOG = """\
28Additional option details:
Guido van Rossumf58ed251997-03-07 21:04:33 +000029
Collin Winterfd12f492009-03-29 04:05:05 +000030-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
R. David Murray0ba81e02010-04-26 17:02:32 +000034-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.
Barry Warsawe11e3de1999-01-28 19:51:51 +000044
Neal Norwitz94fa2ee2008-03-31 02:55:15 +000045-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
Guido van Rossum9e9d4f82002-06-07 15:17:03 +000051-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.
Tim Petersc5000df2002-06-02 21:42:01 +000055
Skip Montanaro0179a182004-06-06 15:53:18 +000056-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
Michael W. Hudson61147f62004-08-03 11:33:28 +000060-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
Neal Norwitz94fa2ee2008-03-31 02:55:15 +000066"reflog.txt" respectively), and the minimal invocation is '-R :'.
Michael W. Hudson61147f62004-08-03 11:33:28 +000067
Thomas Wouters477c8d52006-05-27 19:21:47 +000068-M runs tests that require an exorbitant amount of memory. These tests
69typically try to ascertain containers keep working when containing more than
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000702 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,
Thomas Wouters477c8d52006-05-27 19:21:47 +000073which 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
Guido van Rossum9e9d4f82002-06-07 15:17:03 +000083-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:
Barry Warsaw08fca522001-08-20 22:33:46 +000087
Fred Drake3a15dac2002-04-11 16:39:16 +000088 all - Enable all special resources.
89
Nadeem Vawda3c01d162011-08-01 23:48:26 +020090 none - Disable all special resources (this is the default).
91
Guido van Rossum315aa362003-03-11 14:46:48 +000092 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
Andrew M. Kuchling2158df02001-10-22 15:26:09 +000096 curses - Tests that use curses and will modify the terminal's
97 state and output modes.
Tim Peters1633a2e2001-10-30 05:56:40 +000098
Guido van Rossum9e9d4f82002-06-07 15:17:03 +000099 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.
Barry Warsaw08fca522001-08-20 22:33:46 +0000102
Guido van Rossum9e9d4f82002-06-07 15:17:03 +0000103 network - It is okay to run tests that use external network
104 resource, e.g. testing SSL support for sockets.
Martin v. Löwis1c6b1a22002-11-19 17:47:07 +0000105
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000106 decimal - Test the decimal module against a large suite that
107 verifies compliance with standards.
108
Antoine Pitrou5bc4fa72010-10-14 15:34:31 +0000109 cpu - Used for certain CPU-heavy tests.
Jeremy Hylton4336eda2004-08-07 19:25:33 +0000110
Tim Peterseba28be2005-03-28 01:08:02 +0000111 subprocess Run all tests for the subprocess module.
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000112
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000113 urlfetch - It is okay to download files required on testing.
114
Guilherme Polo9de29af2009-01-28 20:40:48 +0000115 gui - Run tests that require a running GUI.
116
Fred Drake4dd0f7e2002-11-26 21:44:56 +0000117To enable all resources except one, use '-uall,-<resource>'. For
Georg Brandl1158a332009-06-04 09:30:30 +0000118example, to run all the tests except for the gui tests, give the
119option '-uall,-gui'.
Guido van Rossum152494a1996-12-20 03:12:20 +0000120"""
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
Victor Stinner8313d6a2011-06-29 15:22:26 +0200130import logging
Christian Heimesb186d002008-03-18 15:15:01 +0000131import os
Victor Stinner8313d6a2011-06-29 15:22:26 +0200132import platform
Skip Montanaroab1c7912000-06-30 16:39:27 +0000133import random
Thomas Wouters9ada3d62006-04-21 09:47:09 +0000134import re
Éric Araujoff913062011-11-29 16:45:07 +0100135import shutil
Victor Stinnercb41cda2011-07-13 23:47:21 +0200136import signal
Christian Heimesb186d002008-03-18 15:15:01 +0000137import sys
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000138import sysconfig
Victor Stinner8313d6a2011-06-29 15:22:26 +0200139import tempfile
140import time
141import traceback
142import unittest
143import warnings
144from inspect import isabstract
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000145
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200146try:
147 import threading
148except ImportError:
149 threading = None
150try:
151 import multiprocessing.process
152except ImportError:
153 multiprocessing = None
154
Florent Xicluna64fb18e2010-03-06 14:43:34 +0000155
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000156# Some times __path__ and __file__ are not absolute (e.g. while running from
157# Lib/) and, if we change the CWD to run the tests in a temporary dir, some
158# imports might fail. This affects only the modules imported before os.chdir().
159# These modules are searched first in sys.path[0] (so '' -- the CWD) and if
160# they are found in the CWD their __file__ and __path__ will be relative (this
161# happens before the chdir). All the modules imported after the chdir, are
162# not found in the CWD, and since the other paths in sys.path[1:] are absolute
163# (site.py absolutize them), the __file__ and __path__ will be absolute too.
164# Therefore it is necessary to absolutize manually the __file__ and __path__ of
165# the packages to prevent later imports to fail when the CWD is different.
166for module in sys.modules.values():
167 if hasattr(module, '__path__'):
168 module.__path__ = [os.path.abspath(path) for path in module.__path__]
169 if hasattr(module, '__file__'):
170 module.__file__ = os.path.abspath(module.__file__)
171
Guido van Rossumdc15c272002-08-12 21:55:51 +0000172
Guido van Rossumbb484652002-12-02 09:56:21 +0000173# MacOSX (a.k.a. Darwin) has a default stack size that is too small
174# for deeply recursive regular expressions. We see this as crashes in
175# the Python test suite when running test_re.py and test_sre.py. The
176# fix is to set the stack limit to 2048.
177# This approach may also be useful for other Unixy platforms that
178# suffer from small default stack limits.
179if sys.platform == 'darwin':
180 try:
181 import resource
182 except ImportError:
183 pass
184 else:
185 soft, hard = resource.getrlimit(resource.RLIMIT_STACK)
186 newsoft = min(hard, max(soft, 1024*2048))
187 resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
188
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000189# Test result constants.
190PASSED = 1
191FAILED = 0
192ENV_CHANGED = -1
193SKIPPED = -2
194RESOURCE_DENIED = -3
195INTERRUPTED = -4
Victor Stinner4b739882011-03-31 18:02:36 +0200196CHILD_ERROR = -5 # error in a child process
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000197
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000198from test import support
Fred Drake3a15dac2002-04-11 16:39:16 +0000199
Georg Brandl1158a332009-06-04 09:30:30 +0000200RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network',
Antoine Pitrou5bc4fa72010-10-14 15:34:31 +0000201 'decimal', 'cpu', 'subprocess', 'urlfetch', 'gui')
Fred Drake3a15dac2002-04-11 16:39:16 +0000202
Chris Jerdonek517e9252013-02-27 09:02:53 -0800203# When tests are run from the Python build directory, it is best practice
204# to keep the test files in a subfolder. This eases the cleanup of leftover
205# files using the "make distclean" command.
206if sysconfig.is_python_build():
207 TEMPDIR = os.path.join(sysconfig.get_config_var('srcdir'), 'build')
208else:
209 TEMPDIR = tempfile.gettempdir()
210TEMPDIR = os.path.abspath(TEMPDIR)
Fred Drake3a15dac2002-04-11 16:39:16 +0000211
Chris Jerdonek15738422013-01-07 17:07:32 -0800212class _ArgParser(argparse.ArgumentParser):
213
214 def error(self, message):
215 super().error(message + "\nPass -h or --help for complete help.")
216
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -0800217def _create_parser():
218 # Set prog to prevent the uninformative "__main__.py" from displaying in
219 # error messages when using "python -m test ...".
Chris Jerdonek15738422013-01-07 17:07:32 -0800220 parser = _ArgParser(prog='regrtest.py',
221 usage=USAGE,
222 description=DESCRIPTION,
223 epilog=EPILOG,
224 add_help=False,
225 formatter_class=argparse.RawDescriptionHelpFormatter)
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -0800226
227 # Arguments with this clause added to its help are described further in
228 # the epilog's "Additional option details" section.
229 more_details = ' See the section at bottom for more details.'
230
231 group = parser.add_argument_group('General options')
232 # We add help explicitly to control what argument group it renders under.
233 group.add_argument('-h', '--help', action='help',
234 help='show this help message and exit')
235 group.add_argument('--timeout', metavar='TIMEOUT',
236 help='dump the traceback and exit if a test takes '
237 'more than TIMEOUT seconds; disabled if TIMEOUT '
238 'is negative or equals to zero')
239 group.add_argument('--wait', action='store_true', help='wait for user '
240 'input, e.g., allow a debugger to be attached')
241 group.add_argument('--slaveargs', metavar='ARGS')
242 group.add_argument('-S', '--start', metavar='START', help='the name of '
243 'the test at which to start.' + more_details)
244
245 group = parser.add_argument_group('Verbosity')
246 group.add_argument('-v', '--verbose', action='store_true',
247 help='run tests in verbose mode with output to stdout')
248 group.add_argument('-w', '--verbose2', action='store_true',
249 help='re-run failed tests in verbose mode')
250 group.add_argument('-W', '--verbose3', action='store_true',
251 help='display test output on failure')
252 group.add_argument('-d', '--debug', action='store_true',
253 help='print traceback for failed tests')
254 group.add_argument('-q', '--quiet', action='store_true',
255 help='no output unless one or more tests fail')
256 group.add_argument('-o', '--slow', action='store_true',
257 help='print the slowest 10 tests')
258 group.add_argument('--header', action='store_true',
259 help='print header with interpreter info')
260
261 group = parser.add_argument_group('Selecting tests')
262 group.add_argument('-r', '--randomize', action='store_true',
263 help='randomize test execution order.' + more_details)
264 group.add_argument('--randseed', metavar='SEED', help='pass a random seed '
265 'to reproduce a previous random run')
266 group.add_argument('-f', '--fromfile', metavar='FILE', help='read names '
267 'of tests to run from a file.' + more_details)
268 group.add_argument('-x', '--exclude', action='store_true',
269 help='arguments are tests to *exclude*')
270 group.add_argument('-s', '--single', action='store_true', help='single '
271 'step through a set of tests.' + more_details)
272 group.add_argument('-m', '--match', metavar='PAT', help='match test cases '
273 'and methods with glob pattern PAT')
274 group.add_argument('-G', '--failfast', action='store_true', help='fail as '
275 'soon as a test fails (only with -v or -W)')
276 group.add_argument('-u', '--use', metavar='RES1,RES2,...', help='specify '
277 'which special resource intensive tests to run.' +
278 more_details)
279 group.add_argument('-M', '--memlimit', metavar='LIMIT', help='run very '
280 'large memory-consuming tests.' + more_details)
281 group.add_argument('--testdir', metavar='DIR',
282 help='execute test files in the specified directory '
283 '(instead of the Python stdlib test suite)')
284
285 group = parser.add_argument_group('Special runs')
286 group.add_argument('-l', '--findleaks', action='store_true', help='if GC '
287 'is available detect tests that leak memory')
288 group.add_argument('-L', '--runleaks', action='store_true',
289 help='run the leaks(1) command just before exit.' +
290 more_details)
291 group.add_argument('-R', '--huntrleaks', metavar='RUNCOUNTS',
292 help='search for reference leaks (needs debug build, '
293 'very slow).' + more_details)
294 group.add_argument('-j', '--multiprocess', metavar='PROCESSES',
295 help='run PROCESSES processes at once')
296 group.add_argument('-T', '--coverage', action='store_true', help='turn on '
297 'code coverage tracing using the trace module')
298 group.add_argument('-D', '--coverdir', metavar='DIR',
299 help='directory where coverage files are put')
300 group.add_argument('-N', '--nocoverdir', action='store_true',
301 help='put coverage files alongside modules')
302 group.add_argument('-t', '--threshold', metavar='THRESHOLD',
303 help='call gc.set_threshold(THRESHOLD)')
304 group.add_argument('-n', '--nowindows', action='store_true',
305 help='suppress error message boxes on Windows')
306 group.add_argument('-F', '--forever', action='store_true',
307 help='run the specified tests in a loop, until an '
308 'error happens')
309
310 parser.add_argument('args', nargs=argparse.REMAINDER,
311 help=argparse.SUPPRESS)
312
313 return parser
314
Chris Jerdonek15738422013-01-07 17:07:32 -0800315# TODO: remove this function as described in issue #16799, for example.
316# We use this function since regrtest.main() was originally written to use
317# getopt for parsing.
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -0800318def _convert_namespace_to_getopt(ns):
Chris Jerdonek15738422013-01-07 17:07:32 -0800319 """Convert an argparse.Namespace object to a getopt-style opts list.
320
321 The return value of this function mimics the first element of
322 getopt.getopt()'s (opts, args) return value. In addition, the (option,
323 value) pairs in the opts list are sorted by option and use the long
324 option string. The args part of (opts, args) can be mimicked by the
325 args attribute of the Namespace object we are using in regrtest.
326 """
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -0800327 opts = []
328 args_dict = vars(ns)
329 for key in sorted(args_dict.keys()):
330 if key == 'args':
331 continue
332 val = args_dict[key]
333 # Don't continue if val equals '' because this means an option
334 # accepting a value was provided the empty string. Such values should
335 # show up in the returned opts list.
336 if val is None or val is False:
337 continue
338 if val is True:
339 # Then an option with action store_true was passed. getopt
340 # includes these with value '' in the opts list.
341 val = ''
342 opts.append(('--' + key, val))
Chris Jerdonek15738422013-01-07 17:07:32 -0800343 return opts
Barry Warsaw08fca522001-08-20 22:33:46 +0000344
345
Antoine Pitrou88909542009-06-29 13:54:42 +0000346def main(tests=None, testdir=None, verbose=0, quiet=False,
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000347 exclude=False, single=False, randomize=False, fromfile=None,
Walter Dörwaldaee4da62004-11-12 18:51:27 +0000348 findleaks=False, use_resources=None, trace=False, coverdir='coverage',
Collin Winterfd12f492009-03-29 04:05:05 +0000349 runleaks=False, huntrleaks=False, verbose2=False, print_slow=False,
Antoine Pitrou3c4402f2011-01-03 20:38:52 +0000350 random_seed=None, use_mp=None, verbose3=False, forever=False,
Antoine Pitroub9c73e82011-07-29 23:53:38 +0200351 header=False, failfast=False, match_tests=None):
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000352 """Execute a test suite.
353
Thomas Wouters7e474022000-07-16 12:04:32 +0000354 This also parses command-line options and modifies its behavior
Fred Drake004d5e62000-10-23 17:22:08 +0000355 accordingly.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000356
357 tests -- a list of strings containing test names (optional)
358 testdir -- the directory in which to look for tests (optional)
359
360 Users other than the Python test suite will certainly want to
361 specify testdir; if it's omitted, the directory containing the
Fred Drake004d5e62000-10-23 17:22:08 +0000362 Python test suite is searched for.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000363
364 If the tests argument is omitted, the tests listed on the
365 command-line will be used. If that's empty, too, then all *.py
366 files beginning with test_ will be used.
Skip Montanaroab1c7912000-06-30 16:39:27 +0000367
Antoine Pitrou88909542009-06-29 13:54:42 +0000368 The other default arguments (verbose, quiet, exclude,
Collin Winterfd12f492009-03-29 04:05:05 +0000369 single, randomize, findleaks, use_resources, trace, coverdir,
370 print_slow, and random_seed) allow programmers calling main()
371 directly to set the values that would normally be set by flags
372 on the command line.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000373 """
Victor Stinner3c18f252011-05-22 15:27:14 +0200374
Victor Stinnercb41cda2011-07-13 23:47:21 +0200375 # Display the Python traceback on fatal errors (e.g. segfault)
Victor Stinner3c18f252011-05-22 15:27:14 +0200376 faulthandler.enable(all_threads=True)
377
Victor Stinnercb41cda2011-07-13 23:47:21 +0200378 # Display the Python traceback on SIGALRM or SIGUSR1 signal
379 signals = []
380 if hasattr(signal, 'SIGALRM'):
381 signals.append(signal.SIGALRM)
382 if hasattr(signal, 'SIGUSR1'):
383 signals.append(signal.SIGUSR1)
384 for signum in signals:
385 faulthandler.register(signum, chain=True)
386
Victor Stinner1802d3f2010-05-19 17:11:19 +0000387 replace_stdout()
388
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000389 support.record_original_stdout(sys.stdout)
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -0800390
Chris Jerdonek15738422013-01-07 17:07:32 -0800391 parser = _create_parser()
392 ns = parser.parse_args()
393 opts = _convert_namespace_to_getopt(ns)
394 args = ns.args
395 usage = parser.error
Barry Warsaw08fca522001-08-20 22:33:46 +0000396
397 # Defaults
Collin Winterfd12f492009-03-29 04:05:05 +0000398 if random_seed is None:
399 random_seed = random.randrange(10000000)
Barry Warsaw08fca522001-08-20 22:33:46 +0000400 if use_resources is None:
401 use_resources = []
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000402 debug = False
403 start = None
Victor Stinner30196882011-06-03 12:53:26 +0200404 timeout = None
Guido van Rossum152494a1996-12-20 03:12:20 +0000405 for o, a in opts:
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -0800406 if o in ('-v', '--verbose'):
Barry Warsaw08fca522001-08-20 22:33:46 +0000407 verbose += 1
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000408 elif o in ('-w', '--verbose2'):
409 verbose2 = True
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000410 elif o in ('-d', '--debug'):
411 debug = True
Georg Brandl96f78972009-10-27 21:02:11 +0000412 elif o in ('-W', '--verbose3'):
413 verbose3 = True
Antoine Pitrou216a3bc2011-07-23 22:33:39 +0200414 elif o in ('-G', '--failfast'):
415 failfast = True
Barry Warsaw08fca522001-08-20 22:33:46 +0000416 elif o in ('-q', '--quiet'):
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000417 quiet = True;
Barry Warsaw08fca522001-08-20 22:33:46 +0000418 verbose = 0
Barry Warsaw08fca522001-08-20 22:33:46 +0000419 elif o in ('-x', '--exclude'):
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000420 exclude = True
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000421 elif o in ('-S', '--start'):
422 start = a
Barry Warsaw08fca522001-08-20 22:33:46 +0000423 elif o in ('-s', '--single'):
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000424 single = True
Senthil Kumaranbcfe56d2012-01-14 18:26:27 +0800425 elif o in ('-o', '--slow'):
Christian Heimesb186d002008-03-18 15:15:01 +0000426 print_slow = True
Barry Warsaw08fca522001-08-20 22:33:46 +0000427 elif o in ('-r', '--randomize'):
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000428 randomize = True
Collin Winterfd12f492009-03-29 04:05:05 +0000429 elif o == '--randseed':
430 random_seed = int(a)
Tim Petersc5000df2002-06-02 21:42:01 +0000431 elif o in ('-f', '--fromfile'):
432 fromfile = a
Antoine Pitroub9c73e82011-07-29 23:53:38 +0200433 elif o in ('-m', '--match'):
434 match_tests = a
Barry Warsaw08fca522001-08-20 22:33:46 +0000435 elif o in ('-l', '--findleaks'):
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000436 findleaks = True
Skip Montanaro0179a182004-06-06 15:53:18 +0000437 elif o in ('-L', '--runleaks'):
438 runleaks = True
Guido van Rossum9e9d4f82002-06-07 15:17:03 +0000439 elif o in ('-t', '--threshold'):
440 import gc
441 gc.set_threshold(int(a))
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000442 elif o in ('-T', '--coverage'):
443 trace = True
Walter Dörwaldaee4da62004-11-12 18:51:27 +0000444 elif o in ('-D', '--coverdir'):
R David Murray03504fc2011-03-24 14:35:30 -0400445 # CWD is replaced with a temporary dir before calling main(), so we
446 # need join it with the saved CWD so it goes where the user expects.
447 coverdir = os.path.join(support.SAVEDCWD, a)
Walter Dörwaldaee4da62004-11-12 18:51:27 +0000448 elif o in ('-N', '--nocoverdir'):
449 coverdir = None
Michael W. Hudson61147f62004-08-03 11:33:28 +0000450 elif o in ('-R', '--huntrleaks'):
451 huntrleaks = a.split(':')
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000452 if len(huntrleaks) not in (2, 3):
453 print(a, huntrleaks)
454 usage('-R takes 2 or 3 colon-separated arguments')
455 if not huntrleaks[0]:
Michael W. Hudson61147f62004-08-03 11:33:28 +0000456 huntrleaks[0] = 5
457 else:
458 huntrleaks[0] = int(huntrleaks[0])
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000459 if not huntrleaks[1]:
Michael W. Hudson61147f62004-08-03 11:33:28 +0000460 huntrleaks[1] = 4
461 else:
462 huntrleaks[1] = int(huntrleaks[1])
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000463 if len(huntrleaks) == 2 or not huntrleaks[2]:
464 huntrleaks[2:] = ["reflog.txt"]
Stefan Krah5c3ddc82012-08-17 23:09:48 +0200465 # Avoid false positives due to various caches
466 # filling slowly with random data:
467 warm_caches()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000468 elif o in ('-M', '--memlimit'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000469 support.set_memlimit(a)
Barry Warsaw08fca522001-08-20 22:33:46 +0000470 elif o in ('-u', '--use'):
Guido van Rossumfe3f6962001-09-06 16:09:41 +0000471 u = [x.lower() for x in a.split(',')]
472 for r in u:
Fred Drake3a15dac2002-04-11 16:39:16 +0000473 if r == 'all':
Fred Drake4dd0f7e2002-11-26 21:44:56 +0000474 use_resources[:] = RESOURCE_NAMES
475 continue
Nadeem Vawda3c01d162011-08-01 23:48:26 +0200476 if r == 'none':
477 del use_resources[:]
478 continue
Fred Drake4dd0f7e2002-11-26 21:44:56 +0000479 remove = False
480 if r[0] == '-':
481 remove = True
482 r = r[1:]
Fred Drake3a15dac2002-04-11 16:39:16 +0000483 if r not in RESOURCE_NAMES:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000484 usage('Invalid -u/--use option: ' + a)
Fred Drake4dd0f7e2002-11-26 21:44:56 +0000485 if remove:
486 if r in use_resources:
487 use_resources.remove(r)
488 elif r not in use_resources:
Andrew MacIntyree41abab2002-04-30 12:11:04 +0000489 use_resources.append(r)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000490 elif o in ('-n', '--nowindows'):
491 import msvcrt
492 msvcrt.SetErrorMode(msvcrt.SEM_FAILCRITICALERRORS|
493 msvcrt.SEM_NOALIGNMENTFAULTEXCEPT|
494 msvcrt.SEM_NOGPFAULTERRORBOX|
495 msvcrt.SEM_NOOPENFILEERRORBOX)
496 try:
497 msvcrt.CrtSetReportMode
498 except AttributeError:
499 # release build
500 pass
501 else:
502 for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]:
503 msvcrt.CrtSetReportMode(m, msvcrt.CRTDBG_MODE_FILE)
504 msvcrt.CrtSetReportFile(m, msvcrt.CRTDBG_FILE_STDERR)
R. David Murray7dc72cc2009-11-14 16:13:02 +0000505 elif o in ('-F', '--forever'):
506 forever = True
Antoine Pitrou88909542009-06-29 13:54:42 +0000507 elif o in ('-j', '--multiprocess'):
508 use_mp = int(a)
Antoine Pitrou6ab79d92011-03-23 20:17:45 +0100509 if use_mp <= 0:
510 try:
511 import multiprocessing
512 # Use all cores + extras for tests that like to sleep
513 use_mp = 2 + multiprocessing.cpu_count()
514 except (ImportError, NotImplementedError):
515 use_mp = 3
Nadeem Vawda3c01d162011-08-01 23:48:26 +0200516 if use_mp == 1:
517 use_mp = None
Antoine Pitrou3c4402f2011-01-03 20:38:52 +0000518 elif o == '--header':
519 header = True
Antoine Pitrou88909542009-06-29 13:54:42 +0000520 elif o == '--slaveargs':
521 args, kwargs = json.loads(a)
522 try:
523 result = runtest(*args, **kwargs)
Victor Stinner29650112012-08-08 22:37:26 +0200524 except KeyboardInterrupt:
525 result = INTERRUPTED, ''
Antoine Pitrou88909542009-06-29 13:54:42 +0000526 except BaseException as e:
Victor Stinner29650112012-08-08 22:37:26 +0200527 traceback.print_exc()
528 result = CHILD_ERROR, str(e)
Antoine Pitrou88909542009-06-29 13:54:42 +0000529 sys.stdout.flush()
530 print() # Force a newline (just in case)
531 print(json.dumps(result))
532 sys.exit(0)
R David Murrayb588f8d2011-03-24 14:42:58 -0400533 elif o == '--testdir':
534 # CWD is replaced with a temporary dir before calling main(), so we
535 # join it with the saved CWD so it ends up where the user expects.
536 testdir = os.path.join(support.SAVEDCWD, a)
Victor Stinner0cc8d592011-03-31 18:10:13 +0200537 elif o == '--timeout':
Victor Stinner88345682011-06-06 12:14:23 +0200538 if hasattr(faulthandler, 'dump_tracebacks_later'):
539 timeout = float(a)
540 if timeout <= 0:
541 timeout = None
542 else:
543 print("Warning: The timeout option requires "
544 "faulthandler.dump_tracebacks_later")
Victor Stinner9e586c22011-06-06 12:04:36 +0200545 timeout = None
Brian Curtinf6643452011-04-28 17:45:17 -0500546 elif o == '--wait':
547 input("Press any key to continue...")
R. David Murray35768ad2009-11-15 00:23:21 +0000548 else:
549 print(("No handler for option {}. Please report this as a bug "
Georg Brandldee7b852010-08-02 18:59:52 +0000550 "at http://bugs.python.org.").format(o), file=sys.stderr)
R. David Murray35768ad2009-11-15 00:23:21 +0000551 sys.exit(1)
Tim Petersc5000df2002-06-02 21:42:01 +0000552 if single and fromfile:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000553 usage("-s and -f don't go together!")
Antoine Pitrou88909542009-06-29 13:54:42 +0000554 if use_mp and trace:
Florent Xicluna64fb18e2010-03-06 14:43:34 +0000555 usage("-T and -j don't go together!")
Antoine Pitrou88909542009-06-29 13:54:42 +0000556 if use_mp and findleaks:
Florent Xicluna64fb18e2010-03-06 14:43:34 +0000557 usage("-l and -j don't go together!")
Nadeem Vawdac1fba3e2011-08-27 15:22:05 +0200558 if use_mp and support.max_memuse:
559 usage("-M and -j don't go together!")
Antoine Pitrou216a3bc2011-07-23 22:33:39 +0200560 if failfast and not (verbose or verbose3):
561 usage("-G/--failfast needs either -v or -W")
Barry Warsaw08fca522001-08-20 22:33:46 +0000562
Guido van Rossum152494a1996-12-20 03:12:20 +0000563 good = []
564 bad = []
565 skipped = []
Fred Drake9a0db072003-02-03 15:19:30 +0000566 resource_denieds = []
Nick Coghlan6ead5522009-10-18 13:19:33 +0000567 environment_changed = []
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000568 interrupted = False
Barry Warsawe11e3de1999-01-28 19:51:51 +0000569
Neil Schemenauerd569f232000-09-22 15:29:28 +0000570 if findleaks:
Barry Warsawa873b032000-08-03 15:50:37 +0000571 try:
572 import gc
573 except ImportError:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000574 print('No GC available, disabling findleaks.')
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000575 findleaks = False
Barry Warsawa873b032000-08-03 15:50:37 +0000576 else:
Neil Schemenauer8a00abc2000-10-13 01:32:42 +0000577 # Uncomment the line below to report garbage that is not
578 # freeable by reference counting alone. By default only
579 # garbage that is not collectable by the GC is reported.
580 #gc.set_debug(gc.DEBUG_SAVEALL)
Neil Schemenauerd569f232000-09-22 15:29:28 +0000581 found_garbage = []
Barry Warsawa873b032000-08-03 15:50:37 +0000582
Barry Warsawe11e3de1999-01-28 19:51:51 +0000583 if single:
Florent Xiclunaec882212010-08-09 16:56:43 +0000584 filename = os.path.join(TEMPDIR, 'pynexttest')
Barry Warsawe11e3de1999-01-28 19:51:51 +0000585 try:
586 fp = open(filename, 'r')
R. David Murray7dc72cc2009-11-14 16:13:02 +0000587 next_test = fp.read().strip()
588 tests = [next_test]
Barry Warsawe11e3de1999-01-28 19:51:51 +0000589 fp.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200590 except OSError:
Barry Warsawe11e3de1999-01-28 19:51:51 +0000591 pass
Tim Petersc5000df2002-06-02 21:42:01 +0000592
593 if fromfile:
594 tests = []
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000595 fp = open(os.path.join(support.SAVEDCWD, fromfile))
Antoine Pitroud95c7b52010-11-07 20:50:51 +0000596 count_pat = re.compile(r'\[\s*\d+/\s*\d+\]')
Tim Petersc5000df2002-06-02 21:42:01 +0000597 for line in fp:
Antoine Pitroud95c7b52010-11-07 20:50:51 +0000598 line = count_pat.sub('', line)
Tim Petersc5000df2002-06-02 21:42:01 +0000599 guts = line.split() # assuming no test has whitespace in its name
600 if guts and not guts[0].startswith('#'):
601 tests.extend(guts)
602 fp.close()
603
604 # Strip .py extensions.
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000605 removepy(args)
606 removepy(tests)
Tim Petersc5000df2002-06-02 21:42:01 +0000607
Guido van Rossum6c74fea1998-08-25 12:29:08 +0000608 stdtests = STDTESTS[:]
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000609 nottests = NOTTESTS.copy()
Guido van Rossum152494a1996-12-20 03:12:20 +0000610 if exclude:
Guido van Rossum6c74fea1998-08-25 12:29:08 +0000611 for arg in args:
612 if arg in stdtests:
613 stdtests.remove(arg)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000614 nottests.add(arg)
Guido van Rossum41360a41998-03-26 19:42:58 +0000615 args = []
Florent Xicluna0e62a142010-03-06 17:34:48 +0000616
617 # For a partial run, we do not need to clutter the output.
Antoine Pitrou3c4402f2011-01-03 20:38:52 +0000618 if verbose or header or not (quiet or single or tests or args):
Florent Xicluna0e62a142010-03-06 17:34:48 +0000619 # Print basic platform information
620 print("==", platform.python_implementation(), *sys.version.split())
Florent Xiclunaec882212010-08-09 16:56:43 +0000621 print("== ", platform.platform(aliased=True),
622 "%s-endian" % sys.byteorder)
Florent Xicluna0e62a142010-03-06 17:34:48 +0000623 print("== ", os.getcwd())
Antoine Pitrou3c4402f2011-01-03 20:38:52 +0000624 print("Testing with flags:", sys.flags)
Florent Xicluna0e62a142010-03-06 17:34:48 +0000625
R David Murrayb588f8d2011-03-24 14:42:58 -0400626 # if testdir is set, then we are not running the python tests suite, so
627 # don't add default tests to be executed or skipped (pass empty values)
628 if testdir:
629 alltests = findtests(testdir, list(), set())
630 else:
631 alltests = findtests(testdir, stdtests, nottests)
632
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000633 selected = tests or args or alltests
Barry Warsawe11e3de1999-01-28 19:51:51 +0000634 if single:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000635 selected = selected[:1]
R. David Murrayef1992b2009-12-16 15:19:27 +0000636 try:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000637 next_single_test = alltests[alltests.index(selected[0])+1]
R. David Murrayef1992b2009-12-16 15:19:27 +0000638 except IndexError:
639 next_single_test = None
R David Murrayc3bf78a2012-10-27 17:07:05 -0400640 # Remove all the selected tests that precede start if it's set.
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000641 if start:
642 try:
R David Murrayc3bf78a2012-10-27 17:07:05 -0400643 del selected[:selected.index(start)]
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000644 except ValueError:
645 print("Couldn't find starting test (%s), using all tests" % start)
Skip Montanaroab1c7912000-06-30 16:39:27 +0000646 if randomize:
Collin Winterfd12f492009-03-29 04:05:05 +0000647 random.seed(random_seed)
648 print("Using random seed", random_seed)
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000649 random.shuffle(selected)
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000650 if trace:
Georg Brandl33c28812009-04-01 23:07:29 +0000651 import trace, tempfile
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100652 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,
Georg Brandl33c28812009-04-01 23:07:29 +0000653 tempfile.gettempdir()],
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000654 trace=False, count=True)
R. David Murray7dc72cc2009-11-14 16:13:02 +0000655
Christian Heimesb186d002008-03-18 15:15:01 +0000656 test_times = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000657 support.verbose = verbose # Tell tests to be moderately quiet
658 support.use_resources = use_resources
Guido van Rossum5796d262000-04-21 21:35:06 +0000659 save_modules = sys.modules.keys()
Antoine Pitrou88909542009-06-29 13:54:42 +0000660
661 def accumulate_result(test, result):
662 ok, test_time = result
663 test_times.append((test_time, test))
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000664 if ok == PASSED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000665 good.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000666 elif ok == FAILED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000667 bad.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000668 elif ok == ENV_CHANGED:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000669 environment_changed.append(test)
670 elif ok == SKIPPED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000671 skipped.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000672 elif ok == RESOURCE_DENIED:
673 skipped.append(test)
674 resource_denieds.append(test)
Antoine Pitrou88909542009-06-29 13:54:42 +0000675
R. David Murray7dc72cc2009-11-14 16:13:02 +0000676 if forever:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000677 def test_forever(tests=list(selected)):
R. David Murray7dc72cc2009-11-14 16:13:02 +0000678 while True:
679 for test in tests:
680 yield test
681 if bad:
682 return
683 tests = test_forever()
Georg Brandle8e02e32010-08-03 07:56:50 +0000684 test_count = ''
685 test_count_width = 3
R. David Murray7dc72cc2009-11-14 16:13:02 +0000686 else:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000687 tests = iter(selected)
Georg Brandle8e02e32010-08-03 07:56:50 +0000688 test_count = '/{}'.format(len(selected))
689 test_count_width = len(test_count) - 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000690
Antoine Pitrou88909542009-06-29 13:54:42 +0000691 if use_mp:
Victor Stinner45df8202010-04-28 22:31:17 +0000692 try:
693 from threading import Thread
694 except ImportError:
695 print("Multiprocess option requires thread support")
696 sys.exit(2)
Georg Brandl1b37e872010-03-14 10:45:50 +0000697 from queue import Queue
698 from subprocess import Popen, PIPE
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100699 debug_output_pat = re.compile(r"\[\d+ refs, \d+ blocks\]$")
Antoine Pitrou88909542009-06-29 13:54:42 +0000700 output = Queue()
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200701 pending = MultiprocessTests(tests)
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +0000702 opt_args = support.args_from_interpreter_flags()
703 base_cmd = [sys.executable] + opt_args + ['-m', 'test.regrtest']
Antoine Pitrou88909542009-06-29 13:54:42 +0000704 def work():
705 # A worker thread.
Neal Norwitz14ca3272006-02-28 18:05:43 +0000706 try:
Antoine Pitrou88909542009-06-29 13:54:42 +0000707 while True:
708 try:
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200709 test = next(pending)
R. David Murray7dc72cc2009-11-14 16:13:02 +0000710 except StopIteration:
R. David Murray27144602009-10-19 15:26:16 +0000711 output.put((None, None, None, None))
Antoine Pitrou88909542009-06-29 13:54:42 +0000712 return
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200713 args_tuple = (
714 (test, verbose, quiet),
715 dict(huntrleaks=huntrleaks, use_resources=use_resources,
716 debug=debug, output_on_failure=verbose3,
Antoine Pitrou0b9e7b92012-07-26 00:47:15 +0200717 timeout=timeout, failfast=failfast,
718 match_tests=match_tests)
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200719 )
Antoine Pitrou88909542009-06-29 13:54:42 +0000720 # -E is needed by some tests, e.g. test_import
Antoine Pitrou282083d2012-07-11 19:19:14 +0200721 # Running the child from the same working directory ensures
722 # that TEMPDIR for the child is the same when
723 # sysconfig.is_python_build() is true. See issue 15300.
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +0000724 popen = Popen(base_cmd + ['--slaveargs', json.dumps(args_tuple)],
R. David Murray27144602009-10-19 15:26:16 +0000725 stdout=PIPE, stderr=PIPE,
Antoine Pitrou36e778e2010-08-18 20:44:14 +0000726 universal_newlines=True,
Antoine Pitrou282083d2012-07-11 19:19:14 +0200727 close_fds=(os.name != 'nt'),
728 cwd=support.SAVEDCWD)
R. David Murray27144602009-10-19 15:26:16 +0000729 stdout, stderr = popen.communicate()
Victor Stinner4b739882011-03-31 18:02:36 +0200730 retcode = popen.wait()
R. David Murray27144602009-10-19 15:26:16 +0000731 # Strip last refcount output line if it exists, since it
732 # comes from the shutdown of the interpreter in the subcommand.
733 stderr = debug_output_pat.sub("", stderr)
734 stdout, _, result = stdout.strip().rpartition("\n")
Victor Stinner4b739882011-03-31 18:02:36 +0200735 if retcode != 0:
736 result = (CHILD_ERROR, "Exit code %s" % retcode)
737 output.put((test, stdout.rstrip(), stderr.rstrip(), result))
738 return
R. David Murray7dc72cc2009-11-14 16:13:02 +0000739 if not result:
740 output.put((None, None, None, None))
741 return
Antoine Pitrou88909542009-06-29 13:54:42 +0000742 result = json.loads(result)
R. David Murray27144602009-10-19 15:26:16 +0000743 output.put((test, stdout.rstrip(), stderr.rstrip(), result))
Antoine Pitrou88909542009-06-29 13:54:42 +0000744 except BaseException:
R. David Murray27144602009-10-19 15:26:16 +0000745 output.put((None, None, None, None))
Neal Norwitz14ca3272006-02-28 18:05:43 +0000746 raise
Antoine Pitrou88909542009-06-29 13:54:42 +0000747 workers = [Thread(target=work) for i in range(use_mp)]
748 for worker in workers:
749 worker.start()
750 finished = 0
Georg Brandldee7b852010-08-02 18:59:52 +0000751 test_index = 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000752 try:
753 while finished < use_mp:
754 test, stdout, stderr, result = output.get()
755 if test is None:
756 finished += 1
757 continue
Victor Stinnera2a895c2011-05-23 23:14:05 +0200758 accumulate_result(test, result)
Georg Brandldee7b852010-08-02 18:59:52 +0000759 if not quiet:
Ezio Melotti84f75c62011-05-24 01:00:10 +0300760 fmt = "[{1:{0}}{2}/{3}] {4}" if bad else "[{1:{0}}{2}] {4}"
761 print(fmt.format(
Victor Stinnera2a895c2011-05-23 23:14:05 +0200762 test_count_width, test_index, test_count,
763 len(bad), test))
R. David Murray7dc72cc2009-11-14 16:13:02 +0000764 if stdout:
765 print(stdout)
766 if stderr:
767 print(stderr, file=sys.stderr)
Antoine Pitrou82372582012-06-27 17:41:07 +0200768 sys.stdout.flush()
769 sys.stderr.flush()
R. David Murray7dc72cc2009-11-14 16:13:02 +0000770 if result[0] == INTERRUPTED:
Victor Stinner29650112012-08-08 22:37:26 +0200771 raise KeyboardInterrupt
Victor Stinner4b739882011-03-31 18:02:36 +0200772 if result[0] == CHILD_ERROR:
Victor Stinner571e8fd2011-05-01 22:57:43 +0200773 raise Exception("Child error on {}: {}".format(test, result[1]))
Georg Brandldee7b852010-08-02 18:59:52 +0000774 test_index += 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000775 except KeyboardInterrupt:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000776 interrupted = True
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200777 pending.interrupted = True
Antoine Pitrou88909542009-06-29 13:54:42 +0000778 for worker in workers:
779 worker.join()
780 else:
Georg Brandldee7b852010-08-02 18:59:52 +0000781 for test_index, test in enumerate(tests, 1):
Antoine Pitrou88909542009-06-29 13:54:42 +0000782 if not quiet:
Ezio Melotti84f75c62011-05-24 01:00:10 +0300783 fmt = "[{1:{0}}{2}/{3}] {4}" if bad else "[{1:{0}}{2}] {4}"
784 print(fmt.format(
Victor Stinnera2a895c2011-05-23 23:14:05 +0200785 test_count_width, test_index, test_count, len(bad), test))
Antoine Pitrou88909542009-06-29 13:54:42 +0000786 sys.stdout.flush()
787 if trace:
788 # If we're tracing code coverage, then we don't exit with status
789 # if on a false return value from main.
Victor Stinner0cc8d592011-03-31 18:10:13 +0200790 tracer.runctx('runtest(test, verbose, quiet, timeout=timeout)',
Antoine Pitrou88909542009-06-29 13:54:42 +0000791 globals=globals(), locals=vars())
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000792 else:
Antoine Pitrou88909542009-06-29 13:54:42 +0000793 try:
Antoine Pitrou293954d2011-03-23 23:01:49 +0100794 result = runtest(test, verbose, quiet, huntrleaks, debug,
Antoine Pitrou216a3bc2011-07-23 22:33:39 +0200795 output_on_failure=verbose3,
Antoine Pitrouf83e4ac2011-07-29 23:57:10 +0200796 timeout=timeout, failfast=failfast,
797 match_tests=match_tests)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000798 accumulate_result(test, result)
Antoine Pitrou88909542009-06-29 13:54:42 +0000799 except KeyboardInterrupt:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000800 interrupted = True
Antoine Pitrou88909542009-06-29 13:54:42 +0000801 break
802 except:
803 raise
804 if findleaks:
805 gc.collect()
806 if gc.garbage:
807 print("Warning: test created", len(gc.garbage), end=' ')
808 print("uncollectable object(s).")
809 # move the uncollectable objects somewhere so we don't see
810 # them again
811 found_garbage.extend(gc.garbage)
812 del gc.garbage[:]
813 # Unload the newly imported modules (best effort finalization)
814 for module in sys.modules.keys():
815 if module not in save_modules and module.startswith("test."):
816 support.unload(module)
Jeremy Hylton7a1ea0e2001-10-17 13:45:28 +0000817
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000818 if interrupted:
819 # print a newline after ^C
820 print()
821 print("Test suite interrupted by signal SIGINT.")
822 omitted = set(selected) - set(good) - set(bad) - set(skipped)
823 print(count(len(omitted), "test"), "omitted:")
824 printlist(omitted)
Guido van Rossum152494a1996-12-20 03:12:20 +0000825 if good and not quiet:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000826 if not bad and not skipped and not interrupted and len(good) > 1:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000827 print("All", end=' ')
828 print(count(len(good), "test"), "OK.")
Christian Heimesb186d002008-03-18 15:15:01 +0000829 if print_slow:
830 test_times.sort(reverse=True)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000831 print("10 slowest tests:")
Christian Heimesb186d002008-03-18 15:15:01 +0000832 for time, test in test_times[:10]:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000833 print("%s: %.1fs" % (test, time))
Guido van Rossum152494a1996-12-20 03:12:20 +0000834 if bad:
Nick Coghlan6ead5522009-10-18 13:19:33 +0000835 bad = sorted(set(bad) - set(environment_changed))
836 if bad:
837 print(count(len(bad), "test"), "failed:")
838 printlist(bad)
Vinay Sajipf9596182012-03-02 01:01:13 +0000839 if environment_changed:
840 print("{} altered the execution environment:".format(
841 count(len(environment_changed), "test")))
842 printlist(environment_changed)
Guido van Rossum152494a1996-12-20 03:12:20 +0000843 if skipped and not quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000844 print(count(len(skipped), "test"), "skipped:")
Tim Petersa45da922001-08-12 03:45:50 +0000845 printlist(skipped)
Barry Warsawe11e3de1999-01-28 19:51:51 +0000846
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000847 if verbose2 and bad:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000848 print("Re-running failed tests in verbose mode")
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000849 for test in bad:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000850 print("Re-running test %r in verbose mode" % test)
Tim Peters922dd7d2006-03-10 23:37:10 +0000851 sys.stdout.flush()
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000852 try:
Antoine Pitrou88909542009-06-29 13:54:42 +0000853 verbose = True
Victor Stinner0cc8d592011-03-31 18:10:13 +0200854 ok = runtest(test, True, quiet, huntrleaks, debug, timeout=timeout)
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000855 except KeyboardInterrupt:
856 # print a newline separate from the ^C
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000857 print()
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000858 break
859 except:
860 raise
861
Barry Warsawe11e3de1999-01-28 19:51:51 +0000862 if single:
R. David Murrayef1992b2009-12-16 15:19:27 +0000863 if next_single_test:
864 with open(filename, 'w') as fp:
865 fp.write(next_single_test + '\n')
Barry Warsawe11e3de1999-01-28 19:51:51 +0000866 else:
867 os.unlink(filename)
868
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000869 if trace:
870 r = tracer.results()
871 r.write_results(show_missing=True, summary=True, coverdir=coverdir)
872
Skip Montanaro0179a182004-06-06 15:53:18 +0000873 if runleaks:
874 os.system("leaks %d" % os.getpid())
875
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000876 sys.exit(len(bad) > 0 or interrupted)
Barry Warsaw08fca522001-08-20 22:33:46 +0000877
Guido van Rossum152494a1996-12-20 03:12:20 +0000878
R David Murrayb588f8d2011-03-24 14:42:58 -0400879# small set of tests to determine if we have a basically functioning interpreter
880# (i.e. if any of these fail, then anything else is likely to follow)
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000881STDTESTS = [
Guido van Rossum152494a1996-12-20 03:12:20 +0000882 'test_grammar',
883 'test_opcodes',
Guido van Rossumd8faa362007-04-27 19:54:29 +0000884 'test_dict',
Guido van Rossum152494a1996-12-20 03:12:20 +0000885 'test_builtin',
886 'test_exceptions',
887 'test_types',
Collin Winter7afaa882007-03-08 19:54:43 +0000888 'test_unittest',
889 'test_doctest',
890 'test_doctest2',
Eli Benderskyd18a0472011-07-27 20:21:45 +0300891 'test_support'
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000892]
Guido van Rossum152494a1996-12-20 03:12:20 +0000893
R David Murrayb588f8d2011-03-24 14:42:58 -0400894# set of tests that we don't want to be executed when using regrtest
R David Murray57648302011-03-24 14:57:05 -0400895NOTTESTS = set()
Guido van Rossum152494a1996-12-20 03:12:20 +0000896
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000897def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
Guido van Rossum152494a1996-12-20 03:12:20 +0000898 """Return a list of all applicable test modules."""
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000899 testdir = findtestdir(testdir)
Guido van Rossum152494a1996-12-20 03:12:20 +0000900 names = os.listdir(testdir)
901 tests = []
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000902 others = set(stdtests) | nottests
Guido van Rossum152494a1996-12-20 03:12:20 +0000903 for name in names:
R David Murray661720e2011-03-21 15:14:34 -0400904 mod, ext = os.path.splitext(name)
905 if mod[:5] == "test_" and ext in (".py", "") and mod not in others:
906 tests.append(mod)
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000907 return stdtests + sorted(tests)
Guido van Rossum152494a1996-12-20 03:12:20 +0000908
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200909# We do not use a generator so multiple threads can call next().
910class MultiprocessTests(object):
911
912 """A thread-safe iterator over tests for multiprocess mode."""
913
914 def __init__(self, tests):
915 self.interrupted = False
916 self.lock = threading.Lock()
917 self.tests = tests
918
919 def __iter__(self):
920 return self
921
922 def __next__(self):
923 with self.lock:
924 if self.interrupted:
925 raise StopIteration('tests interrupted')
926 return next(self.tests)
927
Victor Stinnerf58087b2010-05-02 17:24:51 +0000928def replace_stdout():
929 """Set stdout encoder error handler to backslashreplace (as stderr error
930 handler) to avoid UnicodeEncodeError when printing a traceback"""
Victor Stinner4b2b43d2011-01-05 03:54:26 +0000931 import atexit
932
Victor Stinnerf58087b2010-05-02 17:24:51 +0000933 stdout = sys.stdout
934 sys.stdout = open(stdout.fileno(), 'w',
935 encoding=stdout.encoding,
Victor Stinner4b2b43d2011-01-05 03:54:26 +0000936 errors="backslashreplace",
Victor Stinnerbe621032011-05-25 02:01:55 +0200937 closefd=False,
938 newline='\n')
Victor Stinner4b2b43d2011-01-05 03:54:26 +0000939
940 def restore_stdout():
941 sys.stdout.close()
942 sys.stdout = stdout
943 atexit.register(restore_stdout)
Victor Stinnerf58087b2010-05-02 17:24:51 +0000944
Antoine Pitrou88909542009-06-29 13:54:42 +0000945def runtest(test, verbose, quiet,
Antoine Pitrou293954d2011-03-23 23:01:49 +0100946 huntrleaks=False, debug=False, use_resources=None,
Antoine Pitrouf83e4ac2011-07-29 23:57:10 +0200947 output_on_failure=False, failfast=False, match_tests=None,
948 timeout=None):
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000949 """Run a single test.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000950
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000951 test -- the name of the test
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000952 verbose -- if true, print more messages
Trent Mickf29f47b2000-08-11 19:02:59 +0000953 quiet -- if true, don't print 'skipped' messages (probably redundant)
Christian Heimesb186d002008-03-18 15:15:01 +0000954 test_times -- a list of (time, test_name) pairs
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000955 huntrleaks -- run multiple times to test for leaks; requires a debug
956 build; a triple corresponding to -R's three arguments
Victor Stinner8313d6a2011-06-29 15:22:26 +0200957 output_on_failure -- if true, display test output on failure
Victor Stinner0cc8d592011-03-31 18:10:13 +0200958 timeout -- dump the traceback and exit if a test takes more than
959 timeout seconds
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000960
961 Returns one of the test result constants:
962 INTERRUPTED KeyboardInterrupt when run under -j
963 RESOURCE_DENIED test skipped because resource denied
964 SKIPPED test skipped for some other reason
965 ENV_CHANGED test failed because it changed the execution environment
966 FAILED test failed
967 PASSED test passed
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000968 """
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000969
Antoine Pitrou88909542009-06-29 13:54:42 +0000970 if use_resources is not None:
971 support.use_resources = use_resources
Victor Stinner30196882011-06-03 12:53:26 +0200972 use_timeout = (timeout is not None)
Victor Stinner7d648a02011-03-31 18:27:50 +0200973 if use_timeout:
Victor Stinner0cc8d592011-03-31 18:10:13 +0200974 faulthandler.dump_tracebacks_later(timeout, exit=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000975 try:
Antoine Pitroub9c73e82011-07-29 23:53:38 +0200976 support.match_tests = match_tests
Antoine Pitrou216a3bc2011-07-23 22:33:39 +0200977 if failfast:
978 support.failfast = True
Victor Stinner8313d6a2011-06-29 15:22:26 +0200979 if output_on_failure:
Victor Stinnerea95de72011-06-29 15:34:48 +0200980 support.verbose = True
981
982 # Reuse the same instance to all calls to runtest(). Some
983 # tests keep a reference to sys.stdout or sys.stderr
984 # (eg. test_argparse).
Victor Stinner8313d6a2011-06-29 15:22:26 +0200985 if runtest.stringio is None:
Victor Stinnerfcc2a212011-06-29 20:01:29 +0200986 stream = io.StringIO()
987 runtest.stringio = stream
988 else:
989 stream = runtest.stringio
990 stream.seek(0)
991 stream.truncate()
Victor Stinner8313d6a2011-06-29 15:22:26 +0200992
993 orig_stdout = sys.stdout
Victor Stinnera7c33e52011-06-29 13:00:54 +0200994 orig_stderr = sys.stderr
Victor Stinner8313d6a2011-06-29 15:22:26 +0200995 try:
Victor Stinnerea95de72011-06-29 15:34:48 +0200996 sys.stdout = stream
997 sys.stderr = stream
Victor Stinner8313d6a2011-06-29 15:22:26 +0200998 result = runtest_inner(test, verbose, quiet, huntrleaks,
999 debug, display_failure=False)
1000 if result[0] == FAILED:
Victor Stinnerea95de72011-06-29 15:34:48 +02001001 output = stream.getvalue()
Victor Stinner8313d6a2011-06-29 15:22:26 +02001002 orig_stderr.write(output)
1003 orig_stderr.flush()
1004 finally:
1005 sys.stdout = orig_stdout
1006 sys.stderr = orig_stderr
Victor Stinnera7c33e52011-06-29 13:00:54 +02001007 else:
Victor Stinnerea95de72011-06-29 15:34:48 +02001008 support.verbose = verbose # Tell tests to be moderately quiet
Victor Stinnera7c33e52011-06-29 13:00:54 +02001009 result = runtest_inner(test, verbose, quiet, huntrleaks, debug,
1010 display_failure=not verbose)
Antoine Pitrou293954d2011-03-23 23:01:49 +01001011 return result
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001012 finally:
Victor Stinner7d648a02011-03-31 18:27:50 +02001013 if use_timeout:
Victor Stinner0cc8d592011-03-31 18:10:13 +02001014 faulthandler.cancel_dump_tracebacks_later()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001015 cleanup_test_droppings(test, verbose)
Victor Stinner8313d6a2011-06-29 15:22:26 +02001016runtest.stringio = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001017
Nick Coghlan6ead5522009-10-18 13:19:33 +00001018# Unit tests are supposed to leave the execution environment unchanged
1019# once they complete. But sometimes tests have bugs, especially when
1020# tests fail, and the changes to environment go on to mess up other
1021# tests. This can cause issues with buildbot stability, since tests
1022# are run in random order and so problems may appear to come and go.
1023# There are a few things we can save and restore to mitigate this, and
1024# the following context manager handles this task.
1025
1026class saved_test_environment:
1027 """Save bits of the test environment and restore them at block exit.
1028
1029 with saved_test_environment(testname, verbose, quiet):
1030 #stuff
1031
1032 Unless quiet is True, a warning is printed to stderr if any of
1033 the saved items was changed by the test. The attribute 'changed'
1034 is initially False, but is set to True if a change is detected.
1035
1036 If verbose is more than 1, the before and after state of changed
1037 items is also printed.
1038 """
1039
1040 changed = False
1041
1042 def __init__(self, testname, verbose=0, quiet=False):
1043 self.testname = testname
1044 self.verbose = verbose
1045 self.quiet = quiet
1046
1047 # To add things to save and restore, add a name XXX to the resources list
1048 # and add corresponding get_XXX/restore_XXX functions. get_XXX should
1049 # return the value to be saved and compared against a second call to the
1050 # get function when test execution completes. restore_XXX should accept
1051 # the saved value and restore the resource using it. It will be called if
1052 # and only if a change in the value is detected.
1053 #
1054 # Note: XXX will have any '.' replaced with '_' characters when determining
1055 # the corresponding method names.
1056
1057 resources = ('sys.argv', 'cwd', 'sys.stdin', 'sys.stdout', 'sys.stderr',
Brett Cannon29c0e4f2010-03-20 22:22:57 +00001058 'os.environ', 'sys.path', 'sys.path_hooks', '__import__',
Nick Coghlan7bd5dbe2010-12-05 07:17:25 +00001059 'warnings.filters', 'asyncore.socket_map',
Ezio Melotti45763d02011-03-20 15:34:28 +02001060 'logging._handlers', 'logging._handlerList', 'sys.gettrace',
Antoine Pitrouc081c0c2011-07-15 22:12:24 +02001061 'sys.warnoptions', 'threading._dangling',
Éric Araujo28df8de2011-09-19 05:10:45 +02001062 'multiprocessing.process._dangling',
Éric Araujoec177c12012-06-24 03:27:43 -04001063 'sysconfig._CONFIG_VARS', 'sysconfig._INSTALL_SCHEMES',
Vinay Sajipf9596182012-03-02 01:01:13 +00001064 'support.TESTFN',
Éric Araujo28df8de2011-09-19 05:10:45 +02001065 )
Nick Coghlan6ead5522009-10-18 13:19:33 +00001066
1067 def get_sys_argv(self):
1068 return id(sys.argv), sys.argv, sys.argv[:]
1069 def restore_sys_argv(self, saved_argv):
1070 sys.argv = saved_argv[1]
1071 sys.argv[:] = saved_argv[2]
1072
1073 def get_cwd(self):
1074 return os.getcwd()
1075 def restore_cwd(self, saved_cwd):
1076 os.chdir(saved_cwd)
1077
1078 def get_sys_stdout(self):
1079 return sys.stdout
1080 def restore_sys_stdout(self, saved_stdout):
1081 sys.stdout = saved_stdout
1082
1083 def get_sys_stderr(self):
1084 return sys.stderr
1085 def restore_sys_stderr(self, saved_stderr):
1086 sys.stderr = saved_stderr
1087
1088 def get_sys_stdin(self):
1089 return sys.stdin
1090 def restore_sys_stdin(self, saved_stdin):
1091 sys.stdin = saved_stdin
1092
1093 def get_os_environ(self):
1094 return id(os.environ), os.environ, dict(os.environ)
1095 def restore_os_environ(self, saved_environ):
1096 os.environ = saved_environ[1]
1097 os.environ.clear()
1098 os.environ.update(saved_environ[2])
1099
1100 def get_sys_path(self):
1101 return id(sys.path), sys.path, sys.path[:]
1102 def restore_sys_path(self, saved_path):
1103 sys.path = saved_path[1]
1104 sys.path[:] = saved_path[2]
1105
Brett Cannon055470a2010-02-19 15:57:10 +00001106 def get_sys_path_hooks(self):
1107 return id(sys.path_hooks), sys.path_hooks, sys.path_hooks[:]
1108 def restore_sys_path_hooks(self, saved_hooks):
1109 sys.path_hooks = saved_hooks[1]
1110 sys.path_hooks[:] = saved_hooks[2]
1111
Brett Cannon31f59292011-02-21 19:29:56 +00001112 def get_sys_gettrace(self):
1113 return sys.gettrace()
1114 def restore_sys_gettrace(self, trace_fxn):
1115 sys.settrace(trace_fxn)
1116
Brett Cannon055470a2010-02-19 15:57:10 +00001117 def get___import__(self):
Brett Cannon45071902010-06-14 22:22:54 +00001118 return builtins.__import__
Brett Cannon055470a2010-02-19 15:57:10 +00001119 def restore___import__(self, import_):
Brett Cannon45071902010-06-14 22:22:54 +00001120 builtins.__import__ = import_
Brett Cannon055470a2010-02-19 15:57:10 +00001121
Brett Cannon29c0e4f2010-03-20 22:22:57 +00001122 def get_warnings_filters(self):
1123 return id(warnings.filters), warnings.filters, warnings.filters[:]
1124 def restore_warnings_filters(self, saved_filters):
1125 warnings.filters = saved_filters[1]
1126 warnings.filters[:] = saved_filters[2]
1127
Antoine Pitroub14ac8c2010-08-16 00:28:05 +00001128 def get_asyncore_socket_map(self):
1129 asyncore = sys.modules.get('asyncore')
Antoine Pitrouaa879652010-10-29 11:54:38 +00001130 # XXX Making a copy keeps objects alive until __exit__ gets called.
1131 return asyncore and asyncore.socket_map.copy() or {}
Antoine Pitroub14ac8c2010-08-16 00:28:05 +00001132 def restore_asyncore_socket_map(self, saved_map):
1133 asyncore = sys.modules.get('asyncore')
1134 if asyncore is not None:
Antoine Pitrouaa879652010-10-29 11:54:38 +00001135 asyncore.close_all(ignore_all=True)
Antoine Pitroub14ac8c2010-08-16 00:28:05 +00001136 asyncore.socket_map.update(saved_map)
1137
Éric Araujoff913062011-11-29 16:45:07 +01001138 def get_shutil_archive_formats(self):
1139 # we could call get_archives_formats() but that only returns the
1140 # registry keys; we want to check the values too (the functions that
1141 # are registered)
1142 return shutil._ARCHIVE_FORMATS, shutil._ARCHIVE_FORMATS.copy()
1143 def restore_shutil_archive_formats(self, saved):
1144 shutil._ARCHIVE_FORMATS = saved[0]
1145 shutil._ARCHIVE_FORMATS.clear()
1146 shutil._ARCHIVE_FORMATS.update(saved[1])
1147
1148 def get_shutil_unpack_formats(self):
1149 return shutil._UNPACK_FORMATS, shutil._UNPACK_FORMATS.copy()
1150 def restore_shutil_unpack_formats(self, saved):
1151 shutil._UNPACK_FORMATS = saved[0]
1152 shutil._UNPACK_FORMATS.clear()
1153 shutil._UNPACK_FORMATS.update(saved[1])
1154
Nick Coghlan7d819752010-12-05 06:45:03 +00001155 def get_logging__handlers(self):
1156 # _handlers is a WeakValueDictionary
Nick Coghlan7bd5dbe2010-12-05 07:17:25 +00001157 return id(logging._handlers), logging._handlers, logging._handlers.copy()
Nick Coghlan7d819752010-12-05 06:45:03 +00001158 def restore_logging__handlers(self, saved_handlers):
1159 # Can't easily revert the logging state
1160 pass
1161
Nick Coghlan7bd5dbe2010-12-05 07:17:25 +00001162 def get_logging__handlerList(self):
1163 # _handlerList is a list of weakrefs to handlers
1164 return id(logging._handlerList), logging._handlerList, logging._handlerList[:]
1165 def restore_logging__handlerList(self, saved_handlerList):
1166 # Can't easily revert the logging state
1167 pass
1168
Ezio Melotti0123e052011-03-20 15:09:26 +02001169 def get_sys_warnoptions(self):
1170 return id(sys.warnoptions), sys.warnoptions, sys.warnoptions[:]
1171 def restore_sys_warnoptions(self, saved_options):
1172 sys.warnoptions = saved_options[1]
1173 sys.warnoptions[:] = saved_options[2]
1174
Antoine Pitrouc081c0c2011-07-15 22:12:24 +02001175 # Controlling dangling references to Thread objects can make it easier
1176 # to track reference leaks.
1177 def get_threading__dangling(self):
1178 if not threading:
1179 return None
1180 # This copies the weakrefs without making any strong reference
1181 return threading._dangling.copy()
1182 def restore_threading__dangling(self, saved):
1183 if not threading:
1184 return
1185 threading._dangling.clear()
1186 threading._dangling.update(saved)
1187
1188 # Same for Process objects
1189 def get_multiprocessing_process__dangling(self):
1190 if not multiprocessing:
1191 return None
1192 # This copies the weakrefs without making any strong reference
1193 return multiprocessing.process._dangling.copy()
1194 def restore_multiprocessing_process__dangling(self, saved):
1195 if not multiprocessing:
1196 return
1197 multiprocessing.process._dangling.clear()
1198 multiprocessing.process._dangling.update(saved)
1199
Éric Araujo28df8de2011-09-19 05:10:45 +02001200 def get_sysconfig__CONFIG_VARS(self):
1201 # make sure the dict is initialized
1202 sysconfig.get_config_var('prefix')
1203 return (id(sysconfig._CONFIG_VARS), sysconfig._CONFIG_VARS,
1204 dict(sysconfig._CONFIG_VARS))
1205 def restore_sysconfig__CONFIG_VARS(self, saved):
1206 sysconfig._CONFIG_VARS = saved[1]
1207 sysconfig._CONFIG_VARS.clear()
1208 sysconfig._CONFIG_VARS.update(saved[2])
1209
Éric Araujoec177c12012-06-24 03:27:43 -04001210 def get_sysconfig__INSTALL_SCHEMES(self):
1211 return (id(sysconfig._INSTALL_SCHEMES), sysconfig._INSTALL_SCHEMES,
1212 sysconfig._INSTALL_SCHEMES.copy())
1213 def restore_sysconfig__INSTALL_SCHEMES(self, saved):
1214 sysconfig._INSTALL_SCHEMES = saved[1]
1215 sysconfig._INSTALL_SCHEMES.clear()
1216 sysconfig._INSTALL_SCHEMES.update(saved[2])
Éric Araujo28df8de2011-09-19 05:10:45 +02001217
Vinay Sajipf9596182012-03-02 01:01:13 +00001218 def get_support_TESTFN(self):
1219 if os.path.isfile(support.TESTFN):
1220 result = 'f'
1221 elif os.path.isdir(support.TESTFN):
1222 result = 'd'
1223 else:
1224 result = None
1225 return result
1226 def restore_support_TESTFN(self, saved_value):
1227 if saved_value is None:
1228 if os.path.isfile(support.TESTFN):
1229 os.unlink(support.TESTFN)
1230 elif os.path.isdir(support.TESTFN):
1231 shutil.rmtree(support.TESTFN)
Éric Araujo28df8de2011-09-19 05:10:45 +02001232
Nick Coghlan6ead5522009-10-18 13:19:33 +00001233 def resource_info(self):
1234 for name in self.resources:
1235 method_suffix = name.replace('.', '_')
1236 get_name = 'get_' + method_suffix
1237 restore_name = 'restore_' + method_suffix
1238 yield name, getattr(self, get_name), getattr(self, restore_name)
1239
1240 def __enter__(self):
1241 self.saved_values = dict((name, get()) for name, get, restore
1242 in self.resource_info())
1243 return self
1244
1245 def __exit__(self, exc_type, exc_val, exc_tb):
Antoine Pitrouaa879652010-10-29 11:54:38 +00001246 saved_values = self.saved_values
1247 del self.saved_values
Nick Coghlan6ead5522009-10-18 13:19:33 +00001248 for name, get, restore in self.resource_info():
1249 current = get()
Antoine Pitrouaa879652010-10-29 11:54:38 +00001250 original = saved_values.pop(name)
Nick Coghlan6ead5522009-10-18 13:19:33 +00001251 # Check for changes to the resource's value
1252 if current != original:
1253 self.changed = True
1254 restore(original)
1255 if not self.quiet:
1256 print("Warning -- {} was modified by {}".format(
1257 name, self.testname),
1258 file=sys.stderr)
1259 if self.verbose > 1:
1260 print(" Before: {}\n After: {} ".format(
1261 original, current),
1262 file=sys.stderr)
1263 return False
1264
1265
Victor Stinnera7c33e52011-06-29 13:00:54 +02001266def runtest_inner(test, verbose, quiet,
1267 huntrleaks=False, debug=False, display_failure=True):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001268 support.unload(test)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001269
Antoine Pitrou88909542009-06-29 13:54:42 +00001270 test_time = 0.0
Collin Wintera5503d52009-05-15 01:20:21 +00001271 refleak = False # True if the test leaked references.
Guido van Rossum152494a1996-12-20 03:12:20 +00001272 try:
R. David Murray0bc11ae2009-10-18 22:18:17 +00001273 if test.startswith('test.'):
1274 abstest = test
1275 else:
1276 # Always import it from the test package
1277 abstest = 'test.' + test
1278 with saved_test_environment(test, verbose, quiet) as environment:
1279 start_time = time.time()
Brett Cannon613cf252012-11-14 13:42:51 -05001280 the_module = importlib.import_module(abstest)
R David Murray78fc25c2012-04-09 08:55:42 -04001281 # If the test has a test_main, that will run the appropriate
1282 # tests. If not, use normal unittest test loading.
1283 test_runner = getattr(the_module, "test_main", None)
1284 if test_runner is None:
1285 tests = unittest.TestLoader().loadTestsFromModule(the_module)
1286 test_runner = lambda: support.run_unittest(tests)
1287 test_runner()
R. David Murray0bc11ae2009-10-18 22:18:17 +00001288 if huntrleaks:
R David Murray78fc25c2012-04-09 08:55:42 -04001289 refleak = dash_R(the_module, test, test_runner,
R. David Murray0bc11ae2009-10-18 22:18:17 +00001290 huntrleaks)
1291 test_time = time.time() - start_time
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001292 except support.ResourceDenied as msg:
Fred Drake9a0db072003-02-03 15:19:30 +00001293 if not quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001294 print(test, "skipped --", msg)
Fred Drake9a0db072003-02-03 15:19:30 +00001295 sys.stdout.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001296 return RESOURCE_DENIED, test_time
R. David Murraya21e4ca2009-03-31 23:16:50 +00001297 except unittest.SkipTest as msg:
Trent Mickf29f47b2000-08-11 19:02:59 +00001298 if not quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001299 print(test, "skipped --", msg)
Guido van Rossum3cda93e2002-09-13 21:28:03 +00001300 sys.stdout.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001301 return SKIPPED, test_time
Fred Drakefe5c22a2000-08-18 16:04:05 +00001302 except KeyboardInterrupt:
1303 raise
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001304 except support.TestFailed as msg:
Victor Stinnera7c33e52011-06-29 13:00:54 +02001305 if display_failure:
1306 print("test", test, "failed --", msg, file=sys.stderr)
1307 else:
1308 print("test", test, "failed", file=sys.stderr)
R. David Murray11cabcf2010-09-29 01:08:05 +00001309 sys.stderr.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001310 return FAILED, test_time
Guido van Rossum9e48b271997-07-16 01:56:13 +00001311 except:
Antoine Pitrou779a5b02011-03-21 19:55:16 +01001312 msg = traceback.format_exc()
1313 print("test", test, "crashed --", msg, file=sys.stderr)
R. David Murray11cabcf2010-09-29 01:08:05 +00001314 sys.stderr.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001315 return FAILED, test_time
Guido van Rossum152494a1996-12-20 03:12:20 +00001316 else:
Collin Wintera5503d52009-05-15 01:20:21 +00001317 if refleak:
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001318 return FAILED, test_time
Nick Coghlan6ead5522009-10-18 13:19:33 +00001319 if environment.changed:
Benjamin Petersona0dfa822009-11-13 02:25:08 +00001320 return ENV_CHANGED, test_time
1321 return PASSED, test_time
Guido van Rossum0fcca4e2001-09-21 20:31:52 +00001322
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001323def cleanup_test_droppings(testname, verbose):
1324 import shutil
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001325 import stat
Antoine Pitrouc14efc42010-10-29 19:34:45 +00001326 import gc
1327
1328 # First kill any dangling references to open files etc.
1329 # This can also issue some ResourceWarnings which would otherwise get
Antoine Pitrou2b40efd2010-10-29 19:36:37 +00001330 # triggered during the following test run, and possibly produce failures.
Antoine Pitrouc14efc42010-10-29 19:34:45 +00001331 gc.collect()
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001332
1333 # Try to clean up junk commonly left behind. While tests shouldn't leave
1334 # any files or directories behind, when a test fails that can be tedious
1335 # for it to arrange. The consequences can be especially nasty on Windows,
1336 # since if a test leaves a file open, it cannot be deleted by name (while
1337 # there's nothing we can do about that here either, we can display the
1338 # name of the offending test, which is a real help).
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001339 for name in (support.TESTFN,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001340 "db_home",
1341 ):
1342 if not os.path.exists(name):
1343 continue
1344
1345 if os.path.isdir(name):
1346 kind, nuker = "directory", shutil.rmtree
1347 elif os.path.isfile(name):
1348 kind, nuker = "file", os.unlink
1349 else:
1350 raise SystemError("os.path says %r exists but is neither "
1351 "directory nor file" % name)
1352
1353 if verbose:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001354 print("%r left behind %s %r" % (testname, kind, name))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001355 try:
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001356 # if we have chmod, fix possible permissions problems
1357 # that might prevent cleanup
1358 if (hasattr(os, 'chmod')):
1359 os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001360 nuker(name)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001361 except Exception as msg:
1362 print(("%r left behind %s %r and it couldn't be "
1363 "removed: %s" % (testname, kind, name, msg)), file=sys.stderr)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001364
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001365def dash_R(the_module, test, indirect_test, huntrleaks):
Collin Wintera5503d52009-05-15 01:20:21 +00001366 """Run a test multiple times, looking for reference leaks.
1367
1368 Returns:
1369 False if the test didn't leak references; True if we detected refleaks.
1370 """
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001371 # This code is hackish and inelegant, but it seems to do the job.
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001372 import copyreg
1373 import collections.abc
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001374
1375 if not hasattr(sys, 'gettotalrefcount'):
1376 raise Exception("Tracking reference leaks requires a debug build "
1377 "of Python")
1378
1379 # Save current values for dash_R_cleanup() to restore.
1380 fs = warnings.filters[:]
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001381 ps = copyreg.dispatch_table.copy()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001382 pic = sys.path_importer_cache.copy()
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001383 try:
1384 import zipimport
1385 except ImportError:
1386 zdc = None # Run unmodified on platforms without zipimport support
1387 else:
1388 zdc = zipimport._zip_directory_cache.copy()
Christian Heimes93852662007-12-01 12:22:32 +00001389 abcs = {}
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001390 for abc in [getattr(collections.abc, a) for a in collections.abc.__all__]:
Christian Heimesbe5b30b2008-03-03 19:18:51 +00001391 if not isabstract(abc):
Christian Heimes93852662007-12-01 12:22:32 +00001392 continue
1393 for obj in abc.__subclasses__() + [abc]:
1394 abcs[obj] = obj._abc_registry.copy()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001395
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001396 nwarmup, ntracked, fname = huntrleaks
Ezio Melotti184bdfb2010-02-18 09:37:05 +00001397 fname = os.path.join(support.SAVEDCWD, fname)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001398 repcount = nwarmup + ntracked
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001399 rc_deltas = [0] * repcount
1400 alloc_deltas = [0] * repcount
1401
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001402 print("beginning", repcount, "repetitions", file=sys.stderr)
1403 print(("1234567890"*(repcount//10 + 1))[:repcount], file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +00001404 sys.stderr.flush()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001405 for i in range(repcount):
R David Murray14d080e2013-01-12 11:34:38 -05001406 indirect_test()
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001407 alloc_after, rc_after = dash_R_cleanup(fs, ps, pic, zdc, abcs)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001408 sys.stderr.write('.')
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001409 sys.stderr.flush()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001410 if i >= nwarmup:
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001411 rc_deltas[i] = rc_after - rc_before
1412 alloc_deltas[i] = alloc_after - alloc_before
1413 alloc_before, rc_before = alloc_after, rc_after
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001414 print(file=sys.stderr)
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001415 # These checkers return False on success, True on failure
1416 def check_rc_deltas(deltas):
1417 return any(deltas)
1418 def check_alloc_deltas(deltas):
1419 # At least 1/3rd of 0s
1420 if 3 * deltas.count(0) < len(deltas):
1421 return True
1422 # Nothing else than 1s, 0s and -1s
1423 if not set(deltas) <= {1,0,-1}:
1424 return True
1425 return False
1426 failed = False
1427 for deltas, item_name, checker in [
1428 (rc_deltas, 'references', check_rc_deltas),
1429 (alloc_deltas, 'memory blocks', check_alloc_deltas)]:
1430 if checker(deltas):
1431 msg = '%s leaked %s %s, sum=%s' % (
1432 test, deltas[nwarmup:], item_name, sum(deltas))
1433 print(msg, file=sys.stderr)
1434 sys.stderr.flush()
1435 with open(fname, "a") as refrep:
1436 print(msg, file=refrep)
1437 refrep.flush()
1438 failed = True
1439 return failed
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001440
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001441def dash_R_cleanup(fs, ps, pic, zdc, abcs):
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001442 import gc, copyreg
Brett Cannonf4fd9932008-05-10 21:11:46 +00001443 import _strptime, linecache
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001444 import urllib.parse, urllib.request, mimetypes, doctest
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001445 import struct, filecmp, collections.abc
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001446 from distutils.dir_util import _path_created
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001447 from weakref import WeakSet
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001448
Christian Heimesdae2a892008-04-19 00:55:37 +00001449 # Clear the warnings registry, so they can be displayed again
1450 for mod in sys.modules.values():
1451 if hasattr(mod, '__warningregistry__'):
1452 del mod.__warningregistry__
1453
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001454 # Restore some original values.
1455 warnings.filters[:] = fs
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001456 copyreg.dispatch_table.clear()
1457 copyreg.dispatch_table.update(ps)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001458 sys.path_importer_cache.clear()
1459 sys.path_importer_cache.update(pic)
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001460 try:
1461 import zipimport
1462 except ImportError:
1463 pass # Run unmodified on platforms without zipimport support
1464 else:
1465 zipimport._zip_directory_cache.clear()
1466 zipimport._zip_directory_cache.update(zdc)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001467
Christian Heimes26855632008-01-27 23:50:43 +00001468 # clear type cache
Christian Heimes15ebc882008-02-04 18:48:49 +00001469 sys._clear_type_cache()
Christian Heimes26855632008-01-27 23:50:43 +00001470
Guido van Rossum3de862d2007-08-18 00:10:33 +00001471 # Clear ABC registries, restoring previously saved ABC registries.
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001472 for abc in [getattr(collections.abc, a) for a in collections.abc.__all__]:
Christian Heimesbe5b30b2008-03-03 19:18:51 +00001473 if not isabstract(abc):
Christian Heimes941973a2007-11-30 21:53:03 +00001474 continue
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001475 for obj in abc.__subclasses__() + [abc]:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001476 obj._abc_registry = abcs.get(obj, WeakSet()).copy()
Guido van Rossumc1e315d2007-08-20 19:29:24 +00001477 obj._abc_cache.clear()
1478 obj._abc_negative_cache.clear()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001479
Antoine Pitrou046467c2009-10-30 18:30:35 +00001480 # Flush standard output, so that buffered data is sent to the OS and
1481 # associated Python objects are reclaimed.
1482 for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__):
1483 if stream is not None:
1484 stream.flush()
1485
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001486 # Clear assorted module caches.
1487 _path_created.clear()
1488 re.purge()
1489 _strptime._regex_cache.clear()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001490 urllib.parse.clear_cache()
1491 urllib.request.urlcleanup()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001492 linecache.clearcache()
1493 mimetypes._default_mime_types()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001494 filecmp._cache.clear()
Christian Heimesa34706f2008-01-04 03:06:10 +00001495 struct._clearcache()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001496 doctest.master = None
Meador Inge11e38132011-11-25 22:33:32 -06001497 try:
1498 import ctypes
1499 except ImportError:
1500 # Don't worry about resetting the cache if ctypes is not supported
1501 pass
1502 else:
1503 ctypes._reset_cache()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001504
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001505 # Collect cyclic trash and read memory statistics immediately after.
1506 func1 = sys.getallocatedblocks
1507 func2 = sys.gettotalrefcount
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001508 gc.collect()
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001509 return func1(), func2()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001510
Stefan Krah5c3ddc82012-08-17 23:09:48 +02001511def warm_caches():
1512 # char cache
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001513 s = bytes(range(256))
1514 for i in range(256):
1515 s[i:i+1]
Stefan Krah5c3ddc82012-08-17 23:09:48 +02001516 # unicode cache
1517 x = [chr(i) for i in range(256)]
1518 # int cache
1519 x = list(range(-5, 257))
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001520
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001521def findtestdir(path=None):
1522 return path or os.path.dirname(__file__) or os.curdir
Guido van Rossum152494a1996-12-20 03:12:20 +00001523
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001524def removepy(names):
1525 if not names:
1526 return
1527 for idx, name in enumerate(names):
1528 basename, ext = os.path.splitext(name)
1529 if ext == '.py':
1530 names[idx] = basename
Tim Petersc5000df2002-06-02 21:42:01 +00001531
Guido van Rossum152494a1996-12-20 03:12:20 +00001532def count(n, word):
1533 if n == 1:
Guido van Rossum41360a41998-03-26 19:42:58 +00001534 return "%d %s" % (n, word)
Guido van Rossum152494a1996-12-20 03:12:20 +00001535 else:
Guido van Rossum41360a41998-03-26 19:42:58 +00001536 return "%d %ss" % (n, word)
Guido van Rossum152494a1996-12-20 03:12:20 +00001537
Tim Petersa45da922001-08-12 03:45:50 +00001538def printlist(x, width=70, indent=4):
Tim Peters7c7efe92002-08-23 17:55:54 +00001539 """Print the elements of iterable x to stdout.
Tim Petersa45da922001-08-12 03:45:50 +00001540
1541 Optional arg width (default 70) is the maximum line length.
1542 Optional arg indent (default 4) is the number of blanks with which to
1543 begin each line.
1544 """
1545
Tim Petersba78bc42002-07-04 19:45:06 +00001546 from textwrap import fill
1547 blanks = ' ' * indent
Florent Xiclunafd1b0932010-03-28 00:25:02 +00001548 # Print the sorted list: 'x' may be a '--random' list or a set()
1549 print(fill(' '.join(str(elt) for elt in sorted(x)), width,
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001550 initial_indent=blanks, subsequent_indent=blanks))
Tim Petersa45da922001-08-12 03:45:50 +00001551
Tim Petersb5b7b782001-08-12 01:20:39 +00001552
Chris Jerdonek517e9252013-02-27 09:02:53 -08001553def main_in_temp_cwd():
1554 """Run main() in a temporary working directory."""
Michael Foord3ab34cc2010-12-03 12:27:40 +00001555 if sysconfig.is_python_build():
Antoine Pitrouee429342011-04-16 18:53:59 +02001556 try:
Michael Foord3ab34cc2010-12-03 12:27:40 +00001557 os.mkdir(TEMPDIR)
Florent Xicluna68f71a32011-10-28 16:06:23 +02001558 except FileExistsError:
1559 pass
Michael Foord3ab34cc2010-12-03 12:27:40 +00001560
1561 # Define a writable temp dir that will be used as cwd while running
1562 # the tests. The name of the dir includes the pid to allow parallel
1563 # testing (see the -j option).
Chris Jerdonek517e9252013-02-27 09:02:53 -08001564 test_cwd = 'test_python_{}'.format(os.getpid())
1565 test_cwd = os.path.join(TEMPDIR, test_cwd)
Michael Foord3ab34cc2010-12-03 12:27:40 +00001566
Chris Jerdonek517e9252013-02-27 09:02:53 -08001567 # Run the tests in a context manager that temporarily changes the CWD to a
1568 # temporary and writable directory. If it's not possible to create or
1569 # change the CWD, the original CWD will be used. The original CWD is
1570 # available from support.SAVEDCWD.
1571 with support.temp_cwd(test_cwd, quiet=True):
1572 main()
1573
Nick Coghlan4c4c0f22010-12-03 07:44:33 +00001574
Guido van Rossum152494a1996-12-20 03:12:20 +00001575if __name__ == '__main__':
Nick Coghlan4c4c0f22010-12-03 07:44:33 +00001576 # Remove regrtest.py's own directory from the module search path. Despite
1577 # the elimination of implicit relative imports, this is still needed to
1578 # ensure that submodules of the test package do not inappropriately appear
1579 # as top-level modules even when people (or buildbots!) invoke regrtest.py
1580 # directly instead of using the -m switch
1581 mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
1582 i = len(sys.path)
1583 while i >= 0:
1584 i -= 1
1585 if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
1586 del sys.path[i]
1587
Florent Xiclunadc69e722010-09-13 16:35:02 +00001588 # findtestdir() gets the dirname out of __file__, so we have to make it
1589 # absolute before changing the working directory.
1590 # For example __file__ may be relative when running trace or profile.
1591 # See issue #9323.
1592 __file__ = os.path.abspath(__file__)
1593
1594 # sanity check
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001595 assert __file__ == os.path.abspath(sys.argv[0])
Ezio Melotti184bdfb2010-02-18 09:37:05 +00001596
Chris Jerdonek517e9252013-02-27 09:02:53 -08001597 main_in_temp_cwd()