blob: a4bac79c8af680a19469fb6c8759822fc3a6968b [file] [log] [blame]
Victor Stinner98de5342015-09-26 09:43:45 +02001import argparse
Victor Stinner98de5342015-09-26 09:43:45 +02002import os
Steve Dower08ec6d92015-10-08 11:34:07 -07003import sys
Victor Stinner98de5342015-09-26 09:43:45 +02004from test import support
Hai Shi3ddc6342020-06-30 21:46:06 +08005from test.support import os_helper
Victor Stinner98de5342015-09-26 09:43:45 +02006
Victor Stinner3844fe52015-09-26 10:38:01 +02007
Victor Stinner98de5342015-09-26 09:43:45 +02008USAGE = """\
9python -m test [options] [test_name1 [test_name2 ...]]
10python path/to/Lib/test/regrtest.py [options] [test_name1 [test_name2 ...]]
11"""
12
13DESCRIPTION = """\
14Run Python regression tests.
15
16If no arguments or options are provided, finds all files matching
17the pattern "test_*" in the Lib/test subdirectory and runs
18them in alphabetical order (but see -M and -u, below, for exceptions).
19
20For more rigorous testing, it is useful to use the following
21command line:
22
23python -E -Wd -m test [options] [test_name1 ...]
24"""
25
26EPILOG = """\
27Additional option details:
28
Serhiy Storchaka4a7c03a2015-11-02 14:44:29 +020029-r randomizes test execution order. You can use --randseed=int to provide an
Victor Stinner98de5342015-09-26 09:43:45 +020030int seed value for the randomizer; this is useful for reproducing troublesome
31test orders.
32
33-s On the first invocation of regrtest using -s, the first test file found
34or the first test file given on the command line is run, and the name of
35the next test is recorded in a file named pynexttest. If run from the
36Python build directory, pynexttest is located in the 'build' subdirectory,
37otherwise it is located in tempfile.gettempdir(). On subsequent runs,
38the test in pynexttest is run, and the next test is written to pynexttest.
39When the last test has been run, pynexttest is deleted. In this way it
40is possible to single step through the test files. This is useful when
41doing memory analysis on the Python interpreter, which process tends to
42consume too many resources to run the full regression test non-stop.
43
44-S is used to continue running tests after an aborted run. It will
45maintain the order a standard run (ie, this assumes -r is not used).
46This is useful after the tests have prematurely stopped for some external
47reason and you want to start running from where you left off rather
48than starting from the beginning.
49
50-f reads the names of tests from the file given as f's argument, one
51or more test names per line. Whitespace is ignored. Blank lines and
52lines beginning with '#' are ignored. This is especially useful for
53whittling down failures involving interactions among tests.
54
55-L causes the leaks(1) command to be run just before exit if it exists.
56leaks(1) is available on Mac OS X and presumably on some other
57FreeBSD-derived systems.
58
59-R runs each test several times and examines sys.gettotalrefcount() to
60see if the test appears to be leaking references. The argument should
61be of the form stab:run:fname where 'stab' is the number of times the
62test is run to let gettotalrefcount settle down, 'run' is the number
63of times further it is run and 'fname' is the name of the file the
64reports are written to. These parameters all have defaults (5, 4 and
65"reflog.txt" respectively), and the minimal invocation is '-R :'.
66
67-M runs tests that require an exorbitant amount of memory. These tests
68typically try to ascertain containers keep working when containing more than
692 billion objects, which only works on 64-bit systems. There are also some
70tests that try to exhaust the address space of the process, which only makes
71sense on 32-bit systems with at least 2Gb of memory. The passed-in memlimit,
sth7108aab2018-12-31 06:41:39 +010072which is a string in the form of '2.5Gb', determines how much memory the
Victor Stinner98de5342015-09-26 09:43:45 +020073tests will limit themselves to (but they may go slightly over.) The number
74shouldn't be more memory than the machine has (including swap memory). You
75should also keep in mind that swap memory is generally much, much slower
76than RAM, and setting memlimit to all available RAM or higher will heavily
77tax the machine. On the other hand, it is no use running these tests with a
78limit of less than 2.5Gb, and many require more than 20Gb. Tests that expect
79to use more than memlimit memory will be skipped. The big-memory tests
80generally run very, very long.
81
82-u is used to specify which special resource intensive tests to run,
83such as those requiring large file support or network connectivity.
84The argument is a comma-separated list of words indicating the
85resources to test. Currently only the following are defined:
86
87 all - Enable all special resources.
88
89 none - Disable all special resources (this is the default).
90
91 audio - Tests that use the audio device. (There are known
92 cases of broken audio drivers that can crash Python or
93 even the Linux kernel.)
94
95 curses - Tests that use curses and will modify the terminal's
96 state and output modes.
97
98 largefile - It is okay to run some test that may create huge
99 files. These tests can take a long time and may
Victor Stinner8c663fd2017-11-08 14:44:44 -0800100 consume >2 GiB of disk space temporarily.
Victor Stinner98de5342015-09-26 09:43:45 +0200101
102 network - It is okay to run tests that use external network
103 resource, e.g. testing SSL support for sockets.
104
105 decimal - Test the decimal module against a large suite that
106 verifies compliance with standards.
107
108 cpu - Used for certain CPU-heavy tests.
109
110 subprocess Run all tests for the subprocess module.
111
112 urlfetch - It is okay to download files required on testing.
113
114 gui - Run tests that require a running GUI.
115
Alexander Belopolsky5d0c5982016-07-22 18:47:04 -0400116 tzdata - Run tests that require timezone data.
117
Victor Stinner98de5342015-09-26 09:43:45 +0200118To enable all resources except one, use '-uall,-<resource>'. For
119example, to run all the tests except for the gui tests, give the
120option '-uall,-gui'.
Victor Stinneref8320c2017-06-09 10:18:48 +0200121
122--matchfile filters tests using a text file, one pattern per line.
123Pattern examples:
124
125- test method: test_stat_attributes
126- test class: FileTests
127- test identifier: test_os.FileTests.test_stat_attributes
Victor Stinner98de5342015-09-26 09:43:45 +0200128"""
129
130
Victor Stinner5b392bb2017-07-20 15:46:32 +0200131ALL_RESOURCES = ('audio', 'curses', 'largefile', 'network',
132 'decimal', 'cpu', 'subprocess', 'urlfetch', 'gui')
133
134# Other resources excluded from --use=all:
135#
136# - extralagefile (ex: test_zipfile64): really too slow to be enabled
137# "by default"
138# - tzdata: while needed to validate fully test_datetime, it makes
139# test_datetime too slow (15-20 min on some buildbots) and so is disabled by
140# default (see bpo-30822).
141RESOURCE_NAMES = ALL_RESOURCES + ('extralargefile', 'tzdata')
Victor Stinner98de5342015-09-26 09:43:45 +0200142
143class _ArgParser(argparse.ArgumentParser):
144
145 def error(self, message):
146 super().error(message + "\nPass -h or --help for complete help.")
147
148
149def _create_parser():
150 # Set prog to prevent the uninformative "__main__.py" from displaying in
151 # error messages when using "python -m test ...".
152 parser = _ArgParser(prog='regrtest.py',
153 usage=USAGE,
154 description=DESCRIPTION,
155 epilog=EPILOG,
156 add_help=False,
157 formatter_class=argparse.RawDescriptionHelpFormatter)
158
159 # Arguments with this clause added to its help are described further in
160 # the epilog's "Additional option details" section.
161 more_details = ' See the section at bottom for more details.'
162
163 group = parser.add_argument_group('General options')
164 # We add help explicitly to control what argument group it renders under.
165 group.add_argument('-h', '--help', action='help',
166 help='show this help message and exit')
167 group.add_argument('--timeout', metavar='TIMEOUT', type=float,
168 help='dump the traceback and exit if a test takes '
169 'more than TIMEOUT seconds; disabled if TIMEOUT '
170 'is negative or equals to zero')
171 group.add_argument('--wait', action='store_true',
172 help='wait for user input, e.g., allow a debugger '
173 'to be attached')
Victor Stinner012f5b92018-09-07 17:20:42 +0200174 group.add_argument('--worker-args', metavar='ARGS')
Victor Stinner98de5342015-09-26 09:43:45 +0200175 group.add_argument('-S', '--start', metavar='START',
176 help='the name of the test at which to start.' +
177 more_details)
178
179 group = parser.add_argument_group('Verbosity')
180 group.add_argument('-v', '--verbose', action='count',
181 help='run tests in verbose mode with output to stdout')
182 group.add_argument('-w', '--verbose2', action='store_true',
183 help='re-run failed tests in verbose mode')
184 group.add_argument('-W', '--verbose3', action='store_true',
185 help='display test output on failure')
186 group.add_argument('-q', '--quiet', action='store_true',
187 help='no output unless one or more tests fail')
Victor Stinner6c446192016-08-17 11:25:43 +0200188 group.add_argument('-o', '--slowest', action='store_true', dest='print_slow',
Victor Stinner98de5342015-09-26 09:43:45 +0200189 help='print the slowest 10 tests')
190 group.add_argument('--header', action='store_true',
191 help='print header with interpreter info')
192
193 group = parser.add_argument_group('Selecting tests')
194 group.add_argument('-r', '--randomize', action='store_true',
195 help='randomize test execution order.' + more_details)
196 group.add_argument('--randseed', metavar='SEED',
197 dest='random_seed', type=int,
198 help='pass a random seed to reproduce a previous '
199 'random run')
200 group.add_argument('-f', '--fromfile', metavar='FILE',
201 help='read names of tests to run from a file.' +
202 more_details)
203 group.add_argument('-x', '--exclude', action='store_true',
204 help='arguments are tests to *exclude*')
205 group.add_argument('-s', '--single', action='store_true',
206 help='single step through a set of tests.' +
207 more_details)
208 group.add_argument('-m', '--match', metavar='PAT',
Victor Stinneref8320c2017-06-09 10:18:48 +0200209 dest='match_tests', action='append',
Victor Stinner98de5342015-09-26 09:43:45 +0200210 help='match test cases and methods with glob pattern PAT')
Pablo Galindoe0cd8aa2019-11-19 23:46:49 +0000211 group.add_argument('-i', '--ignore', metavar='PAT',
212 dest='ignore_tests', action='append',
213 help='ignore test cases and methods with glob pattern PAT')
Victor Stinneref8320c2017-06-09 10:18:48 +0200214 group.add_argument('--matchfile', metavar='FILENAME',
215 dest='match_filename',
216 help='similar to --match but get patterns from a '
217 'text file, one pattern per line')
Pablo Galindoe0cd8aa2019-11-19 23:46:49 +0000218 group.add_argument('--ignorefile', metavar='FILENAME',
219 dest='ignore_filename',
220 help='similar to --matchfile but it receives patterns '
221 'from text file to ignore')
Victor Stinner98de5342015-09-26 09:43:45 +0200222 group.add_argument('-G', '--failfast', action='store_true',
223 help='fail as soon as a test fails (only with -v or -W)')
224 group.add_argument('-u', '--use', metavar='RES1,RES2,...',
225 action='append', type=resources_list,
226 help='specify which special resource intensive tests '
227 'to run.' + more_details)
228 group.add_argument('-M', '--memlimit', metavar='LIMIT',
229 help='run very large memory-consuming tests.' +
230 more_details)
231 group.add_argument('--testdir', metavar='DIR',
232 type=relative_filename,
233 help='execute test files in the specified directory '
234 '(instead of the Python stdlib test suite)')
235
236 group = parser.add_argument_group('Special runs')
Victor Stinner75120d22019-04-26 09:28:53 +0200237 group.add_argument('-l', '--findleaks', action='store_const', const=2,
238 default=1,
239 help='deprecated alias to --fail-env-changed')
Victor Stinner98de5342015-09-26 09:43:45 +0200240 group.add_argument('-L', '--runleaks', action='store_true',
241 help='run the leaks(1) command just before exit.' +
242 more_details)
243 group.add_argument('-R', '--huntrleaks', metavar='RUNCOUNTS',
244 type=huntrleaks,
245 help='search for reference leaks (needs debug build, '
246 'very slow).' + more_details)
247 group.add_argument('-j', '--multiprocess', metavar='PROCESSES',
248 dest='use_mp', type=int,
249 help='run PROCESSES processes at once')
250 group.add_argument('-T', '--coverage', action='store_true',
251 dest='trace',
252 help='turn on code coverage tracing using the trace '
253 'module')
254 group.add_argument('-D', '--coverdir', metavar='DIR',
255 type=relative_filename,
256 help='directory where coverage files are put')
257 group.add_argument('-N', '--nocoverdir',
258 action='store_const', const=None, dest='coverdir',
259 help='put coverage files alongside modules')
260 group.add_argument('-t', '--threshold', metavar='THRESHOLD',
261 type=int,
262 help='call gc.set_threshold(THRESHOLD)')
263 group.add_argument('-n', '--nowindows', action='store_true',
264 help='suppress error message boxes on Windows')
265 group.add_argument('-F', '--forever', action='store_true',
266 help='run the specified tests in a loop, until an '
Victor Stinnerb0917df2019-05-13 19:17:54 +0200267 'error happens; imply --failfast')
Victor Stinner5f9d3ac2015-10-03 00:21:12 +0200268 group.add_argument('--list-tests', action='store_true',
269 help="only write the name of tests that will be run, "
270 "don't execute them")
mlouielua49c9352017-06-16 17:36:19 +0800271 group.add_argument('--list-cases', action='store_true',
272 help='only write the name of test cases that will be run'
273 ' , don\'t execute them')
Brett Cannon11faa212015-10-02 16:20:49 -0700274 group.add_argument('-P', '--pgo', dest='pgo', action='store_true',
Neil Schemenauer4e16a4a2019-07-22 12:54:25 -0700275 help='enable Profile Guided Optimization (PGO) training')
276 group.add_argument('--pgo-extended', action='store_true',
277 help='enable extended PGO training (slower training)')
Victor Stinner63f54c62017-06-26 18:33:19 +0200278 group.add_argument('--fail-env-changed', action='store_true',
279 help='if a test file alters the environment, mark '
280 'the test as failed')
Victor Stinner98de5342015-09-26 09:43:45 +0200281
Steve Dowerd0f49d22018-09-18 09:10:26 -0700282 group.add_argument('--junit-xml', dest='xmlpath', metavar='FILENAME',
283 help='writes JUnit-style XML results to the specified '
284 'file')
Victor Stinner47fbc4e2019-06-24 12:03:00 +0200285 group.add_argument('--tempdir', metavar='PATH',
Steve Dower38df97a2018-11-17 04:14:36 -0800286 help='override the working directory for the test run')
Victor Stinner47fbc4e2019-06-24 12:03:00 +0200287 group.add_argument('--cleanup', action='store_true',
288 help='remove old test_python_* directories')
Victor Stinner98de5342015-09-26 09:43:45 +0200289 return parser
290
291
292def relative_filename(string):
293 # CWD is replaced with a temporary dir before calling main(), so we
294 # join it with the saved CWD so it ends up where the user expects.
Hai Shi3ddc6342020-06-30 21:46:06 +0800295 return os.path.join(os_helper.SAVEDCWD, string)
Victor Stinner98de5342015-09-26 09:43:45 +0200296
297
298def huntrleaks(string):
299 args = string.split(':')
300 if len(args) not in (2, 3):
301 raise argparse.ArgumentTypeError(
302 'needs 2 or 3 colon-separated arguments')
303 nwarmup = int(args[0]) if args[0] else 5
304 ntracked = int(args[1]) if args[1] else 4
305 fname = args[2] if len(args) > 2 and args[2] else 'reflog.txt'
306 return nwarmup, ntracked, fname
307
308
309def resources_list(string):
310 u = [x.lower() for x in string.split(',')]
311 for r in u:
312 if r == 'all' or r == 'none':
313 continue
314 if r[0] == '-':
315 r = r[1:]
316 if r not in RESOURCE_NAMES:
317 raise argparse.ArgumentTypeError('invalid resource: ' + r)
318 return u
319
320
321def _parse_args(args, **kwargs):
322 # Defaults
323 ns = argparse.Namespace(testdir=None, verbose=0, quiet=False,
324 exclude=False, single=False, randomize=False, fromfile=None,
Victor Stinner75120d22019-04-26 09:28:53 +0200325 findleaks=1, use_resources=None, trace=False, coverdir='coverage',
Victor Stinner98de5342015-09-26 09:43:45 +0200326 runleaks=False, huntrleaks=False, verbose2=False, print_slow=False,
327 random_seed=None, use_mp=None, verbose3=False, forever=False,
Pablo Galindoe0cd8aa2019-11-19 23:46:49 +0000328 header=False, failfast=False, match_tests=None, ignore_tests=None,
329 pgo=False)
Victor Stinner98de5342015-09-26 09:43:45 +0200330 for k, v in kwargs.items():
331 if not hasattr(ns, k):
332 raise TypeError('%r is an invalid keyword argument '
333 'for this function' % k)
334 setattr(ns, k, v)
335 if ns.use_resources is None:
336 ns.use_resources = []
337
338 parser = _create_parser()
Victor Stinnera506a932016-10-17 18:13:46 +0200339 # Issue #14191: argparse doesn't support "intermixed" positional and
340 # optional arguments. Use parse_known_args() as workaround.
341 ns.args = parser.parse_known_args(args=args, namespace=ns)[1]
342 for arg in ns.args:
343 if arg.startswith('-'):
344 parser.error("unrecognized arguments: %s" % arg)
345 sys.exit(1)
Victor Stinner98de5342015-09-26 09:43:45 +0200346
Victor Stinner75120d22019-04-26 09:28:53 +0200347 if ns.findleaks > 1:
348 # --findleaks implies --fail-env-changed
349 ns.fail_env_changed = True
Victor Stinner98de5342015-09-26 09:43:45 +0200350 if ns.single and ns.fromfile:
351 parser.error("-s and -f don't go together!")
Xiang Zhang772bf2e2016-12-19 22:00:22 +0800352 if ns.use_mp is not None and ns.trace:
Victor Stinner98de5342015-09-26 09:43:45 +0200353 parser.error("-T and -j don't go together!")
Victor Stinner98de5342015-09-26 09:43:45 +0200354 if ns.failfast and not (ns.verbose or ns.verbose3):
355 parser.error("-G/--failfast needs either -v or -W")
Brett Cannon11faa212015-10-02 16:20:49 -0700356 if ns.pgo and (ns.verbose or ns.verbose2 or ns.verbose3):
357 parser.error("--pgo/-v don't go together!")
Neil Schemenauer4e16a4a2019-07-22 12:54:25 -0700358 if ns.pgo_extended:
359 ns.pgo = True # pgo_extended implies pgo
Victor Stinner98de5342015-09-26 09:43:45 +0200360
Steve Dower12c29452015-10-08 09:05:36 -0700361 if ns.nowindows:
362 print("Warning: the --nowindows (-n) option is deprecated. "
363 "Use -vv to display assertions in stderr.", file=sys.stderr)
364
Victor Stinner98de5342015-09-26 09:43:45 +0200365 if ns.quiet:
366 ns.verbose = 0
367 if ns.timeout is not None:
Victor Stinner5f9d3ac2015-10-03 00:21:12 +0200368 if ns.timeout <= 0:
Victor Stinner98de5342015-09-26 09:43:45 +0200369 ns.timeout = None
370 if ns.use_mp is not None:
371 if ns.use_mp <= 0:
372 # Use all cores + extras for tests that like to sleep
373 ns.use_mp = 2 + (os.cpu_count() or 1)
Victor Stinner98de5342015-09-26 09:43:45 +0200374 if ns.use:
375 for a in ns.use:
376 for r in a:
377 if r == 'all':
Victor Stinner5b392bb2017-07-20 15:46:32 +0200378 ns.use_resources[:] = ALL_RESOURCES
Victor Stinner98de5342015-09-26 09:43:45 +0200379 continue
380 if r == 'none':
381 del ns.use_resources[:]
382 continue
383 remove = False
384 if r[0] == '-':
385 remove = True
386 r = r[1:]
387 if remove:
388 if r in ns.use_resources:
389 ns.use_resources.remove(r)
390 elif r not in ns.use_resources:
391 ns.use_resources.append(r)
392 if ns.random_seed is not None:
393 ns.randomize = True
Victor Stinner3d005682017-05-04 15:21:12 +0200394 if ns.verbose:
395 ns.header = True
Victor Stinnerfcdd9b62017-05-18 13:03:24 -0700396 if ns.huntrleaks and ns.verbose3:
397 ns.verbose3 = False
398 print("WARNING: Disable --verbose3 because it's incompatible with "
399 "--huntrleaks: see http://bugs.python.org/issue27103",
400 file=sys.stderr)
Victor Stinneref8320c2017-06-09 10:18:48 +0200401 if ns.match_filename:
402 if ns.match_tests is None:
403 ns.match_tests = []
Steve Dower38df97a2018-11-17 04:14:36 -0800404 with open(ns.match_filename) as fp:
Victor Stinneref8320c2017-06-09 10:18:48 +0200405 for line in fp:
406 ns.match_tests.append(line.strip())
Pablo Galindoe0cd8aa2019-11-19 23:46:49 +0000407 if ns.ignore_filename:
408 if ns.ignore_tests is None:
409 ns.ignore_tests = []
410 with open(ns.ignore_filename) as fp:
411 for line in fp:
412 ns.ignore_tests.append(line.strip())
Victor Stinnerb0917df2019-05-13 19:17:54 +0200413 if ns.forever:
414 # --forever implies --failfast
415 ns.failfast = True
Victor Stinner98de5342015-09-26 09:43:45 +0200416
417 return ns