blob: 51e9e1802929b7ecada68fe4bad2c1dccefed71e [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
Nick Coghlanbe7e49f2012-07-20 23:40:09 +10009# We import importlib *ASAP* in order to test #15386
10import importlib
11
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -080012import argparse
Brett Cannon45071902010-06-14 22:22:54 +000013import builtins
Victor Stinner024e37a2011-03-31 01:31:06 +020014import faulthandler
Victor Stinner8313d6a2011-06-29 15:22:26 +020015import io
Antoine Pitrou88909542009-06-29 13:54:42 +000016import json
Brett Cannon49e835b2013-04-01 14:11:37 -040017import locale
Victor Stinner8313d6a2011-06-29 15:22:26 +020018import logging
Christian Heimesb186d002008-03-18 15:15:01 +000019import os
Victor Stinner8313d6a2011-06-29 15:22:26 +020020import platform
Skip Montanaroab1c7912000-06-30 16:39:27 +000021import random
Thomas Wouters9ada3d62006-04-21 09:47:09 +000022import re
Éric Araujoff913062011-11-29 16:45:07 +010023import shutil
Victor Stinnercb41cda2011-07-13 23:47:21 +020024import signal
Christian Heimesb186d002008-03-18 15:15:01 +000025import sys
Florent Xiclunada7bfd52010-03-06 11:43:55 +000026import sysconfig
Victor Stinner8313d6a2011-06-29 15:22:26 +020027import tempfile
28import time
29import traceback
30import unittest
31import warnings
32from inspect import isabstract
Ezio Melotti184bdfb2010-02-18 09:37:05 +000033
Antoine Pitrouc081c0c2011-07-15 22:12:24 +020034try:
35 import threading
Brett Cannon260fbe82013-07-04 18:16:15 -040036except ImportError:
Antoine Pitrouc081c0c2011-07-15 22:12:24 +020037 threading = None
38try:
Richard Oudkerk84ed9a62013-08-14 15:35:41 +010039 import _multiprocessing, multiprocessing.process
Brett Cannon260fbe82013-07-04 18:16:15 -040040except ImportError:
Antoine Pitrouc081c0c2011-07-15 22:12:24 +020041 multiprocessing = None
42
Victor Stinner98de5342015-09-26 09:43:45 +020043from test.libregrtest import _parse_args
44
Florent Xicluna64fb18e2010-03-06 14:43:34 +000045
Ezio Melotti184bdfb2010-02-18 09:37:05 +000046# Some times __path__ and __file__ are not absolute (e.g. while running from
47# Lib/) and, if we change the CWD to run the tests in a temporary dir, some
48# imports might fail. This affects only the modules imported before os.chdir().
49# These modules are searched first in sys.path[0] (so '' -- the CWD) and if
50# they are found in the CWD their __file__ and __path__ will be relative (this
51# happens before the chdir). All the modules imported after the chdir, are
52# not found in the CWD, and since the other paths in sys.path[1:] are absolute
53# (site.py absolutize them), the __file__ and __path__ will be absolute too.
54# Therefore it is necessary to absolutize manually the __file__ and __path__ of
55# the packages to prevent later imports to fail when the CWD is different.
56for module in sys.modules.values():
57 if hasattr(module, '__path__'):
58 module.__path__ = [os.path.abspath(path) for path in module.__path__]
59 if hasattr(module, '__file__'):
60 module.__file__ = os.path.abspath(module.__file__)
61
Guido van Rossumdc15c272002-08-12 21:55:51 +000062
Guido van Rossumbb484652002-12-02 09:56:21 +000063# MacOSX (a.k.a. Darwin) has a default stack size that is too small
64# for deeply recursive regular expressions. We see this as crashes in
65# the Python test suite when running test_re.py and test_sre.py. The
66# fix is to set the stack limit to 2048.
67# This approach may also be useful for other Unixy platforms that
68# suffer from small default stack limits.
69if sys.platform == 'darwin':
70 try:
71 import resource
Brett Cannon260fbe82013-07-04 18:16:15 -040072 except ImportError:
Guido van Rossumbb484652002-12-02 09:56:21 +000073 pass
74 else:
75 soft, hard = resource.getrlimit(resource.RLIMIT_STACK)
76 newsoft = min(hard, max(soft, 1024*2048))
77 resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
78
Benjamin Petersona0dfa822009-11-13 02:25:08 +000079# Test result constants.
80PASSED = 1
81FAILED = 0
82ENV_CHANGED = -1
83SKIPPED = -2
84RESOURCE_DENIED = -3
85INTERRUPTED = -4
Victor Stinner4b739882011-03-31 18:02:36 +020086CHILD_ERROR = -5 # error in a child process
Benjamin Petersona0dfa822009-11-13 02:25:08 +000087
Benjamin Petersonee8712c2008-05-20 21:35:26 +000088from test import support
Fred Drake3a15dac2002-04-11 16:39:16 +000089
Chris Jerdonek517e9252013-02-27 09:02:53 -080090# When tests are run from the Python build directory, it is best practice
91# to keep the test files in a subfolder. This eases the cleanup of leftover
92# files using the "make distclean" command.
93if sysconfig.is_python_build():
94 TEMPDIR = os.path.join(sysconfig.get_config_var('srcdir'), 'build')
95else:
96 TEMPDIR = tempfile.gettempdir()
97TEMPDIR = os.path.abspath(TEMPDIR)
Fred Drake3a15dac2002-04-11 16:39:16 +000098
Eli Bendersky7f5c22c2013-09-02 08:57:21 -070099def run_test_in_subprocess(testname, ns):
100 """Run the given test in a subprocess with --slaveargs.
101
102 ns is the option Namespace parsed from command-line arguments. regrtest
103 is invoked in a subprocess with the --slaveargs argument; when the
104 subprocess exits, its return code, stdout and stderr are returned as a
105 3-tuple.
106 """
107 from subprocess import Popen, PIPE
108 base_cmd = ([sys.executable] + support.args_from_interpreter_flags() +
109 ['-X', 'faulthandler', '-m', 'test.regrtest'])
110
111 slaveargs = (
112 (testname, ns.verbose, ns.quiet),
113 dict(huntrleaks=ns.huntrleaks,
114 use_resources=ns.use_resources,
Eli Benderskye8de2962013-09-02 17:01:10 -0700115 output_on_failure=ns.verbose3,
Eli Bendersky7f5c22c2013-09-02 08:57:21 -0700116 timeout=ns.timeout, failfast=ns.failfast,
117 match_tests=ns.match_tests))
118 # Running the child from the same working directory as regrtest's original
119 # invocation ensures that TEMPDIR for the child is the same when
120 # sysconfig.is_python_build() is true. See issue 15300.
121 popen = Popen(base_cmd + ['--slaveargs', json.dumps(slaveargs)],
122 stdout=PIPE, stderr=PIPE,
123 universal_newlines=True,
124 close_fds=(os.name != 'nt'),
125 cwd=support.SAVEDCWD)
126 stdout, stderr = popen.communicate()
127 retcode = popen.wait()
128 return retcode, stdout, stderr
129
130
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300131def main(tests=None, **kwargs):
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000132 """Execute a test suite.
133
Thomas Wouters7e474022000-07-16 12:04:32 +0000134 This also parses command-line options and modifies its behavior
Fred Drake004d5e62000-10-23 17:22:08 +0000135 accordingly.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000136
137 tests -- a list of strings containing test names (optional)
138 testdir -- the directory in which to look for tests (optional)
139
140 Users other than the Python test suite will certainly want to
141 specify testdir; if it's omitted, the directory containing the
Fred Drake004d5e62000-10-23 17:22:08 +0000142 Python test suite is searched for.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000143
144 If the tests argument is omitted, the tests listed on the
145 command-line will be used. If that's empty, too, then all *.py
146 files beginning with test_ will be used.
Skip Montanaroab1c7912000-06-30 16:39:27 +0000147
Antoine Pitrou88909542009-06-29 13:54:42 +0000148 The other default arguments (verbose, quiet, exclude,
Collin Winterfd12f492009-03-29 04:05:05 +0000149 single, randomize, findleaks, use_resources, trace, coverdir,
150 print_slow, and random_seed) allow programmers calling main()
151 directly to set the values that would normally be set by flags
152 on the command line.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000153 """
Victor Stinnercb41cda2011-07-13 23:47:21 +0200154 # Display the Python traceback on fatal errors (e.g. segfault)
Victor Stinner3c18f252011-05-22 15:27:14 +0200155 faulthandler.enable(all_threads=True)
156
Victor Stinnercb41cda2011-07-13 23:47:21 +0200157 # Display the Python traceback on SIGALRM or SIGUSR1 signal
158 signals = []
159 if hasattr(signal, 'SIGALRM'):
160 signals.append(signal.SIGALRM)
161 if hasattr(signal, 'SIGUSR1'):
162 signals.append(signal.SIGUSR1)
163 for signum in signals:
164 faulthandler.register(signum, chain=True)
165
Victor Stinner1802d3f2010-05-19 17:11:19 +0000166 replace_stdout()
167
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000168 support.record_original_stdout(sys.stdout)
Chris Jerdonekd6c18dc2012-12-27 18:53:12 -0800169
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300170 ns = _parse_args(sys.argv[1:], **kwargs)
Barry Warsaw08fca522001-08-20 22:33:46 +0000171
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300172 if ns.huntrleaks:
173 # Avoid false positives due to various caches
174 # filling slowly with random data:
175 warm_caches()
176 if ns.memlimit is not None:
177 support.set_memlimit(ns.memlimit)
178 if ns.threshold is not None:
179 import gc
180 gc.set_threshold(ns.threshold)
181 if ns.nowindows:
182 import msvcrt
183 msvcrt.SetErrorMode(msvcrt.SEM_FAILCRITICALERRORS|
184 msvcrt.SEM_NOALIGNMENTFAULTEXCEPT|
185 msvcrt.SEM_NOGPFAULTERRORBOX|
186 msvcrt.SEM_NOOPENFILEERRORBOX)
187 try:
188 msvcrt.CrtSetReportMode
189 except AttributeError:
190 # release build
191 pass
R. David Murray35768ad2009-11-15 00:23:21 +0000192 else:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300193 for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]:
194 msvcrt.CrtSetReportMode(m, msvcrt.CRTDBG_MODE_FILE)
195 msvcrt.CrtSetReportFile(m, msvcrt.CRTDBG_FILE_STDERR)
196 if ns.wait:
197 input("Press any key to continue...")
198
199 if ns.slaveargs is not None:
200 args, kwargs = json.loads(ns.slaveargs)
Andrew Svetlov8913a6c2013-09-01 07:58:41 +0300201 if kwargs.get('huntrleaks'):
202 unittest.BaseTestSuite._cleanup = False
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300203 try:
204 result = runtest(*args, **kwargs)
205 except KeyboardInterrupt:
206 result = INTERRUPTED, ''
207 except BaseException as e:
208 traceback.print_exc()
209 result = CHILD_ERROR, str(e)
210 sys.stdout.flush()
211 print() # Force a newline (just in case)
212 print(json.dumps(result))
213 sys.exit(0)
Barry Warsaw08fca522001-08-20 22:33:46 +0000214
Guido van Rossum152494a1996-12-20 03:12:20 +0000215 good = []
216 bad = []
217 skipped = []
Fred Drake9a0db072003-02-03 15:19:30 +0000218 resource_denieds = []
Nick Coghlan6ead5522009-10-18 13:19:33 +0000219 environment_changed = []
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000220 interrupted = False
Barry Warsawe11e3de1999-01-28 19:51:51 +0000221
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300222 if ns.findleaks:
Barry Warsawa873b032000-08-03 15:50:37 +0000223 try:
224 import gc
Brett Cannon260fbe82013-07-04 18:16:15 -0400225 except ImportError:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000226 print('No GC available, disabling findleaks.')
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300227 ns.findleaks = False
Barry Warsawa873b032000-08-03 15:50:37 +0000228 else:
Neil Schemenauer8a00abc2000-10-13 01:32:42 +0000229 # Uncomment the line below to report garbage that is not
230 # freeable by reference counting alone. By default only
231 # garbage that is not collectable by the GC is reported.
232 #gc.set_debug(gc.DEBUG_SAVEALL)
Neil Schemenauerd569f232000-09-22 15:29:28 +0000233 found_garbage = []
Barry Warsawa873b032000-08-03 15:50:37 +0000234
Andrew Svetlov8913a6c2013-09-01 07:58:41 +0300235 if ns.huntrleaks:
236 unittest.BaseTestSuite._cleanup = False
237
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300238 if ns.single:
Florent Xiclunaec882212010-08-09 16:56:43 +0000239 filename = os.path.join(TEMPDIR, 'pynexttest')
Barry Warsawe11e3de1999-01-28 19:51:51 +0000240 try:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300241 with open(filename, 'r') as fp:
242 next_test = fp.read().strip()
243 tests = [next_test]
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200244 except OSError:
Barry Warsawe11e3de1999-01-28 19:51:51 +0000245 pass
Tim Petersc5000df2002-06-02 21:42:01 +0000246
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300247 if ns.fromfile:
Tim Petersc5000df2002-06-02 21:42:01 +0000248 tests = []
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300249 with open(os.path.join(support.SAVEDCWD, ns.fromfile)) as fp:
250 count_pat = re.compile(r'\[\s*\d+/\s*\d+\]')
251 for line in fp:
252 line = count_pat.sub('', line)
253 guts = line.split() # assuming no test has whitespace in its name
254 if guts and not guts[0].startswith('#'):
255 tests.extend(guts)
Tim Petersc5000df2002-06-02 21:42:01 +0000256
257 # Strip .py extensions.
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300258 removepy(ns.args)
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000259 removepy(tests)
Tim Petersc5000df2002-06-02 21:42:01 +0000260
Guido van Rossum6c74fea1998-08-25 12:29:08 +0000261 stdtests = STDTESTS[:]
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000262 nottests = NOTTESTS.copy()
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300263 if ns.exclude:
264 for arg in ns.args:
Guido van Rossum6c74fea1998-08-25 12:29:08 +0000265 if arg in stdtests:
266 stdtests.remove(arg)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000267 nottests.add(arg)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300268 ns.args = []
Florent Xicluna0e62a142010-03-06 17:34:48 +0000269
270 # For a partial run, we do not need to clutter the output.
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300271 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 +0000272 # Print basic platform information
273 print("==", platform.python_implementation(), *sys.version.split())
Florent Xiclunaec882212010-08-09 16:56:43 +0000274 print("== ", platform.platform(aliased=True),
275 "%s-endian" % sys.byteorder)
Christian Heimes985ecdc2013-11-20 11:46:18 +0100276 print("== ", "hash algorithm:", sys.hash_info.algorithm,
277 "64bit" if sys.maxsize > 2**32 else "32bit")
Florent Xicluna0e62a142010-03-06 17:34:48 +0000278 print("== ", os.getcwd())
Antoine Pitrou3c4402f2011-01-03 20:38:52 +0000279 print("Testing with flags:", sys.flags)
Florent Xicluna0e62a142010-03-06 17:34:48 +0000280
R David Murrayb588f8d2011-03-24 14:42:58 -0400281 # if testdir is set, then we are not running the python tests suite, so
282 # don't add default tests to be executed or skipped (pass empty values)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300283 if ns.testdir:
284 alltests = findtests(ns.testdir, list(), set())
R David Murrayb588f8d2011-03-24 14:42:58 -0400285 else:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300286 alltests = findtests(ns.testdir, stdtests, nottests)
R David Murrayb588f8d2011-03-24 14:42:58 -0400287
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300288 selected = tests or ns.args or alltests
289 if ns.single:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000290 selected = selected[:1]
R. David Murrayef1992b2009-12-16 15:19:27 +0000291 try:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000292 next_single_test = alltests[alltests.index(selected[0])+1]
R. David Murrayef1992b2009-12-16 15:19:27 +0000293 except IndexError:
294 next_single_test = None
R David Murrayc3bf78a2012-10-27 17:07:05 -0400295 # Remove all the selected tests that precede start if it's set.
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300296 if ns.start:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000297 try:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300298 del selected[:selected.index(ns.start)]
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000299 except ValueError:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300300 print("Couldn't find starting test (%s), using all tests" % ns.start)
301 if ns.randomize:
302 if ns.random_seed is None:
303 ns.random_seed = random.randrange(10000000)
304 random.seed(ns.random_seed)
305 print("Using random seed", ns.random_seed)
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000306 random.shuffle(selected)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300307 if ns.trace:
Georg Brandl33c28812009-04-01 23:07:29 +0000308 import trace, tempfile
Vinay Sajip7ded1f02012-05-26 03:45:29 +0100309 tracer = trace.Trace(ignoredirs=[sys.base_prefix, sys.base_exec_prefix,
Georg Brandl33c28812009-04-01 23:07:29 +0000310 tempfile.gettempdir()],
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000311 trace=False, count=True)
R. David Murray7dc72cc2009-11-14 16:13:02 +0000312
Christian Heimesb186d002008-03-18 15:15:01 +0000313 test_times = []
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300314 support.verbose = ns.verbose # Tell tests to be moderately quiet
315 support.use_resources = ns.use_resources
Guido van Rossum5796d262000-04-21 21:35:06 +0000316 save_modules = sys.modules.keys()
Antoine Pitrou88909542009-06-29 13:54:42 +0000317
318 def accumulate_result(test, result):
319 ok, test_time = result
320 test_times.append((test_time, test))
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000321 if ok == PASSED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000322 good.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000323 elif ok == FAILED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000324 bad.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000325 elif ok == ENV_CHANGED:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000326 environment_changed.append(test)
327 elif ok == SKIPPED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000328 skipped.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000329 elif ok == RESOURCE_DENIED:
330 skipped.append(test)
331 resource_denieds.append(test)
Antoine Pitrou88909542009-06-29 13:54:42 +0000332
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300333 if ns.forever:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000334 def test_forever(tests=list(selected)):
R. David Murray7dc72cc2009-11-14 16:13:02 +0000335 while True:
336 for test in tests:
337 yield test
338 if bad:
339 return
340 tests = test_forever()
Georg Brandle8e02e32010-08-03 07:56:50 +0000341 test_count = ''
342 test_count_width = 3
R. David Murray7dc72cc2009-11-14 16:13:02 +0000343 else:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000344 tests = iter(selected)
Georg Brandle8e02e32010-08-03 07:56:50 +0000345 test_count = '/{}'.format(len(selected))
346 test_count_width = len(test_count) - 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000347
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300348 if ns.use_mp:
Victor Stinner45df8202010-04-28 22:31:17 +0000349 try:
350 from threading import Thread
Brett Cannon260fbe82013-07-04 18:16:15 -0400351 except ImportError:
Victor Stinner45df8202010-04-28 22:31:17 +0000352 print("Multiprocess option requires thread support")
353 sys.exit(2)
Georg Brandl1b37e872010-03-14 10:45:50 +0000354 from queue import Queue
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100355 debug_output_pat = re.compile(r"\[\d+ refs, \d+ blocks\]$")
Antoine Pitrou88909542009-06-29 13:54:42 +0000356 output = Queue()
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200357 pending = MultiprocessTests(tests)
Antoine Pitrou88909542009-06-29 13:54:42 +0000358 def work():
359 # A worker thread.
Neal Norwitz14ca3272006-02-28 18:05:43 +0000360 try:
Antoine Pitrou88909542009-06-29 13:54:42 +0000361 while True:
362 try:
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200363 test = next(pending)
R. David Murray7dc72cc2009-11-14 16:13:02 +0000364 except StopIteration:
R. David Murray27144602009-10-19 15:26:16 +0000365 output.put((None, None, None, None))
Antoine Pitrou88909542009-06-29 13:54:42 +0000366 return
Eli Bendersky7f5c22c2013-09-02 08:57:21 -0700367 retcode, stdout, stderr = run_test_in_subprocess(test, ns)
R. David Murray27144602009-10-19 15:26:16 +0000368 # Strip last refcount output line if it exists, since it
369 # comes from the shutdown of the interpreter in the subcommand.
370 stderr = debug_output_pat.sub("", stderr)
371 stdout, _, result = stdout.strip().rpartition("\n")
Victor Stinner4b739882011-03-31 18:02:36 +0200372 if retcode != 0:
373 result = (CHILD_ERROR, "Exit code %s" % retcode)
374 output.put((test, stdout.rstrip(), stderr.rstrip(), result))
375 return
R. David Murray7dc72cc2009-11-14 16:13:02 +0000376 if not result:
377 output.put((None, None, None, None))
378 return
Antoine Pitrou88909542009-06-29 13:54:42 +0000379 result = json.loads(result)
R. David Murray27144602009-10-19 15:26:16 +0000380 output.put((test, stdout.rstrip(), stderr.rstrip(), result))
Antoine Pitrou88909542009-06-29 13:54:42 +0000381 except BaseException:
R. David Murray27144602009-10-19 15:26:16 +0000382 output.put((None, None, None, None))
Neal Norwitz14ca3272006-02-28 18:05:43 +0000383 raise
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300384 workers = [Thread(target=work) for i in range(ns.use_mp)]
Antoine Pitrou88909542009-06-29 13:54:42 +0000385 for worker in workers:
386 worker.start()
387 finished = 0
Georg Brandldee7b852010-08-02 18:59:52 +0000388 test_index = 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000389 try:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300390 while finished < ns.use_mp:
R. David Murray7dc72cc2009-11-14 16:13:02 +0000391 test, stdout, stderr, result = output.get()
392 if test is None:
393 finished += 1
394 continue
Victor Stinnera2a895c2011-05-23 23:14:05 +0200395 accumulate_result(test, result)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300396 if not ns.quiet:
Ezio Melotti84f75c62011-05-24 01:00:10 +0300397 fmt = "[{1:{0}}{2}/{3}] {4}" if bad else "[{1:{0}}{2}] {4}"
398 print(fmt.format(
Victor Stinnera2a895c2011-05-23 23:14:05 +0200399 test_count_width, test_index, test_count,
400 len(bad), test))
R. David Murray7dc72cc2009-11-14 16:13:02 +0000401 if stdout:
402 print(stdout)
403 if stderr:
404 print(stderr, file=sys.stderr)
Antoine Pitrou82372582012-06-27 17:41:07 +0200405 sys.stdout.flush()
406 sys.stderr.flush()
R. David Murray7dc72cc2009-11-14 16:13:02 +0000407 if result[0] == INTERRUPTED:
Victor Stinner29650112012-08-08 22:37:26 +0200408 raise KeyboardInterrupt
Victor Stinner4b739882011-03-31 18:02:36 +0200409 if result[0] == CHILD_ERROR:
Victor Stinner571e8fd2011-05-01 22:57:43 +0200410 raise Exception("Child error on {}: {}".format(test, result[1]))
Georg Brandldee7b852010-08-02 18:59:52 +0000411 test_index += 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000412 except KeyboardInterrupt:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000413 interrupted = True
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200414 pending.interrupted = True
Antoine Pitrou88909542009-06-29 13:54:42 +0000415 for worker in workers:
416 worker.join()
417 else:
Georg Brandldee7b852010-08-02 18:59:52 +0000418 for test_index, test in enumerate(tests, 1):
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300419 if not ns.quiet:
Ezio Melotti84f75c62011-05-24 01:00:10 +0300420 fmt = "[{1:{0}}{2}/{3}] {4}" if bad else "[{1:{0}}{2}] {4}"
421 print(fmt.format(
Victor Stinnera2a895c2011-05-23 23:14:05 +0200422 test_count_width, test_index, test_count, len(bad), test))
Antoine Pitrou88909542009-06-29 13:54:42 +0000423 sys.stdout.flush()
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300424 if ns.trace:
Antoine Pitrou88909542009-06-29 13:54:42 +0000425 # If we're tracing code coverage, then we don't exit with status
426 # if on a false return value from main.
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300427 tracer.runctx('runtest(test, ns.verbose, ns.quiet, timeout=ns.timeout)',
Antoine Pitrou88909542009-06-29 13:54:42 +0000428 globals=globals(), locals=vars())
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000429 else:
Antoine Pitrou88909542009-06-29 13:54:42 +0000430 try:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300431 result = runtest(test, ns.verbose, ns.quiet,
Eli Benderskye8de2962013-09-02 17:01:10 -0700432 ns.huntrleaks,
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300433 output_on_failure=ns.verbose3,
434 timeout=ns.timeout, failfast=ns.failfast,
435 match_tests=ns.match_tests)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000436 accumulate_result(test, result)
Antoine Pitrou88909542009-06-29 13:54:42 +0000437 except KeyboardInterrupt:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000438 interrupted = True
Antoine Pitrou88909542009-06-29 13:54:42 +0000439 break
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300440 if ns.findleaks:
Antoine Pitrou88909542009-06-29 13:54:42 +0000441 gc.collect()
442 if gc.garbage:
443 print("Warning: test created", len(gc.garbage), end=' ')
444 print("uncollectable object(s).")
445 # move the uncollectable objects somewhere so we don't see
446 # them again
447 found_garbage.extend(gc.garbage)
448 del gc.garbage[:]
449 # Unload the newly imported modules (best effort finalization)
450 for module in sys.modules.keys():
451 if module not in save_modules and module.startswith("test."):
452 support.unload(module)
Jeremy Hylton7a1ea0e2001-10-17 13:45:28 +0000453
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000454 if interrupted:
455 # print a newline after ^C
456 print()
457 print("Test suite interrupted by signal SIGINT.")
458 omitted = set(selected) - set(good) - set(bad) - set(skipped)
459 print(count(len(omitted), "test"), "omitted:")
460 printlist(omitted)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300461 if good and not ns.quiet:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000462 if not bad and not skipped and not interrupted and len(good) > 1:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000463 print("All", end=' ')
464 print(count(len(good), "test"), "OK.")
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300465 if ns.print_slow:
Christian Heimesb186d002008-03-18 15:15:01 +0000466 test_times.sort(reverse=True)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000467 print("10 slowest tests:")
Christian Heimesb186d002008-03-18 15:15:01 +0000468 for time, test in test_times[:10]:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000469 print("%s: %.1fs" % (test, time))
Guido van Rossum152494a1996-12-20 03:12:20 +0000470 if bad:
Zachary Ware9a47ed82015-08-08 22:03:27 -0500471 print(count(len(bad), "test"), "failed:")
472 printlist(bad)
Vinay Sajipf9596182012-03-02 01:01:13 +0000473 if environment_changed:
474 print("{} altered the execution environment:".format(
475 count(len(environment_changed), "test")))
476 printlist(environment_changed)
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300477 if skipped and not ns.quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000478 print(count(len(skipped), "test"), "skipped:")
Tim Petersa45da922001-08-12 03:45:50 +0000479 printlist(skipped)
Barry Warsawe11e3de1999-01-28 19:51:51 +0000480
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300481 if ns.verbose2 and bad:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000482 print("Re-running failed tests in verbose mode")
Zachary Ware920a3352015-08-04 21:54:54 -0500483 for test in bad[:]:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000484 print("Re-running test %r in verbose mode" % test)
Tim Peters922dd7d2006-03-10 23:37:10 +0000485 sys.stdout.flush()
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000486 try:
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300487 ns.verbose = True
Eli Benderskye8de2962013-09-02 17:01:10 -0700488 ok = runtest(test, True, ns.quiet, ns.huntrleaks,
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300489 timeout=ns.timeout)
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000490 except KeyboardInterrupt:
491 # print a newline separate from the ^C
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000492 print()
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000493 break
Zachary Ware920a3352015-08-04 21:54:54 -0500494 else:
495 if ok[0] in {PASSED, ENV_CHANGED, SKIPPED, RESOURCE_DENIED}:
496 bad.remove(test)
497 else:
498 if bad:
499 print(count(len(bad), 'test'), "failed again:")
500 printlist(bad)
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000501
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300502 if ns.single:
R. David Murrayef1992b2009-12-16 15:19:27 +0000503 if next_single_test:
504 with open(filename, 'w') as fp:
505 fp.write(next_single_test + '\n')
Barry Warsawe11e3de1999-01-28 19:51:51 +0000506 else:
507 os.unlink(filename)
508
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300509 if ns.trace:
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000510 r = tracer.results()
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300511 r.write_results(show_missing=True, summary=True, coverdir=ns.coverdir)
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000512
Serhiy Storchaka64f7c4e2013-08-29 12:26:23 +0300513 if ns.runleaks:
Skip Montanaro0179a182004-06-06 15:53:18 +0000514 os.system("leaks %d" % os.getpid())
515
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000516 sys.exit(len(bad) > 0 or interrupted)
Barry Warsaw08fca522001-08-20 22:33:46 +0000517
Guido van Rossum152494a1996-12-20 03:12:20 +0000518
R David Murrayb588f8d2011-03-24 14:42:58 -0400519# small set of tests to determine if we have a basically functioning interpreter
520# (i.e. if any of these fail, then anything else is likely to follow)
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000521STDTESTS = [
Guido van Rossum152494a1996-12-20 03:12:20 +0000522 'test_grammar',
523 'test_opcodes',
Guido van Rossumd8faa362007-04-27 19:54:29 +0000524 'test_dict',
Guido van Rossum152494a1996-12-20 03:12:20 +0000525 'test_builtin',
526 'test_exceptions',
527 'test_types',
Collin Winter7afaa882007-03-08 19:54:43 +0000528 'test_unittest',
529 'test_doctest',
530 'test_doctest2',
Eli Benderskyd18a0472011-07-27 20:21:45 +0300531 'test_support'
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000532]
Guido van Rossum152494a1996-12-20 03:12:20 +0000533
R David Murrayb588f8d2011-03-24 14:42:58 -0400534# set of tests that we don't want to be executed when using regrtest
R David Murray57648302011-03-24 14:57:05 -0400535NOTTESTS = set()
Guido van Rossum152494a1996-12-20 03:12:20 +0000536
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000537def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
Guido van Rossum152494a1996-12-20 03:12:20 +0000538 """Return a list of all applicable test modules."""
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000539 testdir = findtestdir(testdir)
Guido van Rossum152494a1996-12-20 03:12:20 +0000540 names = os.listdir(testdir)
541 tests = []
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000542 others = set(stdtests) | nottests
Guido van Rossum152494a1996-12-20 03:12:20 +0000543 for name in names:
R David Murray661720e2011-03-21 15:14:34 -0400544 mod, ext = os.path.splitext(name)
545 if mod[:5] == "test_" and ext in (".py", "") and mod not in others:
546 tests.append(mod)
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000547 return stdtests + sorted(tests)
Guido van Rossum152494a1996-12-20 03:12:20 +0000548
Antoine Pitrou09f2e6f2012-07-26 00:45:19 +0200549# We do not use a generator so multiple threads can call next().
550class MultiprocessTests(object):
551
552 """A thread-safe iterator over tests for multiprocess mode."""
553
554 def __init__(self, tests):
555 self.interrupted = False
556 self.lock = threading.Lock()
557 self.tests = tests
558
559 def __iter__(self):
560 return self
561
562 def __next__(self):
563 with self.lock:
564 if self.interrupted:
565 raise StopIteration('tests interrupted')
566 return next(self.tests)
567
Victor Stinnerf58087b2010-05-02 17:24:51 +0000568def replace_stdout():
569 """Set stdout encoder error handler to backslashreplace (as stderr error
570 handler) to avoid UnicodeEncodeError when printing a traceback"""
Victor Stinner4b2b43d2011-01-05 03:54:26 +0000571 import atexit
572
Victor Stinnerf58087b2010-05-02 17:24:51 +0000573 stdout = sys.stdout
574 sys.stdout = open(stdout.fileno(), 'w',
575 encoding=stdout.encoding,
Victor Stinner4b2b43d2011-01-05 03:54:26 +0000576 errors="backslashreplace",
Victor Stinnerbe621032011-05-25 02:01:55 +0200577 closefd=False,
578 newline='\n')
Victor Stinner4b2b43d2011-01-05 03:54:26 +0000579
580 def restore_stdout():
581 sys.stdout.close()
582 sys.stdout = stdout
583 atexit.register(restore_stdout)
Victor Stinnerf58087b2010-05-02 17:24:51 +0000584
Antoine Pitrou88909542009-06-29 13:54:42 +0000585def runtest(test, verbose, quiet,
Eli Benderskye8de2962013-09-02 17:01:10 -0700586 huntrleaks=False, use_resources=None,
Antoine Pitrouf83e4ac2011-07-29 23:57:10 +0200587 output_on_failure=False, failfast=False, match_tests=None,
588 timeout=None):
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000589 """Run a single test.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000590
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000591 test -- the name of the test
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000592 verbose -- if true, print more messages
Trent Mickf29f47b2000-08-11 19:02:59 +0000593 quiet -- if true, don't print 'skipped' messages (probably redundant)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000594 huntrleaks -- run multiple times to test for leaks; requires a debug
595 build; a triple corresponding to -R's three arguments
Eli Benderskye5eebed2013-09-02 16:52:25 -0700596 use_resources -- list of extra resources to use
Victor Stinner8313d6a2011-06-29 15:22:26 +0200597 output_on_failure -- if true, display test output on failure
Victor Stinner0cc8d592011-03-31 18:10:13 +0200598 timeout -- dump the traceback and exit if a test takes more than
599 timeout seconds
Eli Benderskye5eebed2013-09-02 16:52:25 -0700600 failfast, match_tests -- See regrtest command-line flags for these.
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000601
Eli Benderskye5eebed2013-09-02 16:52:25 -0700602 Returns the tuple result, test_time, where result is one of the constants:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000603 INTERRUPTED KeyboardInterrupt when run under -j
604 RESOURCE_DENIED test skipped because resource denied
605 SKIPPED test skipped for some other reason
606 ENV_CHANGED test failed because it changed the execution environment
607 FAILED test failed
608 PASSED test passed
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000609 """
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000610
Antoine Pitrou88909542009-06-29 13:54:42 +0000611 if use_resources is not None:
612 support.use_resources = use_resources
Victor Stinner30196882011-06-03 12:53:26 +0200613 use_timeout = (timeout is not None)
Victor Stinner7d648a02011-03-31 18:27:50 +0200614 if use_timeout:
Victor Stinner4de701b2013-06-17 20:27:10 +0200615 faulthandler.dump_traceback_later(timeout, exit=True)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000616 try:
Antoine Pitroub9c73e82011-07-29 23:53:38 +0200617 support.match_tests = match_tests
Antoine Pitrou216a3bc2011-07-23 22:33:39 +0200618 if failfast:
619 support.failfast = True
Victor Stinner8313d6a2011-06-29 15:22:26 +0200620 if output_on_failure:
Victor Stinnerea95de72011-06-29 15:34:48 +0200621 support.verbose = True
622
623 # Reuse the same instance to all calls to runtest(). Some
624 # tests keep a reference to sys.stdout or sys.stderr
625 # (eg. test_argparse).
Victor Stinner8313d6a2011-06-29 15:22:26 +0200626 if runtest.stringio is None:
Victor Stinnerfcc2a212011-06-29 20:01:29 +0200627 stream = io.StringIO()
628 runtest.stringio = stream
629 else:
630 stream = runtest.stringio
631 stream.seek(0)
632 stream.truncate()
Victor Stinner8313d6a2011-06-29 15:22:26 +0200633
634 orig_stdout = sys.stdout
Victor Stinnera7c33e52011-06-29 13:00:54 +0200635 orig_stderr = sys.stderr
Victor Stinner8313d6a2011-06-29 15:22:26 +0200636 try:
Victor Stinnerea95de72011-06-29 15:34:48 +0200637 sys.stdout = stream
638 sys.stderr = stream
Victor Stinner8313d6a2011-06-29 15:22:26 +0200639 result = runtest_inner(test, verbose, quiet, huntrleaks,
Eli Benderskye8de2962013-09-02 17:01:10 -0700640 display_failure=False)
Victor Stinner8313d6a2011-06-29 15:22:26 +0200641 if result[0] == FAILED:
Victor Stinnerea95de72011-06-29 15:34:48 +0200642 output = stream.getvalue()
Victor Stinner8313d6a2011-06-29 15:22:26 +0200643 orig_stderr.write(output)
644 orig_stderr.flush()
645 finally:
646 sys.stdout = orig_stdout
647 sys.stderr = orig_stderr
Victor Stinnera7c33e52011-06-29 13:00:54 +0200648 else:
Victor Stinnerea95de72011-06-29 15:34:48 +0200649 support.verbose = verbose # Tell tests to be moderately quiet
Eli Benderskye8de2962013-09-02 17:01:10 -0700650 result = runtest_inner(test, verbose, quiet, huntrleaks,
Victor Stinnera7c33e52011-06-29 13:00:54 +0200651 display_failure=not verbose)
Antoine Pitrou293954d2011-03-23 23:01:49 +0100652 return result
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000653 finally:
Victor Stinner7d648a02011-03-31 18:27:50 +0200654 if use_timeout:
Victor Stinner934676a2013-06-17 20:35:08 +0200655 faulthandler.cancel_dump_traceback_later()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000656 cleanup_test_droppings(test, verbose)
Victor Stinner8313d6a2011-06-29 15:22:26 +0200657runtest.stringio = None
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000658
Nick Coghlan6ead5522009-10-18 13:19:33 +0000659# Unit tests are supposed to leave the execution environment unchanged
660# once they complete. But sometimes tests have bugs, especially when
661# tests fail, and the changes to environment go on to mess up other
662# tests. This can cause issues with buildbot stability, since tests
663# are run in random order and so problems may appear to come and go.
664# There are a few things we can save and restore to mitigate this, and
665# the following context manager handles this task.
666
667class saved_test_environment:
668 """Save bits of the test environment and restore them at block exit.
669
670 with saved_test_environment(testname, verbose, quiet):
671 #stuff
672
673 Unless quiet is True, a warning is printed to stderr if any of
674 the saved items was changed by the test. The attribute 'changed'
675 is initially False, but is set to True if a change is detected.
676
677 If verbose is more than 1, the before and after state of changed
678 items is also printed.
679 """
680
681 changed = False
682
683 def __init__(self, testname, verbose=0, quiet=False):
684 self.testname = testname
685 self.verbose = verbose
686 self.quiet = quiet
687
688 # To add things to save and restore, add a name XXX to the resources list
689 # and add corresponding get_XXX/restore_XXX functions. get_XXX should
690 # return the value to be saved and compared against a second call to the
691 # get function when test execution completes. restore_XXX should accept
692 # the saved value and restore the resource using it. It will be called if
693 # and only if a change in the value is detected.
694 #
695 # Note: XXX will have any '.' replaced with '_' characters when determining
696 # the corresponding method names.
697
698 resources = ('sys.argv', 'cwd', 'sys.stdin', 'sys.stdout', 'sys.stderr',
Brett Cannon29c0e4f2010-03-20 22:22:57 +0000699 'os.environ', 'sys.path', 'sys.path_hooks', '__import__',
Nick Coghlan7bd5dbe2010-12-05 07:17:25 +0000700 'warnings.filters', 'asyncore.socket_map',
Ezio Melotti45763d02011-03-20 15:34:28 +0200701 'logging._handlers', 'logging._handlerList', 'sys.gettrace',
Richard Oudkerk83d7dea2013-08-29 12:51:11 +0100702 'sys.warnoptions',
703 # multiprocessing.process._cleanup() may release ref
704 # to a thread, so check processes first.
705 'multiprocessing.process._dangling', 'threading._dangling',
Éric Araujoec177c12012-06-24 03:27:43 -0400706 'sysconfig._CONFIG_VARS', 'sysconfig._INSTALL_SCHEMES',
Serhiy Storchakaa3a100b2015-03-30 01:28:02 +0300707 'files', 'locale', 'warnings.showwarning',
Éric Araujo28df8de2011-09-19 05:10:45 +0200708 )
Nick Coghlan6ead5522009-10-18 13:19:33 +0000709
710 def get_sys_argv(self):
711 return id(sys.argv), sys.argv, sys.argv[:]
712 def restore_sys_argv(self, saved_argv):
713 sys.argv = saved_argv[1]
714 sys.argv[:] = saved_argv[2]
715
716 def get_cwd(self):
717 return os.getcwd()
718 def restore_cwd(self, saved_cwd):
719 os.chdir(saved_cwd)
720
721 def get_sys_stdout(self):
722 return sys.stdout
723 def restore_sys_stdout(self, saved_stdout):
724 sys.stdout = saved_stdout
725
726 def get_sys_stderr(self):
727 return sys.stderr
728 def restore_sys_stderr(self, saved_stderr):
729 sys.stderr = saved_stderr
730
731 def get_sys_stdin(self):
732 return sys.stdin
733 def restore_sys_stdin(self, saved_stdin):
734 sys.stdin = saved_stdin
735
736 def get_os_environ(self):
737 return id(os.environ), os.environ, dict(os.environ)
738 def restore_os_environ(self, saved_environ):
739 os.environ = saved_environ[1]
740 os.environ.clear()
741 os.environ.update(saved_environ[2])
742
743 def get_sys_path(self):
744 return id(sys.path), sys.path, sys.path[:]
745 def restore_sys_path(self, saved_path):
746 sys.path = saved_path[1]
747 sys.path[:] = saved_path[2]
748
Brett Cannon055470a2010-02-19 15:57:10 +0000749 def get_sys_path_hooks(self):
750 return id(sys.path_hooks), sys.path_hooks, sys.path_hooks[:]
751 def restore_sys_path_hooks(self, saved_hooks):
752 sys.path_hooks = saved_hooks[1]
753 sys.path_hooks[:] = saved_hooks[2]
754
Brett Cannon31f59292011-02-21 19:29:56 +0000755 def get_sys_gettrace(self):
756 return sys.gettrace()
757 def restore_sys_gettrace(self, trace_fxn):
758 sys.settrace(trace_fxn)
759
Brett Cannon055470a2010-02-19 15:57:10 +0000760 def get___import__(self):
Brett Cannon45071902010-06-14 22:22:54 +0000761 return builtins.__import__
Brett Cannon055470a2010-02-19 15:57:10 +0000762 def restore___import__(self, import_):
Brett Cannon45071902010-06-14 22:22:54 +0000763 builtins.__import__ = import_
Brett Cannon055470a2010-02-19 15:57:10 +0000764
Brett Cannon29c0e4f2010-03-20 22:22:57 +0000765 def get_warnings_filters(self):
766 return id(warnings.filters), warnings.filters, warnings.filters[:]
767 def restore_warnings_filters(self, saved_filters):
768 warnings.filters = saved_filters[1]
769 warnings.filters[:] = saved_filters[2]
770
Antoine Pitroub14ac8c2010-08-16 00:28:05 +0000771 def get_asyncore_socket_map(self):
772 asyncore = sys.modules.get('asyncore')
Antoine Pitrouaa879652010-10-29 11:54:38 +0000773 # XXX Making a copy keeps objects alive until __exit__ gets called.
774 return asyncore and asyncore.socket_map.copy() or {}
Antoine Pitroub14ac8c2010-08-16 00:28:05 +0000775 def restore_asyncore_socket_map(self, saved_map):
776 asyncore = sys.modules.get('asyncore')
777 if asyncore is not None:
Antoine Pitrouaa879652010-10-29 11:54:38 +0000778 asyncore.close_all(ignore_all=True)
Antoine Pitroub14ac8c2010-08-16 00:28:05 +0000779 asyncore.socket_map.update(saved_map)
780
Éric Araujoff913062011-11-29 16:45:07 +0100781 def get_shutil_archive_formats(self):
782 # we could call get_archives_formats() but that only returns the
783 # registry keys; we want to check the values too (the functions that
784 # are registered)
785 return shutil._ARCHIVE_FORMATS, shutil._ARCHIVE_FORMATS.copy()
786 def restore_shutil_archive_formats(self, saved):
787 shutil._ARCHIVE_FORMATS = saved[0]
788 shutil._ARCHIVE_FORMATS.clear()
789 shutil._ARCHIVE_FORMATS.update(saved[1])
790
791 def get_shutil_unpack_formats(self):
792 return shutil._UNPACK_FORMATS, shutil._UNPACK_FORMATS.copy()
793 def restore_shutil_unpack_formats(self, saved):
794 shutil._UNPACK_FORMATS = saved[0]
795 shutil._UNPACK_FORMATS.clear()
796 shutil._UNPACK_FORMATS.update(saved[1])
797
Nick Coghlan7d819752010-12-05 06:45:03 +0000798 def get_logging__handlers(self):
799 # _handlers is a WeakValueDictionary
Nick Coghlan7bd5dbe2010-12-05 07:17:25 +0000800 return id(logging._handlers), logging._handlers, logging._handlers.copy()
Nick Coghlan7d819752010-12-05 06:45:03 +0000801 def restore_logging__handlers(self, saved_handlers):
802 # Can't easily revert the logging state
803 pass
804
Nick Coghlan7bd5dbe2010-12-05 07:17:25 +0000805 def get_logging__handlerList(self):
806 # _handlerList is a list of weakrefs to handlers
807 return id(logging._handlerList), logging._handlerList, logging._handlerList[:]
808 def restore_logging__handlerList(self, saved_handlerList):
809 # Can't easily revert the logging state
810 pass
811
Ezio Melotti0123e052011-03-20 15:09:26 +0200812 def get_sys_warnoptions(self):
813 return id(sys.warnoptions), sys.warnoptions, sys.warnoptions[:]
814 def restore_sys_warnoptions(self, saved_options):
815 sys.warnoptions = saved_options[1]
816 sys.warnoptions[:] = saved_options[2]
817
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200818 # Controlling dangling references to Thread objects can make it easier
819 # to track reference leaks.
820 def get_threading__dangling(self):
821 if not threading:
822 return None
823 # This copies the weakrefs without making any strong reference
824 return threading._dangling.copy()
825 def restore_threading__dangling(self, saved):
826 if not threading:
827 return
828 threading._dangling.clear()
829 threading._dangling.update(saved)
830
831 # Same for Process objects
832 def get_multiprocessing_process__dangling(self):
833 if not multiprocessing:
834 return None
Richard Oudkerk83d7dea2013-08-29 12:51:11 +0100835 # Unjoined process objects can survive after process exits
836 multiprocessing.process._cleanup()
Antoine Pitrouc081c0c2011-07-15 22:12:24 +0200837 # This copies the weakrefs without making any strong reference
838 return multiprocessing.process._dangling.copy()
839 def restore_multiprocessing_process__dangling(self, saved):
840 if not multiprocessing:
841 return
842 multiprocessing.process._dangling.clear()
843 multiprocessing.process._dangling.update(saved)
844
Éric Araujo28df8de2011-09-19 05:10:45 +0200845 def get_sysconfig__CONFIG_VARS(self):
846 # make sure the dict is initialized
847 sysconfig.get_config_var('prefix')
848 return (id(sysconfig._CONFIG_VARS), sysconfig._CONFIG_VARS,
849 dict(sysconfig._CONFIG_VARS))
850 def restore_sysconfig__CONFIG_VARS(self, saved):
851 sysconfig._CONFIG_VARS = saved[1]
852 sysconfig._CONFIG_VARS.clear()
853 sysconfig._CONFIG_VARS.update(saved[2])
854
Éric Araujoec177c12012-06-24 03:27:43 -0400855 def get_sysconfig__INSTALL_SCHEMES(self):
856 return (id(sysconfig._INSTALL_SCHEMES), sysconfig._INSTALL_SCHEMES,
857 sysconfig._INSTALL_SCHEMES.copy())
858 def restore_sysconfig__INSTALL_SCHEMES(self, saved):
859 sysconfig._INSTALL_SCHEMES = saved[1]
860 sysconfig._INSTALL_SCHEMES.clear()
861 sysconfig._INSTALL_SCHEMES.update(saved[2])
Éric Araujo28df8de2011-09-19 05:10:45 +0200862
Serhiy Storchakaa3a100b2015-03-30 01:28:02 +0300863 def get_files(self):
864 return sorted(fn + ('/' if os.path.isdir(fn) else '')
865 for fn in os.listdir())
866 def restore_files(self, saved_value):
867 fn = support.TESTFN
868 if fn not in saved_value and (fn + '/') not in saved_value:
869 if os.path.isfile(fn):
870 support.unlink(fn)
871 elif os.path.isdir(fn):
872 support.rmtree(fn)
Éric Araujo28df8de2011-09-19 05:10:45 +0200873
Victor Stinnerd9ccf7f2013-06-17 20:40:05 +0200874 _lc = [getattr(locale, lc) for lc in dir(locale)
Victor Stinner546ccf02013-06-17 21:28:14 +0200875 if lc.startswith('LC_')]
Brett Cannon49e835b2013-04-01 14:11:37 -0400876 def get_locale(self):
877 pairings = []
878 for lc in self._lc:
879 try:
Victor Stinner546ccf02013-06-17 21:28:14 +0200880 pairings.append((lc, locale.setlocale(lc, None)))
Victor Stinnerd9ccf7f2013-06-17 20:40:05 +0200881 except (TypeError, ValueError):
Brett Cannon49e835b2013-04-01 14:11:37 -0400882 continue
883 return pairings
884 def restore_locale(self, saved):
885 for lc, setting in saved:
886 locale.setlocale(lc, setting)
887
Brett Cannon6d26eba2013-06-16 15:20:48 -0400888 def get_warnings_showwarning(self):
889 return warnings.showwarning
890 def restore_warnings_showwarning(self, fxn):
891 warnings.showwarning = fxn
892
Nick Coghlan6ead5522009-10-18 13:19:33 +0000893 def resource_info(self):
894 for name in self.resources:
895 method_suffix = name.replace('.', '_')
896 get_name = 'get_' + method_suffix
897 restore_name = 'restore_' + method_suffix
898 yield name, getattr(self, get_name), getattr(self, restore_name)
899
900 def __enter__(self):
901 self.saved_values = dict((name, get()) for name, get, restore
902 in self.resource_info())
903 return self
904
905 def __exit__(self, exc_type, exc_val, exc_tb):
Antoine Pitrouaa879652010-10-29 11:54:38 +0000906 saved_values = self.saved_values
907 del self.saved_values
Nick Coghlan6ead5522009-10-18 13:19:33 +0000908 for name, get, restore in self.resource_info():
909 current = get()
Antoine Pitrouaa879652010-10-29 11:54:38 +0000910 original = saved_values.pop(name)
Nick Coghlan6ead5522009-10-18 13:19:33 +0000911 # Check for changes to the resource's value
912 if current != original:
913 self.changed = True
914 restore(original)
915 if not self.quiet:
916 print("Warning -- {} was modified by {}".format(
917 name, self.testname),
918 file=sys.stderr)
919 if self.verbose > 1:
920 print(" Before: {}\n After: {} ".format(
921 original, current),
922 file=sys.stderr)
923 return False
924
925
Victor Stinnera7c33e52011-06-29 13:00:54 +0200926def runtest_inner(test, verbose, quiet,
Eli Benderskye8de2962013-09-02 17:01:10 -0700927 huntrleaks=False, display_failure=True):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000928 support.unload(test)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000929
Antoine Pitrou88909542009-06-29 13:54:42 +0000930 test_time = 0.0
Collin Wintera5503d52009-05-15 01:20:21 +0000931 refleak = False # True if the test leaked references.
Guido van Rossum152494a1996-12-20 03:12:20 +0000932 try:
R. David Murray0bc11ae2009-10-18 22:18:17 +0000933 if test.startswith('test.'):
934 abstest = test
935 else:
936 # Always import it from the test package
937 abstest = 'test.' + test
938 with saved_test_environment(test, verbose, quiet) as environment:
939 start_time = time.time()
Brett Cannon613cf252012-11-14 13:42:51 -0500940 the_module = importlib.import_module(abstest)
R David Murray78fc25c2012-04-09 08:55:42 -0400941 # If the test has a test_main, that will run the appropriate
942 # tests. If not, use normal unittest test loading.
943 test_runner = getattr(the_module, "test_main", None)
944 if test_runner is None:
Zachary Ware69fb6a42014-08-04 11:15:10 -0500945 def test_runner():
946 loader = unittest.TestLoader()
947 tests = loader.loadTestsFromModule(the_module)
Victor Stinner5d575392015-01-06 14:05:03 +0100948 for error in loader.errors:
949 print(error, file=sys.stderr)
950 if loader.errors:
951 raise Exception("errors while loading tests")
Zachary Ware69fb6a42014-08-04 11:15:10 -0500952 support.run_unittest(tests)
R David Murray78fc25c2012-04-09 08:55:42 -0400953 test_runner()
R. David Murray0bc11ae2009-10-18 22:18:17 +0000954 if huntrleaks:
Eli Benderskye5eebed2013-09-02 16:52:25 -0700955 refleak = dash_R(the_module, test, test_runner, huntrleaks)
R. David Murray0bc11ae2009-10-18 22:18:17 +0000956 test_time = time.time() - start_time
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000957 except support.ResourceDenied as msg:
Fred Drake9a0db072003-02-03 15:19:30 +0000958 if not quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000959 print(test, "skipped --", msg)
Fred Drake9a0db072003-02-03 15:19:30 +0000960 sys.stdout.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000961 return RESOURCE_DENIED, test_time
R. David Murraya21e4ca2009-03-31 23:16:50 +0000962 except unittest.SkipTest as msg:
Trent Mickf29f47b2000-08-11 19:02:59 +0000963 if not quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000964 print(test, "skipped --", msg)
Guido van Rossum3cda93e2002-09-13 21:28:03 +0000965 sys.stdout.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000966 return SKIPPED, test_time
Fred Drakefe5c22a2000-08-18 16:04:05 +0000967 except KeyboardInterrupt:
968 raise
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000969 except support.TestFailed as msg:
Victor Stinnera7c33e52011-06-29 13:00:54 +0200970 if display_failure:
971 print("test", test, "failed --", msg, file=sys.stderr)
972 else:
973 print("test", test, "failed", file=sys.stderr)
R. David Murray11cabcf2010-09-29 01:08:05 +0000974 sys.stderr.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000975 return FAILED, test_time
Guido van Rossum9e48b271997-07-16 01:56:13 +0000976 except:
Antoine Pitrou779a5b02011-03-21 19:55:16 +0100977 msg = traceback.format_exc()
978 print("test", test, "crashed --", msg, file=sys.stderr)
R. David Murray11cabcf2010-09-29 01:08:05 +0000979 sys.stderr.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000980 return FAILED, test_time
Guido van Rossum152494a1996-12-20 03:12:20 +0000981 else:
Collin Wintera5503d52009-05-15 01:20:21 +0000982 if refleak:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000983 return FAILED, test_time
Nick Coghlan6ead5522009-10-18 13:19:33 +0000984 if environment.changed:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000985 return ENV_CHANGED, test_time
986 return PASSED, test_time
Guido van Rossum0fcca4e2001-09-21 20:31:52 +0000987
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000988def cleanup_test_droppings(testname, verbose):
989 import shutil
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000990 import stat
Antoine Pitrouc14efc42010-10-29 19:34:45 +0000991 import gc
992
993 # First kill any dangling references to open files etc.
994 # This can also issue some ResourceWarnings which would otherwise get
Antoine Pitrou2b40efd2010-10-29 19:36:37 +0000995 # triggered during the following test run, and possibly produce failures.
Antoine Pitrouc14efc42010-10-29 19:34:45 +0000996 gc.collect()
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000997
998 # Try to clean up junk commonly left behind. While tests shouldn't leave
999 # any files or directories behind, when a test fails that can be tedious
1000 # for it to arrange. The consequences can be especially nasty on Windows,
1001 # since if a test leaves a file open, it cannot be deleted by name (while
1002 # there's nothing we can do about that here either, we can display the
1003 # name of the offending test, which is a real help).
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001004 for name in (support.TESTFN,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001005 "db_home",
1006 ):
1007 if not os.path.exists(name):
1008 continue
1009
1010 if os.path.isdir(name):
1011 kind, nuker = "directory", shutil.rmtree
1012 elif os.path.isfile(name):
1013 kind, nuker = "file", os.unlink
1014 else:
1015 raise SystemError("os.path says %r exists but is neither "
1016 "directory nor file" % name)
1017
1018 if verbose:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001019 print("%r left behind %s %r" % (testname, kind, name))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001020 try:
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001021 # if we have chmod, fix possible permissions problems
1022 # that might prevent cleanup
1023 if (hasattr(os, 'chmod')):
1024 os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001025 nuker(name)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001026 except Exception as msg:
1027 print(("%r left behind %s %r and it couldn't be "
1028 "removed: %s" % (testname, kind, name, msg)), file=sys.stderr)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001029
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001030def dash_R(the_module, test, indirect_test, huntrleaks):
Collin Wintera5503d52009-05-15 01:20:21 +00001031 """Run a test multiple times, looking for reference leaks.
1032
1033 Returns:
1034 False if the test didn't leak references; True if we detected refleaks.
1035 """
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001036 # This code is hackish and inelegant, but it seems to do the job.
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001037 import copyreg
1038 import collections.abc
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001039
1040 if not hasattr(sys, 'gettotalrefcount'):
1041 raise Exception("Tracking reference leaks requires a debug build "
1042 "of Python")
1043
1044 # Save current values for dash_R_cleanup() to restore.
1045 fs = warnings.filters[:]
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001046 ps = copyreg.dispatch_table.copy()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001047 pic = sys.path_importer_cache.copy()
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001048 try:
1049 import zipimport
Brett Cannon260fbe82013-07-04 18:16:15 -04001050 except ImportError:
Benjamin Petersoncf626032014-02-16 14:52:01 -05001051 zdc = None # Run unmodified on platforms without zipimport support
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001052 else:
1053 zdc = zipimport._zip_directory_cache.copy()
Christian Heimes93852662007-12-01 12:22:32 +00001054 abcs = {}
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001055 for abc in [getattr(collections.abc, a) for a in collections.abc.__all__]:
Christian Heimesbe5b30b2008-03-03 19:18:51 +00001056 if not isabstract(abc):
Christian Heimes93852662007-12-01 12:22:32 +00001057 continue
1058 for obj in abc.__subclasses__() + [abc]:
1059 abcs[obj] = obj._abc_registry.copy()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001060
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001061 nwarmup, ntracked, fname = huntrleaks
Ezio Melotti184bdfb2010-02-18 09:37:05 +00001062 fname = os.path.join(support.SAVEDCWD, fname)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001063 repcount = nwarmup + ntracked
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001064 rc_deltas = [0] * repcount
1065 alloc_deltas = [0] * repcount
1066
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001067 print("beginning", repcount, "repetitions", file=sys.stderr)
1068 print(("1234567890"*(repcount//10 + 1))[:repcount], file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +00001069 sys.stderr.flush()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001070 for i in range(repcount):
R David Murray14d080e2013-01-12 11:34:38 -05001071 indirect_test()
Benjamin Petersonf617fa82014-02-16 14:53:55 -05001072 alloc_after, rc_after = dash_R_cleanup(fs, ps, pic, zdc, abcs)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001073 sys.stderr.write('.')
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001074 sys.stderr.flush()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001075 if i >= nwarmup:
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001076 rc_deltas[i] = rc_after - rc_before
1077 alloc_deltas[i] = alloc_after - alloc_before
1078 alloc_before, rc_before = alloc_after, rc_after
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001079 print(file=sys.stderr)
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001080 # These checkers return False on success, True on failure
1081 def check_rc_deltas(deltas):
1082 return any(deltas)
1083 def check_alloc_deltas(deltas):
1084 # At least 1/3rd of 0s
1085 if 3 * deltas.count(0) < len(deltas):
1086 return True
1087 # Nothing else than 1s, 0s and -1s
1088 if not set(deltas) <= {1,0,-1}:
1089 return True
1090 return False
1091 failed = False
1092 for deltas, item_name, checker in [
1093 (rc_deltas, 'references', check_rc_deltas),
1094 (alloc_deltas, 'memory blocks', check_alloc_deltas)]:
1095 if checker(deltas):
1096 msg = '%s leaked %s %s, sum=%s' % (
1097 test, deltas[nwarmup:], item_name, sum(deltas))
1098 print(msg, file=sys.stderr)
1099 sys.stderr.flush()
1100 with open(fname, "a") as refrep:
1101 print(msg, file=refrep)
1102 refrep.flush()
1103 failed = True
1104 return failed
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001105
Benjamin Petersoncf626032014-02-16 14:52:01 -05001106def dash_R_cleanup(fs, ps, pic, zdc, abcs):
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001107 import gc, copyreg
Brett Cannonf4fd9932008-05-10 21:11:46 +00001108 import _strptime, linecache
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001109 import urllib.parse, urllib.request, mimetypes, doctest
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001110 import struct, filecmp, collections.abc
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001111 from distutils.dir_util import _path_created
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001112 from weakref import WeakSet
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001113
Christian Heimesdae2a892008-04-19 00:55:37 +00001114 # Clear the warnings registry, so they can be displayed again
1115 for mod in sys.modules.values():
1116 if hasattr(mod, '__warningregistry__'):
1117 del mod.__warningregistry__
1118
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001119 # Restore some original values.
1120 warnings.filters[:] = fs
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001121 copyreg.dispatch_table.clear()
1122 copyreg.dispatch_table.update(ps)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001123 sys.path_importer_cache.clear()
1124 sys.path_importer_cache.update(pic)
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001125 try:
1126 import zipimport
Brett Cannon260fbe82013-07-04 18:16:15 -04001127 except ImportError:
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001128 pass # Run unmodified on platforms without zipimport support
1129 else:
1130 zipimport._zip_directory_cache.clear()
1131 zipimport._zip_directory_cache.update(zdc)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001132
Christian Heimes26855632008-01-27 23:50:43 +00001133 # clear type cache
Christian Heimes15ebc882008-02-04 18:48:49 +00001134 sys._clear_type_cache()
Christian Heimes26855632008-01-27 23:50:43 +00001135
Guido van Rossum3de862d2007-08-18 00:10:33 +00001136 # Clear ABC registries, restoring previously saved ABC registries.
Raymond Hettinger158c9c22011-02-22 00:41:50 +00001137 for abc in [getattr(collections.abc, a) for a in collections.abc.__all__]:
Christian Heimesbe5b30b2008-03-03 19:18:51 +00001138 if not isabstract(abc):
Christian Heimes941973a2007-11-30 21:53:03 +00001139 continue
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001140 for obj in abc.__subclasses__() + [abc]:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001141 obj._abc_registry = abcs.get(obj, WeakSet()).copy()
Guido van Rossumc1e315d2007-08-20 19:29:24 +00001142 obj._abc_cache.clear()
1143 obj._abc_negative_cache.clear()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001144
Antoine Pitrou046467c2009-10-30 18:30:35 +00001145 # Flush standard output, so that buffered data is sent to the OS and
1146 # associated Python objects are reclaimed.
1147 for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__):
1148 if stream is not None:
1149 stream.flush()
1150
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001151 # Clear assorted module caches.
1152 _path_created.clear()
1153 re.purge()
1154 _strptime._regex_cache.clear()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001155 urllib.parse.clear_cache()
1156 urllib.request.urlcleanup()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001157 linecache.clearcache()
1158 mimetypes._default_mime_types()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001159 filecmp._cache.clear()
Christian Heimesa34706f2008-01-04 03:06:10 +00001160 struct._clearcache()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001161 doctest.master = None
Meador Inge11e38132011-11-25 22:33:32 -06001162 try:
1163 import ctypes
Brett Cannon260fbe82013-07-04 18:16:15 -04001164 except ImportError:
Meador Inge11e38132011-11-25 22:33:32 -06001165 # Don't worry about resetting the cache if ctypes is not supported
1166 pass
1167 else:
1168 ctypes._reset_cache()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001169
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001170 # Collect cyclic trash and read memory statistics immediately after.
1171 func1 = sys.getallocatedblocks
1172 func2 = sys.gettotalrefcount
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001173 gc.collect()
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001174 return func1(), func2()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001175
Stefan Krah5c3ddc82012-08-17 23:09:48 +02001176def warm_caches():
1177 # char cache
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001178 s = bytes(range(256))
1179 for i in range(256):
1180 s[i:i+1]
Stefan Krah5c3ddc82012-08-17 23:09:48 +02001181 # unicode cache
1182 x = [chr(i) for i in range(256)]
1183 # int cache
1184 x = list(range(-5, 257))
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001185
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001186def findtestdir(path=None):
1187 return path or os.path.dirname(__file__) or os.curdir
Guido van Rossum152494a1996-12-20 03:12:20 +00001188
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001189def removepy(names):
1190 if not names:
1191 return
1192 for idx, name in enumerate(names):
1193 basename, ext = os.path.splitext(name)
1194 if ext == '.py':
1195 names[idx] = basename
Tim Petersc5000df2002-06-02 21:42:01 +00001196
Guido van Rossum152494a1996-12-20 03:12:20 +00001197def count(n, word):
1198 if n == 1:
Guido van Rossum41360a41998-03-26 19:42:58 +00001199 return "%d %s" % (n, word)
Guido van Rossum152494a1996-12-20 03:12:20 +00001200 else:
Guido van Rossum41360a41998-03-26 19:42:58 +00001201 return "%d %ss" % (n, word)
Guido van Rossum152494a1996-12-20 03:12:20 +00001202
Tim Petersa45da922001-08-12 03:45:50 +00001203def printlist(x, width=70, indent=4):
Tim Peters7c7efe92002-08-23 17:55:54 +00001204 """Print the elements of iterable x to stdout.
Tim Petersa45da922001-08-12 03:45:50 +00001205
1206 Optional arg width (default 70) is the maximum line length.
1207 Optional arg indent (default 4) is the number of blanks with which to
1208 begin each line.
1209 """
1210
Tim Petersba78bc42002-07-04 19:45:06 +00001211 from textwrap import fill
1212 blanks = ' ' * indent
Florent Xiclunafd1b0932010-03-28 00:25:02 +00001213 # Print the sorted list: 'x' may be a '--random' list or a set()
1214 print(fill(' '.join(str(elt) for elt in sorted(x)), width,
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001215 initial_indent=blanks, subsequent_indent=blanks))
Tim Petersa45da922001-08-12 03:45:50 +00001216
Tim Petersb5b7b782001-08-12 01:20:39 +00001217
Chris Jerdonek517e9252013-02-27 09:02:53 -08001218def main_in_temp_cwd():
1219 """Run main() in a temporary working directory."""
Michael Foord3ab34cc2010-12-03 12:27:40 +00001220 if sysconfig.is_python_build():
Antoine Pitrouee429342011-04-16 18:53:59 +02001221 try:
Michael Foord3ab34cc2010-12-03 12:27:40 +00001222 os.mkdir(TEMPDIR)
Florent Xicluna68f71a32011-10-28 16:06:23 +02001223 except FileExistsError:
1224 pass
Michael Foord3ab34cc2010-12-03 12:27:40 +00001225
1226 # Define a writable temp dir that will be used as cwd while running
1227 # the tests. The name of the dir includes the pid to allow parallel
1228 # testing (see the -j option).
Chris Jerdonek517e9252013-02-27 09:02:53 -08001229 test_cwd = 'test_python_{}'.format(os.getpid())
1230 test_cwd = os.path.join(TEMPDIR, test_cwd)
Michael Foord3ab34cc2010-12-03 12:27:40 +00001231
Chris Jerdonek517e9252013-02-27 09:02:53 -08001232 # Run the tests in a context manager that temporarily changes the CWD to a
1233 # temporary and writable directory. If it's not possible to create or
1234 # change the CWD, the original CWD will be used. The original CWD is
1235 # available from support.SAVEDCWD.
1236 with support.temp_cwd(test_cwd, quiet=True):
1237 main()
1238
Nick Coghlan4c4c0f22010-12-03 07:44:33 +00001239
Guido van Rossum152494a1996-12-20 03:12:20 +00001240if __name__ == '__main__':
Nick Coghlan4c4c0f22010-12-03 07:44:33 +00001241 # Remove regrtest.py's own directory from the module search path. Despite
1242 # the elimination of implicit relative imports, this is still needed to
1243 # ensure that submodules of the test package do not inappropriately appear
1244 # as top-level modules even when people (or buildbots!) invoke regrtest.py
1245 # directly instead of using the -m switch
1246 mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
1247 i = len(sys.path)
1248 while i >= 0:
1249 i -= 1
1250 if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
1251 del sys.path[i]
1252
Florent Xiclunadc69e722010-09-13 16:35:02 +00001253 # findtestdir() gets the dirname out of __file__, so we have to make it
1254 # absolute before changing the working directory.
1255 # For example __file__ may be relative when running trace or profile.
1256 # See issue #9323.
1257 __file__ = os.path.abspath(__file__)
1258
1259 # sanity check
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001260 assert __file__ == os.path.abspath(sys.argv[0])
Ezio Melotti184bdfb2010-02-18 09:37:05 +00001261
Chris Jerdonek517e9252013-02-27 09:02:53 -08001262 main_in_temp_cwd()