Debian Codegraph @

Lib/test/libregrtest/cmdline.py

raw
1 import argparse
2 import os.path
3 import shlex
4 import sys
5 from test.support import os_helper, Py_DEBUG
6 from .utils import ALL_RESOURCES, RESOURCE_NAMES, TestFilter
7
8
9 USAGE = """\
10 python -m test [options] [test_name1 [test_name2 ...]]
11 python path/to/Lib/test/regrtest.py [options] [test_name1 [test_name2 ...]]
12 """
13
14 DESCRIPTION = """\
15 Run Python regression tests.
16
17 If no arguments or options are provided, finds all files matching
18 the pattern "test_*" in the Lib/test subdirectory and runs
19 them in alphabetical order (but see -M and -u, below, for exceptions).
20
21 For more rigorous testing, it is useful to use the following
22 command line:
23
24 python -E -Wd -m test [options] [test_name1 ...]
25 """
26
27 EPILOG = """\
28 Additional option details:
29
30 -r randomizes test execution order. You can use --randseed=int to provide an
31 int seed value for the randomizer. The randseed value will be used
32 to set seeds for all random usages in tests
33 (including randomizing the tests order if -r is set).
34 By default we always set random seed, but do not randomize test order.
35
36 -s On the first invocation of regrtest using -s, the first test file found
37 or the first test file given on the command line is run, and the name of
38 the next test is recorded in a file named pynexttest. If run from the
39 Python build directory, pynexttest is located in the 'build' subdirectory,
40 otherwise it is located in tempfile.gettempdir(). On subsequent runs,
41 the test in pynexttest is run, and the next test is written to pynexttest.
42 When the last test has been run, pynexttest is deleted. In this way it
43 is possible to single step through the test files. This is useful when
44 doing memory analysis on the Python interpreter, which process tends to
45 consume too many resources to run the full regression test non-stop.
46
47 -S is used to continue running tests after an aborted run. It will
48 maintain the order a standard run (ie, this assumes -r is not used).
49 This is useful after the tests have prematurely stopped for some external
50 reason and you want to start running from where you left off rather
51 than starting from the beginning.
52
53 -f reads the names of tests from the file given as f's argument, one
54 or more test names per line. Whitespace is ignored. Blank lines and
55 lines beginning with '#' are ignored. This is especially useful for
56 whittling down failures involving interactions among tests.
57
58 -L causes the leaks(1) command to be run just before exit if it exists.
59 leaks(1) is available on Mac OS X and presumably on some other
60 FreeBSD-derived systems.
61
62 -R runs each test several times and examines sys.gettotalrefcount() to
63 see if the test appears to be leaking references. The argument should
64 be of the form stab:run:fname where 'stab' is the number of times the
65 test is run to let gettotalrefcount settle down, 'run' is the number
66 of times further it is run and 'fname' is the name of the file the
67 reports are written to. These parameters all have defaults (5, 4 and
68 "reflog.txt" respectively), and the minimal invocation is '-R :'.
69
70 -M runs tests that require an exorbitant amount of memory. These tests
71 typically try to ascertain containers keep working when containing more than
72 2 billion objects, which only works on 64-bit systems. There are also some
73 tests that try to exhaust the address space of the process, which only makes
74 sense on 32-bit systems with at least 2Gb of memory. The passed-in memlimit,
75 which is a string in the form of '2.5Gb', determines how much memory the
76 tests will limit themselves to (but they may go slightly over.) The number
77 shouldn't be more memory than the machine has (including swap memory). You
78 should also keep in mind that swap memory is generally much, much slower
79 than RAM, and setting memlimit to all available RAM or higher will heavily
80 tax the machine. On the other hand, it is no use running these tests with a
81 limit of less than 2.5Gb, and many require more than 20Gb. Tests that expect
82 to use more than memlimit memory will be skipped. The big-memory tests
83 generally run very, very long.
84
85 -u is used to specify which special resource intensive tests to run,
86 such as those requiring large file support or network connectivity.
87 The argument is a comma-separated list of words indicating the
88 resources to test. Currently only the following are defined:
89
90 all - Enable all special resources.
91
92 none - Disable all special resources (this is the default).
93
94 audio - Tests that use the audio device. (There are known
95 cases of broken audio drivers that can crash Python or
96 even the Linux kernel.)
97
98 curses - Tests that use curses and will modify the terminal's
99 state and output modes.
100
101 largefile - It is okay to run some test that may create huge
102 files. These tests can take a long time and may
103 consume >2 GiB of disk space temporarily.
104
105 network - It is okay to run tests that use external network
106 resource, e.g. testing SSL support for sockets.
107
108 decimal - Test the decimal module against a large suite that
109 verifies compliance with standards.
110
111 cpu - Used for certain CPU-heavy tests.
112
113 walltime - Long running but not CPU-bound tests.
114
115 subprocess Run all tests for the subprocess module.
116
117 urlfetch - It is okay to download files required on testing.
118
119 gui - Run tests that require a running GUI.
120
121 tzdata - Run tests that require timezone data.
122
123 xpickle - Test pickle and _pickle against Python 3.6, 3.7, 3.8
124 and 3.9 to test backwards compatibility. These tests
125 may take very long to complete.
126
127 wantobjects - Allows to run Tkinter tests with the specified value of
128 tkinter.wantobjects.
129
130 To enable all resources except one, use '-uall,-<resource>'. For
131 example, to run all the tests except for the gui tests, give the
132 option '-uall,-gui'.
133
134 --matchfile filters tests using a text file, one pattern per line.
135 Pattern examples:
136
137 - test method: test_stat_attributes
138 - test class: FileTests
139 - test identifier: test_os.FileTests.test_stat_attributes
140 """
141
142
143 class Namespace(argparse.Namespace):
144 def __init__(self, **kwargs) -> None:
145 self.ci = False
146 self.testdir = None
147 self.verbose = 0
148 self.quiet = False
149 self.exclude = False
150 self.cleanup = False
151 self.wait = False
152 self.list_cases = False
153 self.list_tests = False
154 self.single = False
155 self.randomize = False
156 self.fromfile = None
157 self.fail_env_changed = False
158 self.use_resources: dict[str, str | None] = {}
159 self.trace = False
160 self.coverdir = 'coverage'
161 self.runleaks = False
162 self.huntrleaks: tuple[int, int, str] | None = None
163 self.rerun = False
164 self.verbose3 = False
165 self.print_slow = False
166 self.random_seed = None
167 self.use_mp = None
168 self.forever = False
169 self.header = False
170 self.failfast = False
171 self.match_tests: TestFilter = []
172 self.pgo = False
173 self.pgo_extended = False
174 self.tsan = False
175 self.worker_json = None
176 self.start = None
177 self.timeout = None
178 self.memlimit = None
179 self.threshold = None
180 self.fail_rerun = False
181 self.tempdir = None
182 self._add_python_opts = True
183 self.xmlpath = None
184 self.single_process = False
185
186 super().__init__(**kwargs)
187
188
189 class _ArgParser(argparse.ArgumentParser):
190
191 def error(self, message):
192 super().error(message + "\nPass -h or --help for complete help.")
193
194
195 class FilterAction(argparse.Action):
196 def __call__(self, parser, namespace, value, option_string=None):
197 items = getattr(namespace, self.dest)
198 items.append((value, self.const))
199
200
201 class FromFileFilterAction(argparse.Action):
202 def __call__(self, parser, namespace, value, option_string=None):
203 items = getattr(namespace, self.dest)
204 with open(value, encoding='utf-8') as fp:
205 for line in fp:
206 items.append((line.strip(), self.const))
207
208
209 def _create_parser():
210 # Set prog to prevent the uninformative "__main__.py" from displaying in
211 # error messages when using "python -m test ...".
212 parser = _ArgParser(prog='regrtest.py',
213 usage=USAGE,
214 description=DESCRIPTION,
215 epilog=EPILOG,
216 add_help=False,
217 formatter_class=argparse.RawDescriptionHelpFormatter)
218 parser.set_defaults(match_tests=[])
219
220 # Arguments with this clause added to its help are described further in
221 # the epilog's "Additional option details" section.
222 more_details = ' See the section at bottom for more details.'
223
224 group = parser.add_argument_group('General options')
225 # We add help explicitly to control what argument group it renders under.
226 group.add_argument('-h', '--help', action='help',
227 help='show this help message and exit')
228 group.add_argument('--fast-ci', action='store_true',
229 help='Fast Continuous Integration (CI) mode used by '
230 'GitHub Actions')
231 group.add_argument('--slow-ci', action='store_true',
232 help='Slow Continuous Integration (CI) mode used by '
233 'buildbot workers')
234 group.add_argument('--timeout', metavar='TIMEOUT',
235 help='dump the traceback and exit if a test takes '
236 'more than TIMEOUT seconds; disabled if TIMEOUT '
237 'is negative or equals to zero')
238 group.add_argument('--wait', action='store_true',
239 help='wait for user input, e.g., allow a debugger '
240 'to be attached')
241 group.add_argument('-S', '--start', metavar='START',
242 help='the name of the test at which to start.' +
243 more_details)
244 group.add_argument('-p', '--python', metavar='PYTHON',
245 help='Command to run Python test subprocesses with.')
246 group.add_argument('--randseed', metavar='SEED',
247 dest='random_seed', type=int,
248 help='pass a global random seed')
249
250 group = parser.add_argument_group('Verbosity')
251 group.add_argument('-v', '--verbose', action='count',
252 help='run tests in verbose mode with output to stdout')
253 group.add_argument('-w', '--rerun', action='store_true',
254 help='re-run failed tests in verbose mode')
255 group.add_argument('--verbose2', action='store_true', dest='rerun',
256 help='deprecated alias to --rerun')
257 group.add_argument('-W', '--verbose3', action='store_true',
258 help='display test output on failure')
259 group.add_argument('-q', '--quiet', action='store_true',
260 help='no output unless one or more tests fail')
261 group.add_argument('-o', '--slowest', action='store_true', dest='print_slow',
262 help='print the slowest 10 tests')
263 group.add_argument('--header', action='store_true',
264 help='print header with interpreter info')
265
266 group = parser.add_argument_group('Selecting tests')
267 group.add_argument('-r', '--randomize', action='store_true',
268 help='randomize test execution order.' + more_details)
269 group.add_argument('--no-randomize', dest='no_randomize', action='store_true',
270 help='do not randomize test execution order, even if '
271 'it would be implied by another option')
272 group.add_argument('-f', '--fromfile', metavar='FILE',
273 help='read names of tests to run from a file.' +
274 more_details)
275 group.add_argument('-x', '--exclude', action='store_true',
276 help='arguments are tests to *exclude*')
277 group.add_argument('-s', '--single', action='store_true',
278 help='single step through a set of tests.' +
279 more_details)
280 group.add_argument('-m', '--match', metavar='PAT',
281 dest='match_tests', action=FilterAction, const=True,
282 help='match test cases and methods with glob pattern PAT')
283 group.add_argument('-i', '--ignore', metavar='PAT',
284 dest='match_tests', action=FilterAction, const=False,
285 help='ignore test cases and methods with glob pattern PAT')
286 group.add_argument('--matchfile', metavar='FILENAME',
287 dest='match_tests',
288 action=FromFileFilterAction, const=True,
289 help='similar to --match but get patterns from a '
290 'text file, one pattern per line')
291 group.add_argument('--ignorefile', metavar='FILENAME',
292 dest='match_tests',
293 action=FromFileFilterAction, const=False,
294 help='similar to --matchfile but it receives patterns '
295 'from text file to ignore')
296 group.add_argument('-G', '--failfast', action='store_true',
297 help='fail as soon as a test fails (only with -v or -W)')
298 group.add_argument('-u', '--use', metavar='RES1,RES2,...',
299 action='extend', type=resources_list,
300 help='specify which special resource intensive tests '
301 'to run.' + more_details)
302 group.add_argument('-M', '--memlimit', metavar='LIMIT',
303 help='run very large memory-consuming tests.' +
304 more_details)
305 group.add_argument('--testdir', metavar='DIR',
306 type=relative_filename,
307 help='execute test files in the specified directory '
308 '(instead of the Python stdlib test suite)')
309
310 group = parser.add_argument_group('Special runs')
311 group.add_argument('-L', '--runleaks', action='store_true',
312 help='run the leaks(1) command just before exit.' +
313 more_details)
314 group.add_argument('-R', '--huntrleaks', metavar='RUNCOUNTS',
315 type=huntrleaks,
316 help='search for reference leaks (needs debug build, '
317 'very slow).' + more_details)
318 group.add_argument('-j', '--multiprocess', metavar='PROCESSES',
319 dest='use_mp', type=int,
320 help='run PROCESSES processes at once')
321 group.add_argument('--single-process', action='store_true',
322 dest='single_process',
323 help='always run all tests sequentially in '
324 'a single process, ignore -jN option, '
325 'and failed tests are also rerun sequentially '
326 'in the same process')
327 group.add_argument('-T', '--coverage', action='store_true',
328 dest='trace',
329 help='turn on code coverage tracing using the trace '
330 'module')
331 group.add_argument('-D', '--coverdir', metavar='DIR',
332 type=relative_filename,
333 help='directory where coverage files are put')
334 group.add_argument('-N', '--nocoverdir',
335 action='store_const', const=None, dest='coverdir',
336 help='put coverage files alongside modules')
337 group.add_argument('-t', '--threshold', metavar='THRESHOLD',
338 type=int,
339 help='call gc.set_threshold(THRESHOLD)')
340 group.add_argument('-n', '--nowindows', action='store_true',
341 help='suppress error message boxes on Windows')
342 group.add_argument('-F', '--forever', action='store_true',
343 help='run the specified tests in a loop, until an '
344 'error happens; imply --failfast')
345 group.add_argument('--list-tests', action='store_true',
346 help="only write the name of tests that will be run, "
347 "don't execute them")
348 group.add_argument('--list-cases', action='store_true',
349 help='only write the name of test cases that will be run'
350 ' , don\'t execute them')
351 group.add_argument('-P', '--pgo', dest='pgo', action='store_true',
352 help='enable Profile Guided Optimization (PGO) training')
353 group.add_argument('--pgo-extended', action='store_true',
354 help='enable extended PGO training (slower training)')
355 group.add_argument('--tsan', dest='tsan', action='store_true',
356 help='run a subset of test cases that are proper for the TSAN test')
357 group.add_argument('--fail-env-changed', action='store_true',
358 help='if a test file alters the environment, mark '
359 'the test as failed')
360 group.add_argument('--fail-rerun', action='store_true',
361 help='if a test failed and then passed when re-run, '
362 'mark the tests as failed')
363
364 group.add_argument('--junit-xml', dest='xmlpath', metavar='FILENAME',
365 help='writes JUnit-style XML results to the specified '
366 'file')
367 group.add_argument('--tempdir', metavar='PATH',
368 help='override the working directory for the test run')
369 group.add_argument('--cleanup', action='store_true',
370 help='remove old test_python_* directories')
371 group.add_argument('--bisect', action='store_true',
372 help='if some tests fail, run test.bisect_cmd on them')
373 group.add_argument('--dont-add-python-opts', dest='_add_python_opts',
374 action='store_false',
375 help="internal option, don't use it")
376 return parser
377
378
379 def relative_filename(string):
380 # CWD is replaced with a temporary dir before calling main(), so we
381 # join it with the saved CWD so it ends up where the user expects.
382 return os.path.join(os_helper.SAVEDCWD, string)
383
384
385 def huntrleaks(string):
386 args = string.split(':')
387 if len(args) not in (2, 3):
388 raise argparse.ArgumentTypeError(
389 'needs 2 or 3 colon-separated arguments')
390 nwarmup = int(args[0]) if args[0] else 5
391 ntracked = int(args[1]) if args[1] else 4
392 fname = args[2] if len(args) > 2 and args[2] else 'reflog.txt'
393 return nwarmup, ntracked, fname
394
395
396 def resources_list(string):
397 u = []
398 for x in string.split(','):
399 r, eq, v = x.partition('=')
400 r = r.lower()
401 u.append((r, v if eq else None))
402 if r == 'all' or r == 'none':
403 if eq:
404 raise argparse.ArgumentTypeError('invalid resource: ' + x)
405 continue
406 if r[0] == '-':
407 if eq:
408 raise argparse.ArgumentTypeError('invalid resource: ' + x)
409 r = r[1:]
410 if r not in RESOURCE_NAMES:
411 raise argparse.ArgumentTypeError('invalid resource: ' + r)
412 return u
413
414
415 def _parse_args(args, **kwargs):
416 # Defaults
417 ns = Namespace()
418 for k, v in kwargs.items():
419 if not hasattr(ns, k):
420 raise TypeError('%r is an invalid keyword argument '
421 'for this function' % k)
422 setattr(ns, k, v)
423
424 parser = _create_parser()
425 # Issue #14191: argparse doesn't support "intermixed" positional and
426 # optional arguments. Use parse_known_args() as workaround.
427 ns.args = parser.parse_known_args(args=args, namespace=ns)[1]
428 for arg in ns.args:
429 if arg.startswith('-'):
430 parser.error("unrecognized arguments: %s" % arg)
431
432 if ns.timeout is not None:
433 # Support "--timeout=" (no value) so Makefile.pre.pre TESTTIMEOUT
434 # can be used by "make buildbottest" and "make test".
435 if ns.timeout != "":
436 try:
437 ns.timeout = float(ns.timeout)
438 except ValueError:
439 parser.error(f"invalid timeout value: {ns.timeout!r}")
440 else:
441 ns.timeout = None
442
443 # Continuous Integration (CI): common options for fast/slow CI modes
444 if ns.slow_ci or ns.fast_ci:
445 # Similar to options:
446 # -j0 --randomize --fail-env-changed --rerun --slowest --verbose3
447 if ns.use_mp is None:
448 ns.use_mp = 0
449 ns.randomize = True
450 ns.fail_env_changed = True
451 if ns.python is None:
452 ns.rerun = True
453 ns.print_slow = True
454 if not ns.verbose:
455 ns.verbose3 = True
456 else:
457 # --verbose has the priority over --verbose3
458 pass
459 else:
460 ns._add_python_opts = False
461
462 # --singleprocess overrides -jN option
463 if ns.single_process:
464 ns.use_mp = None
465
466 # When both --slow-ci and --fast-ci options are present,
467 # --slow-ci has the priority
468 if ns.slow_ci:
469 # Similar to: -u "all" --timeout=1200
470 if ns.use is None:
471 ns.use = []
472 ns.use[:0] = [('all', None)]
473 if ns.timeout is None:
474 ns.timeout = 1200 # 20 minutes
475 elif ns.fast_ci:
476 # Similar to: -u "all,-cpu" --timeout=600
477 if ns.use is None:
478 ns.use = []
479 ns.use[:0] = [('all', None), ('-cpu', None)]
480 if ns.timeout is None:
481 ns.timeout = 600 # 10 minutes
482
483 if ns.single and ns.fromfile:
484 parser.error("-s and -f don't go together!")
485 if ns.trace:
486 if ns.use_mp is not None:
487 if not Py_DEBUG:
488 parser.error("need --with-pydebug to use -T and -j together")
489 else:
490 print(
491 "Warning: collecting coverage without -j is imprecise. Configure"
492 " --with-pydebug and run -m test -T -j for best results.",
493 file=sys.stderr
494 )
495 if ns.python is not None:
496 if ns.use_mp is None:
497 parser.error("-p requires -j!")
498 # The "executable" may be two or more parts, e.g. "node python.js"
499 ns.python = shlex.split(ns.python)
500 if ns.failfast and not (ns.verbose or ns.verbose3):
501 parser.error("-G/--failfast needs either -v or -W")
502 if ns.pgo and (ns.verbose or ns.rerun or ns.verbose3):
503 parser.error("--pgo/-v don't go together!")
504 if ns.pgo_extended:
505 ns.pgo = True # pgo_extended implies pgo
506
507 if ns.nowindows:
508 print("Warning: the --nowindows (-n) option is deprecated. "
509 "Use -vv to display assertions in stderr.", file=sys.stderr)
510
511 if ns.quiet:
512 ns.verbose = 0
513 if ns.timeout is not None:
514 if ns.timeout <= 0:
515 ns.timeout = None
516 if ns.use:
517 for r, v in ns.use:
518 if r == 'all':
519 for r in ALL_RESOURCES:
520 ns.use_resources[r] = None
521 elif r == 'none':
522 ns.use_resources.clear()
523 elif r[0] == '-':
524 r = r[1:]
525 ns.use_resources.pop(r, None)
526 else:
527 ns.use_resources[r] = v
528 if ns.random_seed is not None:
529 ns.randomize = True
530 if ns.no_randomize:
531 ns.randomize = False
532 if ns.verbose:
533 ns.header = True
534
535 # When -jN option is used, a worker process does not use --verbose3
536 # and so -R 3:3 -jN --verbose3 just works as expected: there is no false
537 # alarm about memory leak.
538 if ns.huntrleaks and ns.verbose3 and ns.use_mp is None:
539 # run_single_test() replaces sys.stdout with io.StringIO if verbose3
540 # is true. In this case, huntrleaks sees an write into StringIO as
541 # a memory leak, whereas it is not (gh-71290).
542 ns.verbose3 = False
543 print("WARNING: Disable --verbose3 because it's incompatible with "
544 "--huntrleaks without -jN option",
545 file=sys.stderr)
546
547 if ns.forever:
548 # --forever implies --failfast
549 ns.failfast = True
550
551 if ns.huntrleaks:
552 warmup, repetitions, _ = ns.huntrleaks
553 if warmup < 1 or repetitions < 1:
554 msg = ("Invalid values for the --huntrleaks/-R parameters. The "
555 "number of warmups and repetitions must be at least 1 "
556 "each (1:1).")
557 print(msg, file=sys.stderr, flush=True)
558 sys.exit(2)
559
560 return ns