Debian Codegraph @

lib-python/3/test/libregrtest/cmdline.py

raw symbols SCIP
1 import argparse
2 import os.path
3 import shlex
4 import sys
5 from test.support import os_helper
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 To enable all resources except one, use '-uall,-<resource>'. For
124 example, to run all the tests except for the gui tests, give the
125 option '-uall,-gui'.
126
127 --matchfile filters tests using a text file, one pattern per line.
128 Pattern examples:
129
130 - test method: test_stat_attributes
131 - test class: FileTests
132 - test identifier: test_os.FileTests.test_stat_attributes
133 """
134
135
136 class Namespace(argparse.Namespace):
137 def __init__(self, **kwargs) -> None:
138 self.ci = False
139 self.testdir = None
140 self.verbose = 0
141 self.quiet = False
142 self.exclude = False
143 self.cleanup = False
144 self.wait = False
145 self.list_cases = False
146 self.list_tests = False
147 self.single = False
148 self.randomize = False
149 self.fromfile = None
150 self.fail_env_changed = False
151 self.use_resources = None
152 self.trace = False
153 self.coverdir = 'coverage'
154 self.runleaks = False
155 self.huntrleaks: tuple[int, int, str] | None = None
156 self.rerun = False
157 self.verbose3 = False
158 self.print_slow = False
159 self.random_seed = None
160 self.use_mp = None
161 self.forever = False
162 self.header = False
163 self.failfast = False
164 self.match_tests: TestFilter = []
165 self.pgo = False
166 self.pgo_extended = False
167 self.worker_json = None
168 self.start = None
169 self.timeout = None
170 self.memlimit = None
171 self.threshold = None
172 self.fail_rerun = False
173 self.tempdir = None
174 self._add_python_opts = True
175 self.xmlpath = None
176
177 super().__init__(**kwargs)
178
179
180 class _ArgParser(argparse.ArgumentParser):
181
182 def error(self, message):
183 super().error(message + "\nPass -h or --help for complete help.")
184
185
186 class FilterAction(argparse.Action):
187 def __call__(self, parser, namespace, value, option_string=None):
188 items = getattr(namespace, self.dest)
189 items.append((value, self.const))
190
191
192 class FromFileFilterAction(argparse.Action):
193 def __call__(self, parser, namespace, value, option_string=None):
194 items = getattr(namespace, self.dest)
195 with open(value, encoding='utf-8') as fp:
196 for line in fp:
197 items.append((line.strip(), self.const))
198
199
200 def _create_parser():
201 # Set prog to prevent the uninformative "__main__.py" from displaying in
202 # error messages when using "python -m test ...".
203 parser = _ArgParser(prog='regrtest.py',
204 usage=USAGE,
205 description=DESCRIPTION,
206 epilog=EPILOG,
207 add_help=False,
208 formatter_class=argparse.RawDescriptionHelpFormatter)
209 parser.set_defaults(match_tests=[])
210
211 # Arguments with this clause added to its help are described further in
212 # the epilog's "Additional option details" section.
213 more_details = ' See the section at bottom for more details.'
214
215 group = parser.add_argument_group('General options')
216 # We add help explicitly to control what argument group it renders under.
217 group.add_argument('-h', '--help', action='help',
218 help='show this help message and exit')
219 group.add_argument('--fast-ci', action='store_true',
220 help='Fast Continuous Integration (CI) mode used by '
221 'GitHub Actions')
222 group.add_argument('--slow-ci', action='store_true',
223 help='Slow Continuous Integration (CI) mode used by '
224 'buildbot workers')
225 group.add_argument('--timeout', metavar='TIMEOUT',
226 help='dump the traceback and exit if a test takes '
227 'more than TIMEOUT seconds; disabled if TIMEOUT '
228 'is negative or equals to zero')
229 group.add_argument('--wait', action='store_true',
230 help='wait for user input, e.g., allow a debugger '
231 'to be attached')
232 group.add_argument('-S', '--start', metavar='START',
233 help='the name of the test at which to start.' +
234 more_details)
235 group.add_argument('-p', '--python', metavar='PYTHON',
236 help='Command to run Python test subprocesses with.')
237 group.add_argument('--randseed', metavar='SEED',
238 dest='random_seed', type=int,
239 help='pass a global random seed')
240
241 group = parser.add_argument_group('Verbosity')
242 group.add_argument('-v', '--verbose', action='count',
243 help='run tests in verbose mode with output to stdout')
244 group.add_argument('-w', '--rerun', action='store_true',
245 help='re-run failed tests in verbose mode')
246 group.add_argument('--verbose2', action='store_true', dest='rerun',
247 help='deprecated alias to --rerun')
248 group.add_argument('-W', '--verbose3', action='store_true',
249 help='display test output on failure')
250 group.add_argument('-q', '--quiet', action='store_true',
251 help='no output unless one or more tests fail')
252 group.add_argument('-o', '--slowest', action='store_true', dest='print_slow',
253 help='print the slowest 10 tests')
254 group.add_argument('--header', action='store_true',
255 help='print header with interpreter info')
256
257 group = parser.add_argument_group('Selecting tests')
258 group.add_argument('-r', '--randomize', action='store_true',
259 help='randomize test execution order.' + more_details)
260 group.add_argument('-f', '--fromfile', metavar='FILE',
261 help='read names of tests to run from a file.' +
262 more_details)
263 group.add_argument('-x', '--exclude', action='store_true',
264 help='arguments are tests to *exclude*')
265 group.add_argument('-s', '--single', action='store_true',
266 help='single step through a set of tests.' +
267 more_details)
268 group.add_argument('-m', '--match', metavar='PAT',
269 dest='match_tests', action=FilterAction, const=True,
270 help='match test cases and methods with glob pattern PAT')
271 group.add_argument('-i', '--ignore', metavar='PAT',
272 dest='match_tests', action=FilterAction, const=False,
273 help='ignore test cases and methods with glob pattern PAT')
274 group.add_argument('--matchfile', metavar='FILENAME',
275 dest='match_tests',
276 action=FromFileFilterAction, const=True,
277 help='similar to --match but get patterns from a '
278 'text file, one pattern per line')
279 group.add_argument('--ignorefile', metavar='FILENAME',
280 dest='match_tests',
281 action=FromFileFilterAction, const=False,
282 help='similar to --matchfile but it receives patterns '
283 'from text file to ignore')
284 group.add_argument('-G', '--failfast', action='store_true',
285 help='fail as soon as a test fails (only with -v or -W)')
286 group.add_argument('-u', '--use', metavar='RES1,RES2,...',
287 action='append', type=resources_list,
288 help='specify which special resource intensive tests '
289 'to run.' + more_details)
290 group.add_argument('-M', '--memlimit', metavar='LIMIT',
291 help='run very large memory-consuming tests.' +
292 more_details)
293 group.add_argument('--testdir', metavar='DIR',
294 type=relative_filename,
295 help='execute test files in the specified directory '
296 '(instead of the Python stdlib test suite)')
297
298 group = parser.add_argument_group('Special runs')
299 group.add_argument('-L', '--runleaks', action='store_true',
300 help='run the leaks(1) command just before exit.' +
301 more_details)
302 group.add_argument('-R', '--huntrleaks', metavar='RUNCOUNTS',
303 type=huntrleaks,
304 help='search for reference leaks (needs debug build, '
305 'very slow).' + more_details)
306 group.add_argument('-j', '--multiprocess', metavar='PROCESSES',
307 dest='use_mp', type=int,
308 help='run PROCESSES processes at once')
309 group.add_argument('-T', '--coverage', action='store_true',
310 dest='trace',
311 help='turn on code coverage tracing using the trace '
312 'module')
313 group.add_argument('-D', '--coverdir', metavar='DIR',
314 type=relative_filename,
315 help='directory where coverage files are put')
316 group.add_argument('-N', '--nocoverdir',
317 action='store_const', const=None, dest='coverdir',
318 help='put coverage files alongside modules')
319 group.add_argument('-t', '--threshold', metavar='THRESHOLD',
320 type=int,
321 help='call gc.set_threshold(THRESHOLD)')
322 group.add_argument('-n', '--nowindows', action='store_true',
323 help='suppress error message boxes on Windows')
324 group.add_argument('-F', '--forever', action='store_true',
325 help='run the specified tests in a loop, until an '
326 'error happens; imply --failfast')
327 group.add_argument('--list-tests', action='store_true',
328 help="only write the name of tests that will be run, "
329 "don't execute them")
330 group.add_argument('--list-cases', action='store_true',
331 help='only write the name of test cases that will be run'
332 ' , don\'t execute them')
333 group.add_argument('-P', '--pgo', dest='pgo', action='store_true',
334 help='enable Profile Guided Optimization (PGO) training')
335 group.add_argument('--pgo-extended', action='store_true',
336 help='enable extended PGO training (slower training)')
337 group.add_argument('--fail-env-changed', action='store_true',
338 help='if a test file alters the environment, mark '
339 'the test as failed')
340 group.add_argument('--fail-rerun', action='store_true',
341 help='if a test failed and then passed when re-run, '
342 'mark the tests as failed')
343
344 group.add_argument('--junit-xml', dest='xmlpath', metavar='FILENAME',
345 help='writes JUnit-style XML results to the specified '
346 'file')
347 group.add_argument('--tempdir', metavar='PATH',
348 help='override the working directory for the test run')
349 group.add_argument('--cleanup', action='store_true',
350 help='remove old test_python_* directories')
351 group.add_argument('--bisect', action='store_true',
352 help='if some tests fail, run test.bisect_cmd on them')
353 group.add_argument('--dont-add-python-opts', dest='_add_python_opts',
354 action='store_false',
355 help="internal option, don't use it")
356 return parser
357
358
359 def relative_filename(string):
360 # CWD is replaced with a temporary dir before calling main(), so we
361 # join it with the saved CWD so it ends up where the user expects.
362 return os.path.join(os_helper.SAVEDCWD, string)
363
364
365 def huntrleaks(string):
366 args = string.split(':')
367 if len(args) not in (2, 3):
368 raise argparse.ArgumentTypeError(
369 'needs 2 or 3 colon-separated arguments')
370 nwarmup = int(args[0]) if args[0] else 5
371 ntracked = int(args[1]) if args[1] else 4
372 fname = args[2] if len(args) > 2 and args[2] else 'reflog.txt'
373 return nwarmup, ntracked, fname
374
375
376 def resources_list(string):
377 u = [x.lower() for x in string.split(',')]
378 for r in u:
379 if r == 'all' or r == 'none':
380 continue
381 if r[0] == '-':
382 r = r[1:]
383 if r not in RESOURCE_NAMES:
384 raise argparse.ArgumentTypeError('invalid resource: ' + r)
385 return u
386
387
388 def _parse_args(args, **kwargs):
389 # Defaults
390 ns = Namespace()
391 for k, v in kwargs.items():
392 if not hasattr(ns, k):
393 raise TypeError('%r is an invalid keyword argument '
394 'for this function' % k)
395 setattr(ns, k, v)
396 if ns.use_resources is None:
397 ns.use_resources = []
398
399 parser = _create_parser()
400 # Issue #14191: argparse doesn't support "intermixed" positional and
401 # optional arguments. Use parse_known_args() as workaround.
402 ns.args = parser.parse_known_args(args=args, namespace=ns)[1]
403 for arg in ns.args:
404 if arg.startswith('-'):
405 parser.error("unrecognized arguments: %s" % arg)
406
407 if ns.timeout is not None:
408 # Support "--timeout=" (no value) so Makefile.pre.pre TESTTIMEOUT
409 # can be used by "make buildbottest" and "make test".
410 if ns.timeout != "":
411 try:
412 ns.timeout = float(ns.timeout)
413 except ValueError:
414 parser.error(f"invalid timeout value: {ns.timeout!r}")
415 else:
416 ns.timeout = None
417
418 # Continuous Integration (CI): common options for fast/slow CI modes
419 if ns.slow_ci or ns.fast_ci:
420 # Similar to options:
421 #
422 # -j0 --randomize --fail-env-changed --fail-rerun --rerun
423 # --slowest --verbose3
424 if ns.use_mp is None:
425 ns.use_mp = 0
426 ns.randomize = True
427 ns.fail_env_changed = True
428 ns.fail_rerun = True
429 if ns.python is None:
430 ns.rerun = True
431 ns.print_slow = True
432 ns.verbose3 = True
433 else:
434 ns._add_python_opts = False
435
436 # When both --slow-ci and --fast-ci options are present,
437 # --slow-ci has the priority
438 if ns.slow_ci:
439 # Similar to: -u "all" --timeout=1200
440 if ns.use is None:
441 ns.use = []
442 ns.use.insert(0, ['all'])
443 if ns.timeout is None:
444 ns.timeout = 1200 # 20 minutes
445 elif ns.fast_ci:
446 # Similar to: -u "all,-cpu" --timeout=600
447 if ns.use is None:
448 ns.use = []
449 ns.use.insert(0, ['all', '-cpu'])
450 if ns.timeout is None:
451 ns.timeout = 600 # 10 minutes
452
453 if ns.single and ns.fromfile:
454 parser.error("-s and -f don't go together!")
455 if ns.use_mp is not None and ns.trace:
456 parser.error("-T and -j don't go together!")
457 if ns.python is not None:
458 if ns.use_mp is None:
459 parser.error("-p requires -j!")
460 # The "executable" may be two or more parts, e.g. "node python.js"
461 ns.python = shlex.split(ns.python)
462 if ns.failfast and not (ns.verbose or ns.verbose3):
463 parser.error("-G/--failfast needs either -v or -W")
464 if ns.pgo and (ns.verbose or ns.rerun or ns.verbose3):
465 parser.error("--pgo/-v don't go together!")
466 if ns.pgo_extended:
467 ns.pgo = True # pgo_extended implies pgo
468
469 if ns.nowindows:
470 print("Warning: the --nowindows (-n) option is deprecated. "
471 "Use -vv to display assertions in stderr.", file=sys.stderr)
472
473 if ns.quiet:
474 ns.verbose = 0
475 if ns.timeout is not None:
476 if ns.timeout <= 0:
477 ns.timeout = None
478 if ns.use:
479 for a in ns.use:
480 for r in a:
481 if r == 'all':
482 ns.use_resources[:] = ALL_RESOURCES
483 continue
484 if r == 'none':
485 del ns.use_resources[:]
486 continue
487 remove = False
488 if r[0] == '-':
489 remove = True
490 r = r[1:]
491 if remove:
492 if r in ns.use_resources:
493 ns.use_resources.remove(r)
494 elif r not in ns.use_resources:
495 ns.use_resources.append(r)
496 if ns.random_seed is not None:
497 ns.randomize = True
498 if ns.verbose:
499 ns.header = True
500
501 # When -jN option is used, a worker process does not use --verbose3
502 # and so -R 3:3 -jN --verbose3 just works as expected: there is no false
503 # alarm about memory leak.
504 if ns.huntrleaks and ns.verbose3 and ns.use_mp is None:
505 # run_single_test() replaces sys.stdout with io.StringIO if verbose3
506 # is true. In this case, huntrleaks sees an write into StringIO as
507 # a memory leak, whereas it is not (gh-71290).
508 ns.verbose3 = False
509 print("WARNING: Disable --verbose3 because it's incompatible with "
510 "--huntrleaks without -jN option",
511 file=sys.stderr)
512
513 if ns.huntrleaks and ns.xmlpath:
514 # The XML data is written into a file outside runtest_refleak(), so
515 # it looks like a leak but it's not. Simply disable XML output when
516 # hunting for reference leaks (gh-83434).
517 ns.xmlpath = None
518 print("WARNING: Disable --junit-xml because it's incompatible "
519 "with --huntrleaks",
520 file=sys.stderr)
521
522 if ns.forever:
523 # --forever implies --failfast
524 ns.failfast = True
525
526 if ns.huntrleaks:
527 warmup, repetitions, _ = ns.huntrleaks
528 if warmup < 1 or repetitions < 1:
529 msg = ("Invalid values for the --huntrleaks/-R parameters. The "
530 "number of warmups and repetitions must be at least 1 "
531 "each (1:1).")
532 print(msg, file=sys.stderr, flush=True)
533 sys.exit(2)
534
535 return ns