blob: 64d0a7c27199ededfeb8b0151e1b963515c7d49f [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"""
4Usage:
Guido van Rossum152494a1996-12-20 03:12:20 +00005
R. David Murray0ba81e02010-04-26 17:02:32 +00006python -m test.regrtest [options] [test_name1 [test_name2 ...]]
7python path/to/Lib/test/regrtest.py [options] [test_name1 [test_name2 ...]]
Guido van Rossum152494a1996-12-20 03:12:20 +00008
R. David Murray0ba81e02010-04-26 17:02:32 +00009
10If no arguments or options are provided, finds all files matching
11the pattern "test_*" in the Lib/test subdirectory and runs
12them in alphabetical order (but see -M and -u, below, for exceptions).
13
14For more rigorous testing, it is useful to use the following
15command line:
16
17python -E -tt -Wd -3 -m test.regrtest [options] [test_name1 ...]
18
19
20Options:
Guido van Rossum152494a1996-12-20 03:12:20 +000021
Georg Brandl96f78972009-10-27 21:02:11 +000022-h/--help -- print this text and exit
23
24Verbosity
25
26-v/--verbose -- run tests in verbose mode with output to stdout
27-w/--verbose2 -- re-run failed tests in verbose mode
28-W/--verbose3 -- re-run failed tests in verbose mode immediately
29-d/--debug -- print traceback for failed tests
R. David Murray0ba81e02010-04-26 17:02:32 +000030-q/--quiet -- no output unless one or more tests fail
Georg Brandl96f78972009-10-27 21:02:11 +000031-S/--slow -- print the slowest 10 tests
32
33Selecting tests
34
R. David Murray0ba81e02010-04-26 17:02:32 +000035-r/--random -- randomize test execution order (see below)
Georg Brandl96f78972009-10-27 21:02:11 +000036-f/--fromfile -- read names of tests to run from a file (see below)
37-x/--exclude -- arguments are tests to *exclude*
R. David Murray0ba81e02010-04-26 17:02:32 +000038-s/--single -- single step through a set of tests (see below)
Georg Brandl96f78972009-10-27 21:02:11 +000039-u/--use RES1,RES2,...
40 -- specify which special resource intensive tests to run
41-M/--memlimit LIMIT
42 -- run very large memory-consuming tests
43
44Special runs
45
46-l/--findleaks -- if GC is available detect tests that leak memory
47-L/--runleaks -- run the leaks(1) command just before exit
48-R/--huntrleaks RUNCOUNTS
49 -- search for reference leaks (needs debug build, v. slow)
50-j/--multiprocess PROCESSES
51 -- run PROCESSES processes at once
R. David Murray0ba81e02010-04-26 17:02:32 +000052-T/--coverage -- turn on code coverage tracing using the trace module
Georg Brandl96f78972009-10-27 21:02:11 +000053-D/--coverdir DIRECTORY
54 -- Directory where coverage files are put
55-N/--nocoverdir -- Put coverage files alongside modules
56-t/--threshold THRESHOLD
57 -- call gc.set_threshold(THRESHOLD)
58-n/--nowindows -- suppress error message boxes on Windows
R. David Murray0ba81e02010-04-26 17:02:32 +000059-F/--forever -- run the specified tests in a loop, until an error happens
Guido van Rossum152494a1996-12-20 03:12:20 +000060
R. David Murray0ba81e02010-04-26 17:02:32 +000061
62Additional Option Details:
Guido van Rossumf58ed251997-03-07 21:04:33 +000063
Collin Winterfd12f492009-03-29 04:05:05 +000064-r randomizes test execution order. You can use --randseed=int to provide a
65int seed value for the randomizer; this is useful for reproducing troublesome
66test orders.
67
R. David Murray0ba81e02010-04-26 17:02:32 +000068-s On the first invocation of regrtest using -s, the first test file found
69or the first test file given on the command line is run, and the name of
70the next test is recorded in a file named pynexttest. If run from the
71Python build directory, pynexttest is located in the 'build' subdirectory,
72otherwise it is located in tempfile.gettempdir(). On subsequent runs,
73the test in pynexttest is run, and the next test is written to pynexttest.
74When the last test has been run, pynexttest is deleted. In this way it
75is possible to single step through the test files. This is useful when
76doing memory analysis on the Python interpreter, which process tends to
77consume too many resources to run the full regression test non-stop.
Barry Warsawe11e3de1999-01-28 19:51:51 +000078
Neal Norwitz94fa2ee2008-03-31 02:55:15 +000079-S is used to continue running tests after an aborted run. It will
80maintain the order a standard run (ie, this assumes -r is not used).
81This is useful after the tests have prematurely stopped for some external
82reason and you want to start running from where you left off rather
83than starting from the beginning.
84
Guido van Rossum9e9d4f82002-06-07 15:17:03 +000085-f reads the names of tests from the file given as f's argument, one
86or more test names per line. Whitespace is ignored. Blank lines and
87lines beginning with '#' are ignored. This is especially useful for
88whittling down failures involving interactions among tests.
Tim Petersc5000df2002-06-02 21:42:01 +000089
Skip Montanaro0179a182004-06-06 15:53:18 +000090-L causes the leaks(1) command to be run just before exit if it exists.
91leaks(1) is available on Mac OS X and presumably on some other
92FreeBSD-derived systems.
93
Michael W. Hudson61147f62004-08-03 11:33:28 +000094-R runs each test several times and examines sys.gettotalrefcount() to
95see if the test appears to be leaking references. The argument should
96be of the form stab:run:fname where 'stab' is the number of times the
97test is run to let gettotalrefcount settle down, 'run' is the number
98of times further it is run and 'fname' is the name of the file the
99reports are written to. These parameters all have defaults (5, 4 and
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000100"reflog.txt" respectively), and the minimal invocation is '-R :'.
Michael W. Hudson61147f62004-08-03 11:33:28 +0000101
Thomas Wouters477c8d52006-05-27 19:21:47 +0000102-M runs tests that require an exorbitant amount of memory. These tests
103typically try to ascertain containers keep working when containing more than
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001042 billion objects, which only works on 64-bit systems. There are also some
105tests that try to exhaust the address space of the process, which only makes
106sense on 32-bit systems with at least 2Gb of memory. The passed-in memlimit,
Thomas Wouters477c8d52006-05-27 19:21:47 +0000107which is a string in the form of '2.5Gb', determines howmuch memory the
108tests will limit themselves to (but they may go slightly over.) The number
109shouldn't be more memory than the machine has (including swap memory). You
110should also keep in mind that swap memory is generally much, much slower
111than RAM, and setting memlimit to all available RAM or higher will heavily
112tax the machine. On the other hand, it is no use running these tests with a
113limit of less than 2.5Gb, and many require more than 20Gb. Tests that expect
114to use more than memlimit memory will be skipped. The big-memory tests
115generally run very, very long.
116
Guido van Rossum9e9d4f82002-06-07 15:17:03 +0000117-u is used to specify which special resource intensive tests to run,
118such as those requiring large file support or network connectivity.
119The argument is a comma-separated list of words indicating the
120resources to test. Currently only the following are defined:
Barry Warsaw08fca522001-08-20 22:33:46 +0000121
Fred Drake3a15dac2002-04-11 16:39:16 +0000122 all - Enable all special resources.
123
Guido van Rossum315aa362003-03-11 14:46:48 +0000124 audio - Tests that use the audio device. (There are known
125 cases of broken audio drivers that can crash Python or
126 even the Linux kernel.)
127
Andrew M. Kuchling2158df02001-10-22 15:26:09 +0000128 curses - Tests that use curses and will modify the terminal's
129 state and output modes.
Tim Peters1633a2e2001-10-30 05:56:40 +0000130
Guido van Rossum9e9d4f82002-06-07 15:17:03 +0000131 largefile - It is okay to run some test that may create huge
132 files. These tests can take a long time and may
133 consume >2GB of disk space temporarily.
Barry Warsaw08fca522001-08-20 22:33:46 +0000134
Guido van Rossum9e9d4f82002-06-07 15:17:03 +0000135 network - It is okay to run tests that use external network
136 resource, e.g. testing SSL support for sockets.
Martin v. Löwis1c6b1a22002-11-19 17:47:07 +0000137
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000138 decimal - Test the decimal module against a large suite that
139 verifies compliance with standards.
140
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000141 compiler - Allow test_tokenize to verify round-trip lexing on
142 every file in the test library.
Jeremy Hylton4336eda2004-08-07 19:25:33 +0000143
Tim Peterseba28be2005-03-28 01:08:02 +0000144 subprocess Run all tests for the subprocess module.
Peter Astrandf7f1bb72005-03-03 20:47:37 +0000145
Hye-Shik Changaaa2f1d2005-12-10 17:44:27 +0000146 urlfetch - It is okay to download files required on testing.
147
Guilherme Polo9de29af2009-01-28 20:40:48 +0000148 gui - Run tests that require a running GUI.
149
Fred Drake4dd0f7e2002-11-26 21:44:56 +0000150To enable all resources except one, use '-uall,-<resource>'. For
Georg Brandl1158a332009-06-04 09:30:30 +0000151example, to run all the tests except for the gui tests, give the
152option '-uall,-gui'.
Guido van Rossum152494a1996-12-20 03:12:20 +0000153"""
154
Brett Cannon45071902010-06-14 22:22:54 +0000155import builtins
Guido van Rossum152494a1996-12-20 03:12:20 +0000156import getopt
Antoine Pitrou88909542009-06-29 13:54:42 +0000157import json
Christian Heimesb186d002008-03-18 15:15:01 +0000158import os
Skip Montanaroab1c7912000-06-30 16:39:27 +0000159import random
Thomas Wouters9ada3d62006-04-21 09:47:09 +0000160import re
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000161import io
Christian Heimesb186d002008-03-18 15:15:01 +0000162import sys
163import time
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000164import traceback
Christian Heimesb186d002008-03-18 15:15:01 +0000165import warnings
Benjamin Petersone549ead2009-03-28 21:42:05 +0000166import unittest
Christian Heimesbe5b30b2008-03-03 19:18:51 +0000167from inspect import isabstract
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000168import tempfile
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000169import platform
170import sysconfig
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000171
Florent Xicluna64fb18e2010-03-06 14:43:34 +0000172
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000173# Some times __path__ and __file__ are not absolute (e.g. while running from
174# Lib/) and, if we change the CWD to run the tests in a temporary dir, some
175# imports might fail. This affects only the modules imported before os.chdir().
176# These modules are searched first in sys.path[0] (so '' -- the CWD) and if
177# they are found in the CWD their __file__ and __path__ will be relative (this
178# happens before the chdir). All the modules imported after the chdir, are
179# not found in the CWD, and since the other paths in sys.path[1:] are absolute
180# (site.py absolutize them), the __file__ and __path__ will be absolute too.
181# Therefore it is necessary to absolutize manually the __file__ and __path__ of
182# the packages to prevent later imports to fail when the CWD is different.
183for module in sys.modules.values():
184 if hasattr(module, '__path__'):
185 module.__path__ = [os.path.abspath(path) for path in module.__path__]
186 if hasattr(module, '__file__'):
187 module.__file__ = os.path.abspath(module.__file__)
188
Guido van Rossumdc15c272002-08-12 21:55:51 +0000189
Guido van Rossumbb484652002-12-02 09:56:21 +0000190# MacOSX (a.k.a. Darwin) has a default stack size that is too small
191# for deeply recursive regular expressions. We see this as crashes in
192# the Python test suite when running test_re.py and test_sre.py. The
193# fix is to set the stack limit to 2048.
194# This approach may also be useful for other Unixy platforms that
195# suffer from small default stack limits.
196if sys.platform == 'darwin':
197 try:
198 import resource
199 except ImportError:
200 pass
201 else:
202 soft, hard = resource.getrlimit(resource.RLIMIT_STACK)
203 newsoft = min(hard, max(soft, 1024*2048))
204 resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard))
205
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000206# Test result constants.
207PASSED = 1
208FAILED = 0
209ENV_CHANGED = -1
210SKIPPED = -2
211RESOURCE_DENIED = -3
212INTERRUPTED = -4
213
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000214from test import support
Fred Drake3a15dac2002-04-11 16:39:16 +0000215
Georg Brandl1158a332009-06-04 09:30:30 +0000216RESOURCE_NAMES = ('audio', 'curses', 'largefile', 'network',
Guilherme Polo9de29af2009-01-28 20:40:48 +0000217 'decimal', 'compiler', 'subprocess', 'urlfetch', 'gui')
Fred Drake3a15dac2002-04-11 16:39:16 +0000218
Florent Xiclunaec882212010-08-09 16:56:43 +0000219TEMPDIR = os.path.abspath(tempfile.gettempdir())
Fred Drake3a15dac2002-04-11 16:39:16 +0000220
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000221def usage(msg):
222 print(msg, file=sys.stderr)
223 print("Use --help for usage", file=sys.stderr)
224 sys.exit(2)
Barry Warsaw08fca522001-08-20 22:33:46 +0000225
226
Antoine Pitrou88909542009-06-29 13:54:42 +0000227def main(tests=None, testdir=None, verbose=0, quiet=False,
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000228 exclude=False, single=False, randomize=False, fromfile=None,
Walter Dörwaldaee4da62004-11-12 18:51:27 +0000229 findleaks=False, use_resources=None, trace=False, coverdir='coverage',
Collin Winterfd12f492009-03-29 04:05:05 +0000230 runleaks=False, huntrleaks=False, verbose2=False, print_slow=False,
R. David Murray7dc72cc2009-11-14 16:13:02 +0000231 random_seed=None, use_mp=None, verbose3=False, forever=False):
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000232 """Execute a test suite.
233
Thomas Wouters7e474022000-07-16 12:04:32 +0000234 This also parses command-line options and modifies its behavior
Fred Drake004d5e62000-10-23 17:22:08 +0000235 accordingly.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000236
237 tests -- a list of strings containing test names (optional)
238 testdir -- the directory in which to look for tests (optional)
239
240 Users other than the Python test suite will certainly want to
241 specify testdir; if it's omitted, the directory containing the
Fred Drake004d5e62000-10-23 17:22:08 +0000242 Python test suite is searched for.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000243
244 If the tests argument is omitted, the tests listed on the
245 command-line will be used. If that's empty, too, then all *.py
246 files beginning with test_ will be used.
Skip Montanaroab1c7912000-06-30 16:39:27 +0000247
Antoine Pitrou88909542009-06-29 13:54:42 +0000248 The other default arguments (verbose, quiet, exclude,
Collin Winterfd12f492009-03-29 04:05:05 +0000249 single, randomize, findleaks, use_resources, trace, coverdir,
250 print_slow, and random_seed) allow programmers calling main()
251 directly to set the values that would normally be set by flags
252 on the command line.
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000253 """
Fred Drake004d5e62000-10-23 17:22:08 +0000254
Victor Stinner1802d3f2010-05-19 17:11:19 +0000255 replace_stdout()
256
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000257 support.record_original_stdout(sys.stdout)
Guido van Rossum152494a1996-12-20 03:12:20 +0000258 try:
R. David Murray7dc72cc2009-11-14 16:13:02 +0000259 opts, args = getopt.getopt(sys.argv[1:], 'hvqxsSrf:lu:t:TD:NLR:FwWM:nj:',
Georg Brandl96f78972009-10-27 21:02:11 +0000260 ['help', 'verbose', 'verbose2', 'verbose3', 'quiet',
261 'exclude', 'single', 'slow', 'random', 'fromfile', 'findleaks',
262 'use=', 'threshold=', 'trace', 'coverdir=', 'nocoverdir',
R. David Murray7dc72cc2009-11-14 16:13:02 +0000263 'runleaks', 'huntrleaks=', 'memlimit=', 'randseed=',
264 'multiprocess=', 'slaveargs=', 'forever', 'debug', 'start=',
265 'nowindows'])
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000266 except getopt.error as msg:
267 usage(msg)
Barry Warsaw08fca522001-08-20 22:33:46 +0000268
269 # Defaults
Collin Winterfd12f492009-03-29 04:05:05 +0000270 if random_seed is None:
271 random_seed = random.randrange(10000000)
Barry Warsaw08fca522001-08-20 22:33:46 +0000272 if use_resources is None:
273 use_resources = []
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000274 debug = False
275 start = None
Guido van Rossum152494a1996-12-20 03:12:20 +0000276 for o, a in opts:
Barry Warsaw08fca522001-08-20 22:33:46 +0000277 if o in ('-h', '--help'):
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000278 print(__doc__)
279 return
Barry Warsaw08fca522001-08-20 22:33:46 +0000280 elif o in ('-v', '--verbose'):
281 verbose += 1
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000282 elif o in ('-w', '--verbose2'):
283 verbose2 = True
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000284 elif o in ('-d', '--debug'):
285 debug = True
Georg Brandl96f78972009-10-27 21:02:11 +0000286 elif o in ('-W', '--verbose3'):
287 verbose3 = True
Barry Warsaw08fca522001-08-20 22:33:46 +0000288 elif o in ('-q', '--quiet'):
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000289 quiet = True;
Barry Warsaw08fca522001-08-20 22:33:46 +0000290 verbose = 0
Barry Warsaw08fca522001-08-20 22:33:46 +0000291 elif o in ('-x', '--exclude'):
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000292 exclude = True
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000293 elif o in ('-S', '--start'):
294 start = a
Barry Warsaw08fca522001-08-20 22:33:46 +0000295 elif o in ('-s', '--single'):
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000296 single = True
Christian Heimesb186d002008-03-18 15:15:01 +0000297 elif o in ('-S', '--slow'):
298 print_slow = True
Barry Warsaw08fca522001-08-20 22:33:46 +0000299 elif o in ('-r', '--randomize'):
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000300 randomize = True
Collin Winterfd12f492009-03-29 04:05:05 +0000301 elif o == '--randseed':
302 random_seed = int(a)
Tim Petersc5000df2002-06-02 21:42:01 +0000303 elif o in ('-f', '--fromfile'):
304 fromfile = a
Barry Warsaw08fca522001-08-20 22:33:46 +0000305 elif o in ('-l', '--findleaks'):
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000306 findleaks = True
Skip Montanaro0179a182004-06-06 15:53:18 +0000307 elif o in ('-L', '--runleaks'):
308 runleaks = True
Guido van Rossum9e9d4f82002-06-07 15:17:03 +0000309 elif o in ('-t', '--threshold'):
310 import gc
311 gc.set_threshold(int(a))
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000312 elif o in ('-T', '--coverage'):
313 trace = True
Walter Dörwaldaee4da62004-11-12 18:51:27 +0000314 elif o in ('-D', '--coverdir'):
315 coverdir = os.path.join(os.getcwd(), a)
316 elif o in ('-N', '--nocoverdir'):
317 coverdir = None
Michael W. Hudson61147f62004-08-03 11:33:28 +0000318 elif o in ('-R', '--huntrleaks'):
319 huntrleaks = a.split(':')
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000320 if len(huntrleaks) not in (2, 3):
321 print(a, huntrleaks)
322 usage('-R takes 2 or 3 colon-separated arguments')
323 if not huntrleaks[0]:
Michael W. Hudson61147f62004-08-03 11:33:28 +0000324 huntrleaks[0] = 5
325 else:
326 huntrleaks[0] = int(huntrleaks[0])
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000327 if not huntrleaks[1]:
Michael W. Hudson61147f62004-08-03 11:33:28 +0000328 huntrleaks[1] = 4
329 else:
330 huntrleaks[1] = int(huntrleaks[1])
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000331 if len(huntrleaks) == 2 or not huntrleaks[2]:
332 huntrleaks[2:] = ["reflog.txt"]
333 # Avoid false positives due to the character cache in
334 # stringobject.c filling slowly with random data
335 warm_char_cache()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000336 elif o in ('-M', '--memlimit'):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000337 support.set_memlimit(a)
Barry Warsaw08fca522001-08-20 22:33:46 +0000338 elif o in ('-u', '--use'):
Guido van Rossumfe3f6962001-09-06 16:09:41 +0000339 u = [x.lower() for x in a.split(',')]
340 for r in u:
Fred Drake3a15dac2002-04-11 16:39:16 +0000341 if r == 'all':
Fred Drake4dd0f7e2002-11-26 21:44:56 +0000342 use_resources[:] = RESOURCE_NAMES
343 continue
344 remove = False
345 if r[0] == '-':
346 remove = True
347 r = r[1:]
Fred Drake3a15dac2002-04-11 16:39:16 +0000348 if r not in RESOURCE_NAMES:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000349 usage('Invalid -u/--use option: ' + a)
Fred Drake4dd0f7e2002-11-26 21:44:56 +0000350 if remove:
351 if r in use_resources:
352 use_resources.remove(r)
353 elif r not in use_resources:
Andrew MacIntyree41abab2002-04-30 12:11:04 +0000354 use_resources.append(r)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000355 elif o in ('-n', '--nowindows'):
356 import msvcrt
357 msvcrt.SetErrorMode(msvcrt.SEM_FAILCRITICALERRORS|
358 msvcrt.SEM_NOALIGNMENTFAULTEXCEPT|
359 msvcrt.SEM_NOGPFAULTERRORBOX|
360 msvcrt.SEM_NOOPENFILEERRORBOX)
361 try:
362 msvcrt.CrtSetReportMode
363 except AttributeError:
364 # release build
365 pass
366 else:
367 for m in [msvcrt.CRT_WARN, msvcrt.CRT_ERROR, msvcrt.CRT_ASSERT]:
368 msvcrt.CrtSetReportMode(m, msvcrt.CRTDBG_MODE_FILE)
369 msvcrt.CrtSetReportFile(m, msvcrt.CRTDBG_FILE_STDERR)
R. David Murray7dc72cc2009-11-14 16:13:02 +0000370 elif o in ('-F', '--forever'):
371 forever = True
Antoine Pitrou88909542009-06-29 13:54:42 +0000372 elif o in ('-j', '--multiprocess'):
373 use_mp = int(a)
374 elif o == '--slaveargs':
375 args, kwargs = json.loads(a)
376 try:
377 result = runtest(*args, **kwargs)
378 except BaseException as e:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000379 result = INTERRUPTED, e.__class__.__name__
Antoine Pitrou88909542009-06-29 13:54:42 +0000380 sys.stdout.flush()
381 print() # Force a newline (just in case)
382 print(json.dumps(result))
383 sys.exit(0)
R. David Murray35768ad2009-11-15 00:23:21 +0000384 else:
385 print(("No handler for option {}. Please report this as a bug "
Georg Brandldee7b852010-08-02 18:59:52 +0000386 "at http://bugs.python.org.").format(o), file=sys.stderr)
R. David Murray35768ad2009-11-15 00:23:21 +0000387 sys.exit(1)
Tim Petersc5000df2002-06-02 21:42:01 +0000388 if single and fromfile:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000389 usage("-s and -f don't go together!")
Antoine Pitrou88909542009-06-29 13:54:42 +0000390 if use_mp and trace:
Florent Xicluna64fb18e2010-03-06 14:43:34 +0000391 usage("-T and -j don't go together!")
Antoine Pitrou88909542009-06-29 13:54:42 +0000392 if use_mp and findleaks:
Florent Xicluna64fb18e2010-03-06 14:43:34 +0000393 usage("-l and -j don't go together!")
Barry Warsaw08fca522001-08-20 22:33:46 +0000394
Guido van Rossum152494a1996-12-20 03:12:20 +0000395 good = []
396 bad = []
397 skipped = []
Fred Drake9a0db072003-02-03 15:19:30 +0000398 resource_denieds = []
Nick Coghlan6ead5522009-10-18 13:19:33 +0000399 environment_changed = []
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000400 interrupted = False
Barry Warsawe11e3de1999-01-28 19:51:51 +0000401
Neil Schemenauerd569f232000-09-22 15:29:28 +0000402 if findleaks:
Barry Warsawa873b032000-08-03 15:50:37 +0000403 try:
404 import gc
405 except ImportError:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000406 print('No GC available, disabling findleaks.')
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000407 findleaks = False
Barry Warsawa873b032000-08-03 15:50:37 +0000408 else:
Neil Schemenauer8a00abc2000-10-13 01:32:42 +0000409 # Uncomment the line below to report garbage that is not
410 # freeable by reference counting alone. By default only
411 # garbage that is not collectable by the GC is reported.
412 #gc.set_debug(gc.DEBUG_SAVEALL)
Neil Schemenauerd569f232000-09-22 15:29:28 +0000413 found_garbage = []
Barry Warsawa873b032000-08-03 15:50:37 +0000414
Barry Warsawe11e3de1999-01-28 19:51:51 +0000415 if single:
Florent Xiclunaec882212010-08-09 16:56:43 +0000416 filename = os.path.join(TEMPDIR, 'pynexttest')
Barry Warsawe11e3de1999-01-28 19:51:51 +0000417 try:
418 fp = open(filename, 'r')
R. David Murray7dc72cc2009-11-14 16:13:02 +0000419 next_test = fp.read().strip()
420 tests = [next_test]
Barry Warsawe11e3de1999-01-28 19:51:51 +0000421 fp.close()
422 except IOError:
423 pass
Tim Petersc5000df2002-06-02 21:42:01 +0000424
425 if fromfile:
426 tests = []
Ezio Melotti184bdfb2010-02-18 09:37:05 +0000427 fp = open(os.path.join(support.SAVEDCWD, fromfile))
Tim Petersc5000df2002-06-02 21:42:01 +0000428 for line in fp:
429 guts = line.split() # assuming no test has whitespace in its name
430 if guts and not guts[0].startswith('#'):
431 tests.extend(guts)
432 fp.close()
433
434 # Strip .py extensions.
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000435 removepy(args)
436 removepy(tests)
Tim Petersc5000df2002-06-02 21:42:01 +0000437
Guido van Rossum6c74fea1998-08-25 12:29:08 +0000438 stdtests = STDTESTS[:]
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000439 nottests = NOTTESTS.copy()
Guido van Rossum152494a1996-12-20 03:12:20 +0000440 if exclude:
Guido van Rossum6c74fea1998-08-25 12:29:08 +0000441 for arg in args:
442 if arg in stdtests:
443 stdtests.remove(arg)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000444 nottests.add(arg)
Guido van Rossum41360a41998-03-26 19:42:58 +0000445 args = []
Florent Xicluna0e62a142010-03-06 17:34:48 +0000446
447 # For a partial run, we do not need to clutter the output.
Florent Xiclunaec882212010-08-09 16:56:43 +0000448 if verbose or not (quiet or single or tests or args):
Florent Xicluna0e62a142010-03-06 17:34:48 +0000449 # Print basic platform information
450 print("==", platform.python_implementation(), *sys.version.split())
Florent Xiclunaec882212010-08-09 16:56:43 +0000451 print("== ", platform.platform(aliased=True),
452 "%s-endian" % sys.byteorder)
Florent Xicluna0e62a142010-03-06 17:34:48 +0000453 print("== ", os.getcwd())
454
R. David Murrayef1992b2009-12-16 15:19:27 +0000455 alltests = findtests(testdir, stdtests, nottests)
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000456 selected = tests or args or alltests
Barry Warsawe11e3de1999-01-28 19:51:51 +0000457 if single:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000458 selected = selected[:1]
R. David Murrayef1992b2009-12-16 15:19:27 +0000459 try:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000460 next_single_test = alltests[alltests.index(selected[0])+1]
R. David Murrayef1992b2009-12-16 15:19:27 +0000461 except IndexError:
462 next_single_test = None
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000463 # Remove all the tests that precede start if it's set.
464 if start:
465 try:
466 del tests[:tests.index(start)]
467 except ValueError:
468 print("Couldn't find starting test (%s), using all tests" % start)
Skip Montanaroab1c7912000-06-30 16:39:27 +0000469 if randomize:
Collin Winterfd12f492009-03-29 04:05:05 +0000470 random.seed(random_seed)
471 print("Using random seed", random_seed)
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000472 random.shuffle(selected)
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000473 if trace:
Georg Brandl33c28812009-04-01 23:07:29 +0000474 import trace, tempfile
475 tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,
476 tempfile.gettempdir()],
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000477 trace=False, count=True)
R. David Murray7dc72cc2009-11-14 16:13:02 +0000478
Christian Heimesb186d002008-03-18 15:15:01 +0000479 test_times = []
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000480 support.verbose = verbose # Tell tests to be moderately quiet
481 support.use_resources = use_resources
Guido van Rossum5796d262000-04-21 21:35:06 +0000482 save_modules = sys.modules.keys()
Antoine Pitrou88909542009-06-29 13:54:42 +0000483
484 def accumulate_result(test, result):
485 ok, test_time = result
486 test_times.append((test_time, test))
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000487 if ok == PASSED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000488 good.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000489 elif ok == FAILED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000490 bad.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000491 elif ok == ENV_CHANGED:
492 bad.append(test)
493 environment_changed.append(test)
494 elif ok == SKIPPED:
Antoine Pitrou88909542009-06-29 13:54:42 +0000495 skipped.append(test)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000496 elif ok == RESOURCE_DENIED:
497 skipped.append(test)
498 resource_denieds.append(test)
Antoine Pitrou88909542009-06-29 13:54:42 +0000499
R. David Murray7dc72cc2009-11-14 16:13:02 +0000500 if forever:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000501 def test_forever(tests=list(selected)):
R. David Murray7dc72cc2009-11-14 16:13:02 +0000502 while True:
503 for test in tests:
504 yield test
505 if bad:
506 return
507 tests = test_forever()
Georg Brandle8e02e32010-08-03 07:56:50 +0000508 test_count = ''
509 test_count_width = 3
R. David Murray7dc72cc2009-11-14 16:13:02 +0000510 else:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000511 tests = iter(selected)
Georg Brandle8e02e32010-08-03 07:56:50 +0000512 test_count = '/{}'.format(len(selected))
513 test_count_width = len(test_count) - 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000514
Antoine Pitrou88909542009-06-29 13:54:42 +0000515 if use_mp:
Victor Stinner45df8202010-04-28 22:31:17 +0000516 try:
517 from threading import Thread
518 except ImportError:
519 print("Multiprocess option requires thread support")
520 sys.exit(2)
Georg Brandl1b37e872010-03-14 10:45:50 +0000521 from queue import Queue
522 from subprocess import Popen, PIPE
Antoine Pitrou88909542009-06-29 13:54:42 +0000523 debug_output_pat = re.compile(r"\[\d+ refs\]$")
Antoine Pitrou88909542009-06-29 13:54:42 +0000524 output = Queue()
R. David Murray7dc72cc2009-11-14 16:13:02 +0000525 def tests_and_args():
526 for test in tests:
527 args_tuple = (
528 (test, verbose, quiet, testdir),
529 dict(huntrleaks=huntrleaks, use_resources=use_resources,
530 debug=debug)
531 )
532 yield (test, args_tuple)
533 pending = tests_and_args()
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +0000534 opt_args = support.args_from_interpreter_flags()
535 base_cmd = [sys.executable] + opt_args + ['-m', 'test.regrtest']
Antoine Pitrou88909542009-06-29 13:54:42 +0000536 def work():
537 # A worker thread.
Neal Norwitz14ca3272006-02-28 18:05:43 +0000538 try:
Antoine Pitrou88909542009-06-29 13:54:42 +0000539 while True:
540 try:
R. David Murray7dc72cc2009-11-14 16:13:02 +0000541 test, args_tuple = next(pending)
542 except StopIteration:
R. David Murray27144602009-10-19 15:26:16 +0000543 output.put((None, None, None, None))
Antoine Pitrou88909542009-06-29 13:54:42 +0000544 return
Antoine Pitrou88909542009-06-29 13:54:42 +0000545 # -E is needed by some tests, e.g. test_import
Antoine Pitrou1b03f2c2010-10-14 11:12:00 +0000546 popen = Popen(base_cmd + ['--slaveargs', json.dumps(args_tuple)],
R. David Murray27144602009-10-19 15:26:16 +0000547 stdout=PIPE, stderr=PIPE,
Antoine Pitrou36e778e2010-08-18 20:44:14 +0000548 universal_newlines=True,
549 close_fds=(os.name != 'nt'))
R. David Murray27144602009-10-19 15:26:16 +0000550 stdout, stderr = popen.communicate()
551 # Strip last refcount output line if it exists, since it
552 # comes from the shutdown of the interpreter in the subcommand.
553 stderr = debug_output_pat.sub("", stderr)
554 stdout, _, result = stdout.strip().rpartition("\n")
R. David Murray7dc72cc2009-11-14 16:13:02 +0000555 if not result:
556 output.put((None, None, None, None))
557 return
Antoine Pitrou88909542009-06-29 13:54:42 +0000558 result = json.loads(result)
R. David Murray27144602009-10-19 15:26:16 +0000559 output.put((test, stdout.rstrip(), stderr.rstrip(), result))
Antoine Pitrou88909542009-06-29 13:54:42 +0000560 except BaseException:
R. David Murray27144602009-10-19 15:26:16 +0000561 output.put((None, None, None, None))
Neal Norwitz14ca3272006-02-28 18:05:43 +0000562 raise
Antoine Pitrou88909542009-06-29 13:54:42 +0000563 workers = [Thread(target=work) for i in range(use_mp)]
564 for worker in workers:
565 worker.start()
566 finished = 0
Georg Brandldee7b852010-08-02 18:59:52 +0000567 test_index = 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000568 try:
569 while finished < use_mp:
570 test, stdout, stderr, result = output.get()
571 if test is None:
572 finished += 1
573 continue
Georg Brandldee7b852010-08-02 18:59:52 +0000574 if not quiet:
Georg Brandle8e02e32010-08-03 07:56:50 +0000575 print("[{1:{0}}{2}] {3}".format(
Georg Brandldee7b852010-08-02 18:59:52 +0000576 test_count_width, test_index, test_count, test))
R. David Murray7dc72cc2009-11-14 16:13:02 +0000577 if stdout:
578 print(stdout)
579 if stderr:
580 print(stderr, file=sys.stderr)
581 if result[0] == INTERRUPTED:
582 assert result[1] == 'KeyboardInterrupt'
583 raise KeyboardInterrupt # What else?
584 accumulate_result(test, result)
Georg Brandldee7b852010-08-02 18:59:52 +0000585 test_index += 1
R. David Murray7dc72cc2009-11-14 16:13:02 +0000586 except KeyboardInterrupt:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000587 interrupted = True
R. David Murray7dc72cc2009-11-14 16:13:02 +0000588 pending.close()
Antoine Pitrou88909542009-06-29 13:54:42 +0000589 for worker in workers:
590 worker.join()
591 else:
Georg Brandldee7b852010-08-02 18:59:52 +0000592 for test_index, test in enumerate(tests, 1):
Antoine Pitrou88909542009-06-29 13:54:42 +0000593 if not quiet:
Georg Brandle8e02e32010-08-03 07:56:50 +0000594 print("[{1:{0}}{2}] {3}".format(
Georg Brandldee7b852010-08-02 18:59:52 +0000595 test_count_width, test_index, test_count, test))
Antoine Pitrou88909542009-06-29 13:54:42 +0000596 sys.stdout.flush()
597 if trace:
598 # If we're tracing code coverage, then we don't exit with status
599 # if on a false return value from main.
600 tracer.runctx('runtest(test, verbose, quiet, testdir)',
601 globals=globals(), locals=vars())
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000602 else:
Antoine Pitrou88909542009-06-29 13:54:42 +0000603 try:
604 result = runtest(test, verbose, quiet,
605 testdir, huntrleaks, debug)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000606 accumulate_result(test, result)
607 if verbose3 and result[0] == FAILED:
Georg Brandl96f78972009-10-27 21:02:11 +0000608 print("Re-running test {} in verbose mode".format(test))
609 runtest(test, True, quiet, testdir, huntrleaks, debug)
Antoine Pitrou88909542009-06-29 13:54:42 +0000610 except KeyboardInterrupt:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000611 interrupted = True
Antoine Pitrou88909542009-06-29 13:54:42 +0000612 break
613 except:
614 raise
615 if findleaks:
616 gc.collect()
617 if gc.garbage:
618 print("Warning: test created", len(gc.garbage), end=' ')
619 print("uncollectable object(s).")
620 # move the uncollectable objects somewhere so we don't see
621 # them again
622 found_garbage.extend(gc.garbage)
623 del gc.garbage[:]
624 # Unload the newly imported modules (best effort finalization)
625 for module in sys.modules.keys():
626 if module not in save_modules and module.startswith("test."):
627 support.unload(module)
Jeremy Hylton7a1ea0e2001-10-17 13:45:28 +0000628
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000629 if interrupted:
630 # print a newline after ^C
631 print()
632 print("Test suite interrupted by signal SIGINT.")
633 omitted = set(selected) - set(good) - set(bad) - set(skipped)
634 print(count(len(omitted), "test"), "omitted:")
635 printlist(omitted)
Guido van Rossum152494a1996-12-20 03:12:20 +0000636 if good and not quiet:
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000637 if not bad and not skipped and not interrupted and len(good) > 1:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000638 print("All", end=' ')
639 print(count(len(good), "test"), "OK.")
Christian Heimesb186d002008-03-18 15:15:01 +0000640 if print_slow:
641 test_times.sort(reverse=True)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000642 print("10 slowest tests:")
Christian Heimesb186d002008-03-18 15:15:01 +0000643 for time, test in test_times[:10]:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000644 print("%s: %.1fs" % (test, time))
Guido van Rossum152494a1996-12-20 03:12:20 +0000645 if bad:
Nick Coghlan6ead5522009-10-18 13:19:33 +0000646 bad = sorted(set(bad) - set(environment_changed))
647 if bad:
648 print(count(len(bad), "test"), "failed:")
649 printlist(bad)
650 if environment_changed:
651 print("{} altered the execution environment:".format(
652 count(len(environment_changed), "test")))
653 printlist(environment_changed)
Guido van Rossum152494a1996-12-20 03:12:20 +0000654 if skipped and not quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000655 print(count(len(skipped), "test"), "skipped:")
Tim Petersa45da922001-08-12 03:45:50 +0000656 printlist(skipped)
Barry Warsawe11e3de1999-01-28 19:51:51 +0000657
Tim Petersb5b7b782001-08-12 01:20:39 +0000658 e = _ExpectedSkips()
Tim Petersa2be2d62001-08-12 02:01:09 +0000659 plat = sys.platform
Tim Petersb5b7b782001-08-12 01:20:39 +0000660 if e.isvalid():
Raymond Hettingera690a992003-11-16 16:17:49 +0000661 surprise = set(skipped) - e.getexpected() - set(resource_denieds)
Tim Petersb5b7b782001-08-12 01:20:39 +0000662 if surprise:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000663 print(count(len(surprise), "skip"), \
664 "unexpected on", plat + ":")
Tim Petersa45da922001-08-12 03:45:50 +0000665 printlist(surprise)
Tim Petersb5b7b782001-08-12 01:20:39 +0000666 else:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000667 print("Those skips are all expected on", plat + ".")
Tim Petersb5b7b782001-08-12 01:20:39 +0000668 else:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000669 print("Ask someone to teach regrtest.py about which tests are")
670 print("expected to get skipped on", plat + ".")
Tim Petersb5b7b782001-08-12 01:20:39 +0000671
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000672 if verbose2 and bad:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000673 print("Re-running failed tests in verbose mode")
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000674 for test in bad:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000675 print("Re-running test %r in verbose mode" % test)
Tim Peters922dd7d2006-03-10 23:37:10 +0000676 sys.stdout.flush()
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000677 try:
Antoine Pitrou88909542009-06-29 13:54:42 +0000678 verbose = True
679 ok = runtest(test, True, quiet, testdir,
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000680 huntrleaks, debug)
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000681 except KeyboardInterrupt:
682 # print a newline separate from the ^C
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000683 print()
Martin v. Löwis04824ce2006-03-10 21:26:16 +0000684 break
685 except:
686 raise
687
Barry Warsawe11e3de1999-01-28 19:51:51 +0000688 if single:
R. David Murrayef1992b2009-12-16 15:19:27 +0000689 if next_single_test:
690 with open(filename, 'w') as fp:
691 fp.write(next_single_test + '\n')
Barry Warsawe11e3de1999-01-28 19:51:51 +0000692 else:
693 os.unlink(filename)
694
Barry Warsaw3b6d0252004-02-07 22:43:03 +0000695 if trace:
696 r = tracer.results()
697 r.write_results(show_missing=True, summary=True, coverdir=coverdir)
698
Skip Montanaro0179a182004-06-06 15:53:18 +0000699 if runleaks:
700 os.system("leaks %d" % os.getpid())
701
Florent Xiclunad6995eb2010-03-30 19:43:09 +0000702 sys.exit(len(bad) > 0 or interrupted)
Barry Warsaw08fca522001-08-20 22:33:46 +0000703
Guido van Rossum152494a1996-12-20 03:12:20 +0000704
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000705STDTESTS = [
Guido van Rossum152494a1996-12-20 03:12:20 +0000706 'test_grammar',
707 'test_opcodes',
Guido van Rossumd8faa362007-04-27 19:54:29 +0000708 'test_dict',
Guido van Rossum152494a1996-12-20 03:12:20 +0000709 'test_builtin',
710 'test_exceptions',
711 'test_types',
Collin Winter7afaa882007-03-08 19:54:43 +0000712 'test_unittest',
713 'test_doctest',
714 'test_doctest2',
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000715]
Guido van Rossum152494a1996-12-20 03:12:20 +0000716
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000717NOTTESTS = {
Jeremy Hylton62e2c7e2001-02-28 17:48:06 +0000718 'test_future1',
719 'test_future2',
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000720}
Guido van Rossum152494a1996-12-20 03:12:20 +0000721
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000722def findtests(testdir=None, stdtests=STDTESTS, nottests=NOTTESTS):
Guido van Rossum152494a1996-12-20 03:12:20 +0000723 """Return a list of all applicable test modules."""
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000724 testdir = findtestdir(testdir)
Guido van Rossum152494a1996-12-20 03:12:20 +0000725 names = os.listdir(testdir)
726 tests = []
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000727 others = set(stdtests) | nottests
Guido van Rossum152494a1996-12-20 03:12:20 +0000728 for name in names:
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000729 modname, ext = os.path.splitext(name)
730 if modname[:5] == "test_" and ext == ".py" and modname not in others:
731 tests.append(modname)
732 return stdtests + sorted(tests)
Guido van Rossum152494a1996-12-20 03:12:20 +0000733
Victor Stinnerf58087b2010-05-02 17:24:51 +0000734def replace_stdout():
735 """Set stdout encoder error handler to backslashreplace (as stderr error
736 handler) to avoid UnicodeEncodeError when printing a traceback"""
Victor Stinnera3032802010-05-07 00:57:12 +0000737 if os.name == "nt":
738 # Replace sys.stdout breaks the stdout newlines on Windows: issue #8533
739 return
Victor Stinnerf58087b2010-05-02 17:24:51 +0000740 stdout = sys.stdout
741 sys.stdout = open(stdout.fileno(), 'w',
742 encoding=stdout.encoding,
743 errors="backslashreplace")
744
Antoine Pitrou88909542009-06-29 13:54:42 +0000745def runtest(test, verbose, quiet,
746 testdir=None, huntrleaks=False, debug=False, use_resources=None):
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000747 """Run a single test.
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000748
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000749 test -- the name of the test
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000750 verbose -- if true, print more messages
Trent Mickf29f47b2000-08-11 19:02:59 +0000751 quiet -- if true, don't print 'skipped' messages (probably redundant)
Christian Heimesb186d002008-03-18 15:15:01 +0000752 test_times -- a list of (time, test_name) pairs
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000753 testdir -- test directory
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000754 huntrleaks -- run multiple times to test for leaks; requires a debug
755 build; a triple corresponding to -R's three arguments
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000756
757 Returns one of the test result constants:
758 INTERRUPTED KeyboardInterrupt when run under -j
759 RESOURCE_DENIED test skipped because resource denied
760 SKIPPED test skipped for some other reason
761 ENV_CHANGED test failed because it changed the execution environment
762 FAILED test failed
763 PASSED test passed
Guido van Rossum6fd83b71998-08-01 17:04:08 +0000764 """
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000765
Antoine Pitrou88909542009-06-29 13:54:42 +0000766 support.verbose = verbose # Tell tests to be moderately quiet
767 if use_resources is not None:
768 support.use_resources = use_resources
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000769 try:
Antoine Pitrou88909542009-06-29 13:54:42 +0000770 return runtest_inner(test, verbose, quiet,
771 testdir, huntrleaks, debug)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000772 finally:
773 cleanup_test_droppings(test, verbose)
774
Nick Coghlan6ead5522009-10-18 13:19:33 +0000775# Unit tests are supposed to leave the execution environment unchanged
776# once they complete. But sometimes tests have bugs, especially when
777# tests fail, and the changes to environment go on to mess up other
778# tests. This can cause issues with buildbot stability, since tests
779# are run in random order and so problems may appear to come and go.
780# There are a few things we can save and restore to mitigate this, and
781# the following context manager handles this task.
782
783class saved_test_environment:
784 """Save bits of the test environment and restore them at block exit.
785
786 with saved_test_environment(testname, verbose, quiet):
787 #stuff
788
789 Unless quiet is True, a warning is printed to stderr if any of
790 the saved items was changed by the test. The attribute 'changed'
791 is initially False, but is set to True if a change is detected.
792
793 If verbose is more than 1, the before and after state of changed
794 items is also printed.
795 """
796
797 changed = False
798
799 def __init__(self, testname, verbose=0, quiet=False):
800 self.testname = testname
801 self.verbose = verbose
802 self.quiet = quiet
803
804 # To add things to save and restore, add a name XXX to the resources list
805 # and add corresponding get_XXX/restore_XXX functions. get_XXX should
806 # return the value to be saved and compared against a second call to the
807 # get function when test execution completes. restore_XXX should accept
808 # the saved value and restore the resource using it. It will be called if
809 # and only if a change in the value is detected.
810 #
811 # Note: XXX will have any '.' replaced with '_' characters when determining
812 # the corresponding method names.
813
814 resources = ('sys.argv', 'cwd', 'sys.stdin', 'sys.stdout', 'sys.stderr',
Brett Cannon29c0e4f2010-03-20 22:22:57 +0000815 'os.environ', 'sys.path', 'sys.path_hooks', '__import__',
Antoine Pitroub14ac8c2010-08-16 00:28:05 +0000816 'warnings.filters', 'asyncore.socket_map')
Nick Coghlan6ead5522009-10-18 13:19:33 +0000817
818 def get_sys_argv(self):
819 return id(sys.argv), sys.argv, sys.argv[:]
820 def restore_sys_argv(self, saved_argv):
821 sys.argv = saved_argv[1]
822 sys.argv[:] = saved_argv[2]
823
824 def get_cwd(self):
825 return os.getcwd()
826 def restore_cwd(self, saved_cwd):
827 os.chdir(saved_cwd)
828
829 def get_sys_stdout(self):
830 return sys.stdout
831 def restore_sys_stdout(self, saved_stdout):
832 sys.stdout = saved_stdout
833
834 def get_sys_stderr(self):
835 return sys.stderr
836 def restore_sys_stderr(self, saved_stderr):
837 sys.stderr = saved_stderr
838
839 def get_sys_stdin(self):
840 return sys.stdin
841 def restore_sys_stdin(self, saved_stdin):
842 sys.stdin = saved_stdin
843
844 def get_os_environ(self):
845 return id(os.environ), os.environ, dict(os.environ)
846 def restore_os_environ(self, saved_environ):
847 os.environ = saved_environ[1]
848 os.environ.clear()
849 os.environ.update(saved_environ[2])
850
851 def get_sys_path(self):
852 return id(sys.path), sys.path, sys.path[:]
853 def restore_sys_path(self, saved_path):
854 sys.path = saved_path[1]
855 sys.path[:] = saved_path[2]
856
Brett Cannon055470a2010-02-19 15:57:10 +0000857 def get_sys_path_hooks(self):
858 return id(sys.path_hooks), sys.path_hooks, sys.path_hooks[:]
859 def restore_sys_path_hooks(self, saved_hooks):
860 sys.path_hooks = saved_hooks[1]
861 sys.path_hooks[:] = saved_hooks[2]
862
863 def get___import__(self):
Brett Cannon45071902010-06-14 22:22:54 +0000864 return builtins.__import__
Brett Cannon055470a2010-02-19 15:57:10 +0000865 def restore___import__(self, import_):
Brett Cannon45071902010-06-14 22:22:54 +0000866 builtins.__import__ = import_
Brett Cannon055470a2010-02-19 15:57:10 +0000867
Brett Cannon29c0e4f2010-03-20 22:22:57 +0000868 def get_warnings_filters(self):
869 return id(warnings.filters), warnings.filters, warnings.filters[:]
870 def restore_warnings_filters(self, saved_filters):
871 warnings.filters = saved_filters[1]
872 warnings.filters[:] = saved_filters[2]
873
Antoine Pitroub14ac8c2010-08-16 00:28:05 +0000874 def get_asyncore_socket_map(self):
875 asyncore = sys.modules.get('asyncore')
876 return asyncore and asyncore.socket_map or {}
877 def restore_asyncore_socket_map(self, saved_map):
878 asyncore = sys.modules.get('asyncore')
879 if asyncore is not None:
880 asyncore.socket_map.clear()
881 asyncore.socket_map.update(saved_map)
882
Nick Coghlan6ead5522009-10-18 13:19:33 +0000883 def resource_info(self):
884 for name in self.resources:
885 method_suffix = name.replace('.', '_')
886 get_name = 'get_' + method_suffix
887 restore_name = 'restore_' + method_suffix
888 yield name, getattr(self, get_name), getattr(self, restore_name)
889
890 def __enter__(self):
891 self.saved_values = dict((name, get()) for name, get, restore
892 in self.resource_info())
893 return self
894
895 def __exit__(self, exc_type, exc_val, exc_tb):
896 for name, get, restore in self.resource_info():
897 current = get()
898 original = self.saved_values[name]
899 # Check for changes to the resource's value
900 if current != original:
901 self.changed = True
902 restore(original)
903 if not self.quiet:
904 print("Warning -- {} was modified by {}".format(
905 name, self.testname),
906 file=sys.stderr)
907 if self.verbose > 1:
908 print(" Before: {}\n After: {} ".format(
909 original, current),
910 file=sys.stderr)
911 return False
912
913
Antoine Pitrou88909542009-06-29 13:54:42 +0000914def runtest_inner(test, verbose, quiet,
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000915 testdir=None, huntrleaks=False, debug=False):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000916 support.unload(test)
Florent Xiclunada7bfd52010-03-06 11:43:55 +0000917 testdir = findtestdir(testdir)
Benjamin Petersonb48af542010-04-11 20:43:16 +0000918 if verbose:
919 capture_stdout = None
920 else:
921 capture_stdout = io.StringIO()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000922
Antoine Pitrou88909542009-06-29 13:54:42 +0000923 test_time = 0.0
Collin Wintera5503d52009-05-15 01:20:21 +0000924 refleak = False # True if the test leaked references.
Guido van Rossum152494a1996-12-20 03:12:20 +0000925 try:
R. David Murray0bc11ae2009-10-18 22:18:17 +0000926 if test.startswith('test.'):
927 abstest = test
928 else:
929 # Always import it from the test package
930 abstest = 'test.' + test
931 with saved_test_environment(test, verbose, quiet) as environment:
932 start_time = time.time()
933 the_package = __import__(abstest, globals(), locals(), [])
934 the_module = getattr(the_package, test)
935 # Old tests run to completion simply as a side-effect of
936 # being imported. For tests based on unittest or doctest,
937 # explicitly invoke their test_main() function (if it exists).
938 indirect_test = getattr(the_module, "test_main", None)
939 if indirect_test is not None:
940 indirect_test()
941 if huntrleaks:
942 refleak = dash_R(the_module, test, indirect_test,
943 huntrleaks)
944 test_time = time.time() - start_time
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000945 except support.ResourceDenied as msg:
Fred Drake9a0db072003-02-03 15:19:30 +0000946 if not quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000947 print(test, "skipped --", msg)
Fred Drake9a0db072003-02-03 15:19:30 +0000948 sys.stdout.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000949 return RESOURCE_DENIED, test_time
R. David Murraya21e4ca2009-03-31 23:16:50 +0000950 except unittest.SkipTest as msg:
Trent Mickf29f47b2000-08-11 19:02:59 +0000951 if not quiet:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000952 print(test, "skipped --", msg)
Guido van Rossum3cda93e2002-09-13 21:28:03 +0000953 sys.stdout.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000954 return SKIPPED, test_time
Fred Drakefe5c22a2000-08-18 16:04:05 +0000955 except KeyboardInterrupt:
956 raise
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000957 except support.TestFailed as msg:
R. David Murray11cabcf2010-09-29 01:08:05 +0000958 print("test", test, "failed --", msg, file=sys.stderr)
959 sys.stderr.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000960 return FAILED, test_time
Guido van Rossum9e48b271997-07-16 01:56:13 +0000961 except:
Guido van Rossum41360a41998-03-26 19:42:58 +0000962 type, value = sys.exc_info()[:2]
R. David Murray11cabcf2010-09-29 01:08:05 +0000963 print("test", test, "crashed --", str(type) + ":", value, file=sys.stderr)
964 sys.stderr.flush()
Neal Norwitz94fa2ee2008-03-31 02:55:15 +0000965 if verbose or debug:
R. David Murray11cabcf2010-09-29 01:08:05 +0000966 traceback.print_exc(file=sys.stderr)
967 sys.stderr.flush()
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000968 return FAILED, test_time
Guido van Rossum152494a1996-12-20 03:12:20 +0000969 else:
Collin Wintera5503d52009-05-15 01:20:21 +0000970 if refleak:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000971 return FAILED, test_time
Nick Coghlan6ead5522009-10-18 13:19:33 +0000972 if environment.changed:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000973 return ENV_CHANGED, test_time
974 return PASSED, test_time
Guido van Rossum0fcca4e2001-09-21 20:31:52 +0000975
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000976def cleanup_test_droppings(testname, verbose):
977 import shutil
Benjamin Peterson25c95f12009-05-08 20:42:26 +0000978 import stat
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000979
980 # Try to clean up junk commonly left behind. While tests shouldn't leave
981 # any files or directories behind, when a test fails that can be tedious
982 # for it to arrange. The consequences can be especially nasty on Windows,
983 # since if a test leaves a file open, it cannot be deleted by name (while
984 # there's nothing we can do about that here either, we can display the
985 # name of the offending test, which is a real help).
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000986 for name in (support.TESTFN,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000987 "db_home",
988 ):
989 if not os.path.exists(name):
990 continue
991
992 if os.path.isdir(name):
993 kind, nuker = "directory", shutil.rmtree
994 elif os.path.isfile(name):
995 kind, nuker = "file", os.unlink
996 else:
997 raise SystemError("os.path says %r exists but is neither "
998 "directory nor file" % name)
999
1000 if verbose:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001001 print("%r left behind %s %r" % (testname, kind, name))
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001002 try:
Benjamin Peterson25c95f12009-05-08 20:42:26 +00001003 # if we have chmod, fix possible permissions problems
1004 # that might prevent cleanup
1005 if (hasattr(os, 'chmod')):
1006 os.chmod(name, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001007 nuker(name)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001008 except Exception as msg:
1009 print(("%r left behind %s %r and it couldn't be "
1010 "removed: %s" % (testname, kind, name, msg)), file=sys.stderr)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001011
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001012def dash_R(the_module, test, indirect_test, huntrleaks):
Collin Wintera5503d52009-05-15 01:20:21 +00001013 """Run a test multiple times, looking for reference leaks.
1014
1015 Returns:
1016 False if the test didn't leak references; True if we detected refleaks.
1017 """
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001018 # This code is hackish and inelegant, but it seems to do the job.
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001019 import copyreg, _abcoll
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001020
1021 if not hasattr(sys, 'gettotalrefcount'):
1022 raise Exception("Tracking reference leaks requires a debug build "
1023 "of Python")
1024
1025 # Save current values for dash_R_cleanup() to restore.
1026 fs = warnings.filters[:]
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001027 ps = copyreg.dispatch_table.copy()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001028 pic = sys.path_importer_cache.copy()
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001029 try:
1030 import zipimport
1031 except ImportError:
1032 zdc = None # Run unmodified on platforms without zipimport support
1033 else:
1034 zdc = zipimport._zip_directory_cache.copy()
Christian Heimes93852662007-12-01 12:22:32 +00001035 abcs = {}
1036 for abc in [getattr(_abcoll, a) for a in _abcoll.__all__]:
Christian Heimesbe5b30b2008-03-03 19:18:51 +00001037 if not isabstract(abc):
Christian Heimes93852662007-12-01 12:22:32 +00001038 continue
1039 for obj in abc.__subclasses__() + [abc]:
1040 abcs[obj] = obj._abc_registry.copy()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001041
1042 if indirect_test:
1043 def run_the_test():
1044 indirect_test()
1045 else:
1046 def run_the_test():
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001047 del sys.modules[the_module.__name__]
1048 exec('import ' + the_module.__name__)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001049
1050 deltas = []
1051 nwarmup, ntracked, fname = huntrleaks
Ezio Melotti184bdfb2010-02-18 09:37:05 +00001052 fname = os.path.join(support.SAVEDCWD, fname)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001053 repcount = nwarmup + ntracked
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001054 print("beginning", repcount, "repetitions", file=sys.stderr)
1055 print(("1234567890"*(repcount//10 + 1))[:repcount], file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +00001056 sys.stderr.flush()
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001057 dash_R_cleanup(fs, ps, pic, zdc, abcs)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001058 for i in range(repcount):
Collin Winter58bee592010-03-17 02:08:57 +00001059 rc_before = sys.gettotalrefcount()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001060 run_the_test()
1061 sys.stderr.write('.')
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001062 sys.stderr.flush()
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001063 dash_R_cleanup(fs, ps, pic, zdc, abcs)
Collin Winter58bee592010-03-17 02:08:57 +00001064 rc_after = sys.gettotalrefcount()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001065 if i >= nwarmup:
Collin Winter58bee592010-03-17 02:08:57 +00001066 deltas.append(rc_after - rc_before)
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001067 print(file=sys.stderr)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001068 if any(deltas):
Guido van Rossum360e4b82007-05-14 22:51:27 +00001069 msg = '%s leaked %s references, sum=%s' % (test, deltas, sum(deltas))
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001070 print(msg, file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +00001071 sys.stderr.flush()
1072 with open(fname, "a") as refrep:
1073 print(msg, file=refrep)
1074 refrep.flush()
Collin Wintera5503d52009-05-15 01:20:21 +00001075 return True
1076 return False
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001077
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001078def dash_R_cleanup(fs, ps, pic, zdc, abcs):
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001079 import gc, copyreg
Brett Cannonf4fd9932008-05-10 21:11:46 +00001080 import _strptime, linecache
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001081 import urllib.parse, urllib.request, mimetypes, doctest
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001082 import struct, filecmp, _abcoll
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001083 from distutils.dir_util import _path_created
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001084 from weakref import WeakSet
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001085
Christian Heimesdae2a892008-04-19 00:55:37 +00001086 # Clear the warnings registry, so they can be displayed again
1087 for mod in sys.modules.values():
1088 if hasattr(mod, '__warningregistry__'):
1089 del mod.__warningregistry__
1090
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001091 # Restore some original values.
1092 warnings.filters[:] = fs
Alexandre Vassalottif7fa63d2008-05-11 08:55:36 +00001093 copyreg.dispatch_table.clear()
1094 copyreg.dispatch_table.update(ps)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001095 sys.path_importer_cache.clear()
1096 sys.path_importer_cache.update(pic)
Nick Coghlan260bd3e2009-11-16 06:49:25 +00001097 try:
1098 import zipimport
1099 except ImportError:
1100 pass # Run unmodified on platforms without zipimport support
1101 else:
1102 zipimport._zip_directory_cache.clear()
1103 zipimport._zip_directory_cache.update(zdc)
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001104
Christian Heimes26855632008-01-27 23:50:43 +00001105 # clear type cache
Christian Heimes15ebc882008-02-04 18:48:49 +00001106 sys._clear_type_cache()
Christian Heimes26855632008-01-27 23:50:43 +00001107
Guido van Rossum3de862d2007-08-18 00:10:33 +00001108 # Clear ABC registries, restoring previously saved ABC registries.
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001109 for abc in [getattr(_abcoll, a) for a in _abcoll.__all__]:
Christian Heimesbe5b30b2008-03-03 19:18:51 +00001110 if not isabstract(abc):
Christian Heimes941973a2007-11-30 21:53:03 +00001111 continue
Guido van Rossum7eaf8222007-06-18 17:58:50 +00001112 for obj in abc.__subclasses__() + [abc]:
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001113 obj._abc_registry = abcs.get(obj, WeakSet()).copy()
Guido van Rossumc1e315d2007-08-20 19:29:24 +00001114 obj._abc_cache.clear()
1115 obj._abc_negative_cache.clear()
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001116
Antoine Pitrou046467c2009-10-30 18:30:35 +00001117 # Flush standard output, so that buffered data is sent to the OS and
1118 # associated Python objects are reclaimed.
1119 for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__):
1120 if stream is not None:
1121 stream.flush()
1122
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001123 # Clear assorted module caches.
1124 _path_created.clear()
1125 re.purge()
1126 _strptime._regex_cache.clear()
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001127 urllib.parse.clear_cache()
1128 urllib.request.urlcleanup()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001129 linecache.clearcache()
1130 mimetypes._default_mime_types()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001131 filecmp._cache.clear()
Christian Heimesa34706f2008-01-04 03:06:10 +00001132 struct._clearcache()
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00001133 doctest.master = None
1134
1135 # Collect cyclic trash.
1136 gc.collect()
1137
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001138def warm_char_cache():
1139 s = bytes(range(256))
1140 for i in range(256):
1141 s[i:i+1]
1142
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001143def findtestdir(path=None):
1144 return path or os.path.dirname(__file__) or os.curdir
Guido van Rossum152494a1996-12-20 03:12:20 +00001145
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001146def removepy(names):
1147 if not names:
1148 return
1149 for idx, name in enumerate(names):
1150 basename, ext = os.path.splitext(name)
1151 if ext == '.py':
1152 names[idx] = basename
Tim Petersc5000df2002-06-02 21:42:01 +00001153
Guido van Rossum152494a1996-12-20 03:12:20 +00001154def count(n, word):
1155 if n == 1:
Guido van Rossum41360a41998-03-26 19:42:58 +00001156 return "%d %s" % (n, word)
Guido van Rossum152494a1996-12-20 03:12:20 +00001157 else:
Guido van Rossum41360a41998-03-26 19:42:58 +00001158 return "%d %ss" % (n, word)
Guido van Rossum152494a1996-12-20 03:12:20 +00001159
Tim Petersa45da922001-08-12 03:45:50 +00001160def printlist(x, width=70, indent=4):
Tim Peters7c7efe92002-08-23 17:55:54 +00001161 """Print the elements of iterable x to stdout.
Tim Petersa45da922001-08-12 03:45:50 +00001162
1163 Optional arg width (default 70) is the maximum line length.
1164 Optional arg indent (default 4) is the number of blanks with which to
1165 begin each line.
1166 """
1167
Tim Petersba78bc42002-07-04 19:45:06 +00001168 from textwrap import fill
1169 blanks = ' ' * indent
Florent Xiclunafd1b0932010-03-28 00:25:02 +00001170 # Print the sorted list: 'x' may be a '--random' list or a set()
1171 print(fill(' '.join(str(elt) for elt in sorted(x)), width,
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001172 initial_indent=blanks, subsequent_indent=blanks))
Tim Petersa45da922001-08-12 03:45:50 +00001173
Tim Petersde14a302002-04-01 05:04:46 +00001174# Map sys.platform to a string containing the basenames of tests
1175# expected to be skipped on that platform.
Tim Peters2a182db2002-10-09 01:07:11 +00001176#
1177# Special cases:
1178# test_pep277
1179# The _ExpectedSkips constructor adds this to the set of expected
1180# skips if not os.path.supports_unicode_filenames.
Neal Norwitz55b61d22003-02-28 19:57:03 +00001181# test_timeout
1182# Controlled by test_timeout.skip_expected. Requires the network
1183# resource and a socket module.
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001184#
1185# Tests that are expected to be skipped everywhere except on one platform
1186# are also handled separately.
Tim Petersde14a302002-04-01 05:04:46 +00001187
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001188_expectations = {
1189 'win32':
1190 """
Tim Petersc7c516a2003-09-20 22:06:13 +00001191 test__locale
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001192 test_crypt
Tim Petersd7030572001-10-22 22:06:08 +00001193 test_curses
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001194 test_dbm
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001195 test_fcntl
1196 test_fork1
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001197 test_epoll
Benjamin Peterson4d480532008-05-26 19:08:31 +00001198 test_dbm_gnu
Kristján Valur Jónsson42a40c52009-04-01 11:28:47 +00001199 test_dbm_ndbm
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001200 test_grp
Tim Petersfd8e6e52003-03-04 00:26:38 +00001201 test_ioctl
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001202 test_largefile
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001203 test_kqueue
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001204 test_openpty
Tim Petersefc4b122002-12-10 18:47:56 +00001205 test_ossaudiodev
Thomas Wouters47b49bf2007-08-30 22:15:33 +00001206 test_pipes
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001207 test_poll
Tim Peters003eb302003-02-17 21:48:48 +00001208 test_posix
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001209 test_pty
1210 test_pwd
Tim Peters1e33ffa2002-04-23 23:09:02 +00001211 test_resource
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001212 test_signal
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001213 test_syslog
Tim Peterscea2cc42004-08-04 02:32:03 +00001214 test_threadsignals
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001215 test_wait3
1216 test_wait4
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001217 """,
1218 'linux2':
1219 """
Guido van Rossumf66dacd2001-10-23 15:10:55 +00001220 test_curses
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001221 test_largefile
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001222 test_kqueue
Guido van Rossum4507ec72003-02-14 19:29:22 +00001223 test_ossaudiodev
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001224 """,
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001225 'unixware7':
Martin v. Löwis0ace3262001-09-05 14:38:48 +00001226 """
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001227 test_epoll
Martin v. Löwis0ace3262001-09-05 14:38:48 +00001228 test_largefile
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001229 test_kqueue
Martin v. Löwis0ace3262001-09-05 14:38:48 +00001230 test_minidom
Martin v. Löwis0ace3262001-09-05 14:38:48 +00001231 test_openpty
1232 test_pyexpat
1233 test_sax
Martin v. Löwis0ace3262001-09-05 14:38:48 +00001234 test_sundry
Martin v. Löwis0ace3262001-09-05 14:38:48 +00001235 """,
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001236 'openunix8':
1237 """
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001238 test_epoll
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001239 test_largefile
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001240 test_kqueue
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001241 test_minidom
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001242 test_openpty
1243 test_pyexpat
1244 test_sax
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001245 test_sundry
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001246 """,
1247 'sco_sv3':
1248 """
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001249 test_asynchat
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001250 test_fork1
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001251 test_epoll
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001252 test_gettext
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001253 test_largefile
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001254 test_locale
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001255 test_kqueue
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001256 test_minidom
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001257 test_openpty
1258 test_pyexpat
1259 test_queue
1260 test_sax
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001261 test_sundry
1262 test_thread
1263 test_threaded_import
1264 test_threadedtempfile
1265 test_threading
Martin v. Löwis21ee4092002-09-30 16:19:48 +00001266 """,
Jack Jansen8a97f4a2001-12-05 23:27:32 +00001267 'darwin':
Jack Jansen398c2362001-12-02 21:41:36 +00001268 """
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001269 test__locale
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001270 test_curses
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001271 test_epoll
Benjamin Peterson4d480532008-05-26 19:08:31 +00001272 test_dbm_gnu
Jack Jansen398c2362001-12-02 21:41:36 +00001273 test_largefile
Jack Jansenacda3392002-12-30 23:03:13 +00001274 test_locale
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001275 test_minidom
Jack Jansenacda3392002-12-30 23:03:13 +00001276 test_ossaudiodev
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001277 test_poll
Jack Jansen398c2362001-12-02 21:41:36 +00001278 """,
Guido van Rossum11c3f092002-07-17 15:08:24 +00001279 'sunos5':
1280 """
Guido van Rossum11c3f092002-07-17 15:08:24 +00001281 test_curses
1282 test_dbm
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001283 test_epoll
1284 test_kqueue
Benjamin Peterson4d480532008-05-26 19:08:31 +00001285 test_dbm_gnu
Guido van Rossum11c3f092002-07-17 15:08:24 +00001286 test_gzip
Guido van Rossum11c3f092002-07-17 15:08:24 +00001287 test_openpty
Guido van Rossum11c3f092002-07-17 15:08:24 +00001288 test_zipfile
1289 test_zlib
Jeremy Hyltoned375e12002-07-17 15:56:55 +00001290 """,
Skip Montanarob3230212002-03-15 02:54:03 +00001291 'hp-ux11':
1292 """
Skip Montanarob3230212002-03-15 02:54:03 +00001293 test_curses
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001294 test_epoll
Benjamin Peterson4d480532008-05-26 19:08:31 +00001295 test_dbm_gnu
Skip Montanarob3230212002-03-15 02:54:03 +00001296 test_gzip
Skip Montanarob3230212002-03-15 02:54:03 +00001297 test_largefile
Skip Montanarob3230212002-03-15 02:54:03 +00001298 test_locale
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001299 test_kqueue
Skip Montanarob3230212002-03-15 02:54:03 +00001300 test_minidom
Skip Montanarob3230212002-03-15 02:54:03 +00001301 test_openpty
1302 test_pyexpat
1303 test_sax
Skip Montanarob3230212002-03-15 02:54:03 +00001304 test_zipfile
1305 test_zlib
1306 """,
Jason Tishler25115942002-12-05 15:18:15 +00001307 'cygwin':
1308 """
Jason Tishler25115942002-12-05 15:18:15 +00001309 test_curses
1310 test_dbm
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001311 test_epoll
Jason Tishlerc23f39c2003-07-22 18:35:58 +00001312 test_ioctl
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001313 test_kqueue
Jason Tishler25115942002-12-05 15:18:15 +00001314 test_largefile
Jason Tishler25115942002-12-05 15:18:15 +00001315 test_locale
Jason Tishler5c4ded22003-02-05 16:46:01 +00001316 test_ossaudiodev
Jason Tishler25115942002-12-05 15:18:15 +00001317 test_socketserver
Jason Tishler25115942002-12-05 15:18:15 +00001318 """,
Andrew MacIntyrefd07e7d2002-12-31 11:26:50 +00001319 'os2emx':
1320 """
Andrew MacIntyrefd07e7d2002-12-31 11:26:50 +00001321 test_audioop
Andrew MacIntyrefd07e7d2002-12-31 11:26:50 +00001322 test_curses
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001323 test_epoll
1324 test_kqueue
Andrew MacIntyrefd07e7d2002-12-31 11:26:50 +00001325 test_largefile
Andrew MacIntyrefd07e7d2002-12-31 11:26:50 +00001326 test_mmap
Andrew MacIntyrefd07e7d2002-12-31 11:26:50 +00001327 test_openpty
1328 test_ossaudiodev
1329 test_pty
1330 test_resource
1331 test_signal
Andrew MacIntyrefd07e7d2002-12-31 11:26:50 +00001332 """,
Guido van Rossum944a6c32003-11-20 22:11:29 +00001333 'freebsd4':
1334 """
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001335 test_epoll
Benjamin Peterson4d480532008-05-26 19:08:31 +00001336 test_dbm_gnu
Guido van Rossum944a6c32003-11-20 22:11:29 +00001337 test_locale
Guido van Rossum944a6c32003-11-20 22:11:29 +00001338 test_ossaudiodev
1339 test_pep277
Hye-Shik Changf64700a2004-08-18 15:13:41 +00001340 test_pty
Guido van Rossum944a6c32003-11-20 22:11:29 +00001341 test_socketserver
Hye-Shik Changf64700a2004-08-18 15:13:41 +00001342 test_tcl
Guilherme Poloa91790a2009-02-09 20:40:42 +00001343 test_tk
Guilherme Polo9de29af2009-01-28 20:40:48 +00001344 test_ttk_guionly
1345 test_ttk_textonly
Guido van Rossum944a6c32003-11-20 22:11:29 +00001346 test_timeout
Guido van Rossum944a6c32003-11-20 22:11:29 +00001347 test_urllibnet
Benjamin Petersone5384b02008-10-04 22:00:42 +00001348 test_multiprocessing
Martin v. Löwis56f88112003-06-07 20:01:37 +00001349 """,
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +00001350 'aix5':
1351 """
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +00001352 test_bz2
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001353 test_epoll
Benjamin Peterson4d480532008-05-26 19:08:31 +00001354 test_dbm_gnu
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +00001355 test_gzip
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001356 test_kqueue
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +00001357 test_ossaudiodev
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +00001358 test_tcl
Guilherme Poloa91790a2009-02-09 20:40:42 +00001359 test_tk
Guilherme Polo9de29af2009-01-28 20:40:48 +00001360 test_ttk_guionly
1361 test_ttk_textonly
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +00001362 test_zipimport
1363 test_zlib
1364 """,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001365 'openbsd3':
1366 """
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001367 test_ctypes
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001368 test_epoll
Benjamin Peterson4d480532008-05-26 19:08:31 +00001369 test_dbm_gnu
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001370 test_locale
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001371 test_normalization
1372 test_ossaudiodev
1373 test_pep277
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001374 test_tcl
Guilherme Poloa91790a2009-02-09 20:40:42 +00001375 test_tk
Guilherme Polo9de29af2009-01-28 20:40:48 +00001376 test_ttk_guionly
1377 test_ttk_textonly
Benjamin Petersone5384b02008-10-04 22:00:42 +00001378 test_multiprocessing
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001379 """,
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001380 'netbsd3':
1381 """
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001382 test_ctypes
1383 test_curses
Christian Heimes4fbc72b2008-03-22 00:47:35 +00001384 test_epoll
Benjamin Peterson4d480532008-05-26 19:08:31 +00001385 test_dbm_gnu
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001386 test_locale
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001387 test_ossaudiodev
1388 test_pep277
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001389 test_tcl
Guilherme Poloa91790a2009-02-09 20:40:42 +00001390 test_tk
Guilherme Polo9de29af2009-01-28 20:40:48 +00001391 test_ttk_guionly
1392 test_ttk_textonly
Benjamin Petersone5384b02008-10-04 22:00:42 +00001393 test_multiprocessing
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001394 """,
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001395}
Martin v. Löwis32d0c1b2004-07-26 12:09:13 +00001396_expectations['freebsd5'] = _expectations['freebsd4']
Hye-Shik Changf64700a2004-08-18 15:13:41 +00001397_expectations['freebsd6'] = _expectations['freebsd4']
Hye-Shik Chang4e422812005-07-17 02:36:59 +00001398_expectations['freebsd7'] = _expectations['freebsd4']
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001399_expectations['freebsd8'] = _expectations['freebsd4']
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001400
Tim Petersb5b7b782001-08-12 01:20:39 +00001401class _ExpectedSkips:
1402 def __init__(self):
Tim Peters2a182db2002-10-09 01:07:11 +00001403 import os.path
Neal Norwitz55b61d22003-02-28 19:57:03 +00001404 from test import test_timeout
Tim Peters1b445d32002-11-24 18:53:11 +00001405
Tim Peters7c7efe92002-08-23 17:55:54 +00001406 self.valid = False
Tim Petersde14a302002-04-01 05:04:46 +00001407 if sys.platform in _expectations:
Guido van Rossumf73e30c2001-08-12 02:22:19 +00001408 s = _expectations[sys.platform]
Raymond Hettingera690a992003-11-16 16:17:49 +00001409 self.expected = set(s.split())
Tim Peters1b445d32002-11-24 18:53:11 +00001410
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001411 # These are broken tests, for now skipped on every platform.
1412 # XXX Fix these!
Benjamin Petersone9ea19e2008-08-19 23:02:38 +00001413 self.expected.add('test_nis')
Benjamin Peterson4fde0c42008-03-31 02:36:22 +00001414
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001415 # expected to be skipped on every platform, even Linux
Tim Peters2a182db2002-10-09 01:07:11 +00001416 if not os.path.supports_unicode_filenames:
1417 self.expected.add('test_pep277')
Tim Peters1b445d32002-11-24 18:53:11 +00001418
Neal Norwitz94fa2ee2008-03-31 02:55:15 +00001419 # doctest, profile and cProfile tests fail when the codec for the
1420 # fs encoding isn't built in because PyUnicode_Decode() adds two
1421 # calls into Python.
1422 encs = ("utf-8", "latin-1", "ascii", "mbcs", "utf-16", "utf-32")
1423 if sys.getfilesystemencoding().lower() not in encs:
1424 self.expected.add('test_profile')
1425 self.expected.add('test_cProfile')
1426 self.expected.add('test_doctest')
Guido van Rossumdaa251c2007-10-25 23:47:33 +00001427
Neal Norwitz55b61d22003-02-28 19:57:03 +00001428 if test_timeout.skip_expected:
1429 self.expected.add('test_timeout')
1430
Tim Petersecd79eb2003-01-29 00:35:32 +00001431 if sys.platform != "win32":
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001432 # test_sqlite is only reliable on Windows where the library
1433 # is distributed with Python
Neal Norwitz7035c982003-03-29 22:01:17 +00001434 WIN_ONLY = ["test_unicode_file", "test_winreg",
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001435 "test_winsound", "test_startfile",
1436 "test_sqlite"]
Neal Norwitz7035c982003-03-29 22:01:17 +00001437 for skip in WIN_ONLY:
1438 self.expected.add(skip)
Tim Petersf2715e02003-02-19 02:35:07 +00001439
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001440 if sys.platform != 'sunos5':
Guido van Rossumb5a755e2007-07-18 18:15:48 +00001441 self.expected.add('test_nis')
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001442
Tim Peters7c7efe92002-08-23 17:55:54 +00001443 self.valid = True
Tim Petersb5b7b782001-08-12 01:20:39 +00001444
1445 def isvalid(self):
1446 "Return true iff _ExpectedSkips knows about the current platform."
1447 return self.valid
1448
1449 def getexpected(self):
1450 """Return set of test names we expect to skip on current platform.
1451
1452 self.isvalid() must be true.
1453 """
1454
1455 assert self.isvalid()
1456 return self.expected
1457
Guido van Rossum152494a1996-12-20 03:12:20 +00001458if __name__ == '__main__':
Florent Xiclunadc69e722010-09-13 16:35:02 +00001459 # findtestdir() gets the dirname out of __file__, so we have to make it
1460 # absolute before changing the working directory.
1461 # For example __file__ may be relative when running trace or profile.
1462 # See issue #9323.
1463 __file__ = os.path.abspath(__file__)
1464
1465 # sanity check
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001466 assert __file__ == os.path.abspath(sys.argv[0])
Ezio Melotti184bdfb2010-02-18 09:37:05 +00001467
Florent Xiclunada7bfd52010-03-06 11:43:55 +00001468 # When tests are run from the Python build directory, it is best practice
1469 # to keep the test files in a subfolder. It eases the cleanup of leftover
1470 # files using command "make distclean".
1471 if sysconfig.is_python_build():
Florent Xiclunaec882212010-08-09 16:56:43 +00001472 TEMPDIR = os.path.join(sysconfig.get_config_var('srcdir'), 'build')
1473 TEMPDIR = os.path.abspath(TEMPDIR)
1474 if not os.path.exists(TEMPDIR):
1475 os.mkdir(TEMPDIR)
Ezio Melotti184bdfb2010-02-18 09:37:05 +00001476
1477 # Define a writable temp dir that will be used as cwd while running
1478 # the tests. The name of the dir includes the pid to allow parallel
1479 # testing (see the -j option).
1480 TESTCWD = 'test_python_{}'.format(os.getpid())
1481
Florent Xiclunaec882212010-08-09 16:56:43 +00001482 TESTCWD = os.path.join(TEMPDIR, TESTCWD)
Ezio Melotti184bdfb2010-02-18 09:37:05 +00001483
1484 # Run the tests in a context manager that temporary changes the CWD to a
1485 # temporary and writable directory. If it's not possible to create or
1486 # change the CWD, the original CWD will be used. The original CWD is
1487 # available from support.SAVEDCWD.
1488 with support.temp_cwd(TESTCWD, quiet=True):
1489 main()