Debian Codegraph @

Lib/test/libregrtest/main.py

raw
1 import os
2 import random
3 import re
4 import shlex
5 import sys
6 import sysconfig
7 import time
8 import trace
9 from _colorize import get_colors # type: ignore[import-not-found]
10 from typing import NoReturn
11
12 from test.support import os_helper, MS_WINDOWS, flush_std_streams
13
14 from .cmdline import _parse_args, Namespace
15 from .findtests import findtests, split_test_packages, list_cases
16 from .logger import Logger
17 from .pgo import setup_pgo_tests
18 from .result import TestResult
19 from .results import TestResults, EXITCODE_INTERRUPTED
20 from .runtests import RunTests, HuntRefleak
21 from .setup import setup_process, setup_test_dir
22 from .single import run_single_test, PROGRESS_MIN_TIME
23 from .tsan import setup_tsan_tests, setup_tsan_parallel_tests
24 from .utils import (
25 StrPath, StrJSON, TestName, TestList, TestTuple, TestFilter,
26 strip_py_suffix, count, format_duration,
27 printlist, get_temp_dir, get_work_dir, exit_timeout,
28 display_header, cleanup_temp_dir, print_warning,
29 is_cross_compiled, get_host_runner,
30 EXIT_TIMEOUT)
31
32
33 class Regrtest:
34 """Execute a test suite.
35
36 This also parses command-line options and modifies its behavior
37 accordingly.
38
39 tests -- a list of strings containing test names (optional)
40 testdir -- the directory in which to look for tests (optional)
41
42 Users other than the Python test suite will certainly want to
43 specify testdir; if it's omitted, the directory containing the
44 Python test suite is searched for.
45
46 If the tests argument is omitted, the tests listed on the
47 command-line will be used. If that's empty, too, then all *.py
48 files beginning with test_ will be used.
49
50 The other default arguments (verbose, quiet, exclude,
51 single, randomize, use_resources, trace, coverdir,
52 print_slow, and random_seed) allow programmers calling main()
53 directly to set the values that would normally be set by flags
54 on the command line.
55 """
56 def __init__(self, ns: Namespace, _add_python_opts: bool = False):
57 # Log verbosity
58 self.verbose: int = int(ns.verbose)
59 self.quiet: bool = ns.quiet
60 self.pgo: bool = ns.pgo
61 self.pgo_extended: bool = ns.pgo_extended
62 self.tsan: bool = ns.tsan
63 self.tsan_parallel: bool = ns.tsan_parallel
64
65 # Test results
66 self.results: TestResults = TestResults()
67 self.first_state: str | None = None
68
69 # Logger
70 self.logger = Logger(self.results, self.quiet, self.pgo)
71
72 # Actions
73 self.want_header: bool = ns.header
74 self.want_list_tests: bool = ns.list_tests
75 self.want_list_cases: bool = ns.list_cases
76 self.want_wait: bool = ns.wait
77 self.want_cleanup: bool = ns.cleanup
78 self.want_rerun: bool = ns.rerun
79 self.want_run_leaks: bool = ns.runleaks
80 self.want_bisect: bool = ns.bisect
81
82 self.ci_mode: bool = (ns.fast_ci or ns.slow_ci)
83 self.want_add_python_opts: bool = (_add_python_opts
84 and ns._add_python_opts)
85
86 # Select tests
87 self.match_tests: TestFilter = ns.match_tests
88 self.exclude: bool = ns.exclude
89 self.fromfile: StrPath | None = ns.fromfile
90 self.starting_test: TestName | None = ns.start
91 self.cmdline_args: TestList = ns.args
92
93 # Workers
94 self.single_process: bool = ns.single_process
95 if self.single_process or ns.use_mp is None:
96 num_workers = 0 # run sequentially in a single process
97 elif ns.use_mp <= 0:
98 num_workers = -1 # run in parallel, use the number of CPUs
99 else:
100 num_workers = ns.use_mp # run in parallel
101 self.num_workers: int = num_workers
102 self.worker_json: StrJSON | None = ns.worker_json
103
104 # Options to run tests
105 self.fail_fast: bool = ns.failfast
106 self.fail_env_changed: bool = ns.fail_env_changed
107 self.fail_rerun: bool = ns.fail_rerun
108 self.forever: bool = ns.forever
109 self.output_on_failure: bool = ns.verbose3
110 self.timeout: float | None = ns.timeout
111 if ns.huntrleaks:
112 warmups, runs, filename = ns.huntrleaks
113 filename = os.path.abspath(filename)
114 self.hunt_refleak: HuntRefleak | None = HuntRefleak(warmups, runs, filename)
115 else:
116 self.hunt_refleak = None
117 self.test_dir: StrPath | None = ns.testdir
118 self.junit_filename: StrPath | None = ns.xmlpath
119 self.memory_limit: str | None = ns.memlimit
120 self.gc_threshold: int | None = ns.threshold
121 self.use_resources: dict[str, str | None] = dict(ns.use_resources)
122 if ns.python:
123 self.python_cmd: tuple[str, ...] | None = tuple(ns.python)
124 else:
125 self.python_cmd = None
126 self.coverage: bool = ns.trace
127 self.coverage_dir: StrPath | None = ns.coverdir
128 self._tmp_dir: StrPath | None = ns.tempdir
129
130 # Randomize
131 self.randomize: bool = ns.randomize
132 if ('SOURCE_DATE_EPOCH' in os.environ
133 # don't use the variable if empty
134 and os.environ['SOURCE_DATE_EPOCH']
135 ):
136 self.randomize = False
137 # SOURCE_DATE_EPOCH should be an integer, but use a string to not
138 # fail if it's not integer. random.seed() accepts a string.
139 # https://reproducible-builds.org/docs/source-date-epoch/
140 self.random_seed: int | str = os.environ['SOURCE_DATE_EPOCH']
141 elif ns.random_seed is None:
142 self.random_seed = random.getrandbits(32)
143 else:
144 self.random_seed = ns.random_seed
145 self.prioritize_tests: tuple[str, ...] = tuple(ns.prioritize)
146
147 self.parallel_threads = ns.parallel_threads
148
149 # tests
150 self.first_runtests: RunTests | None = None
151
152 # used by --slowest
153 self.print_slowest: bool = ns.print_slow
154
155 # used to display the progress bar "[ 3/100]"
156 self.start_time = time.perf_counter()
157
158 # used by --single
159 self.single_test_run: bool = ns.single
160 self.next_single_test: TestName | None = None
161 self.next_single_filename: StrPath | None = None
162
163 def log(self, line: str = '') -> None:
164 self.logger.log(line)
165
166 def find_tests(self, tests: TestList | None = None) -> tuple[TestTuple, TestList | None]:
167 if tests is None:
168 tests = []
169 if self.single_test_run:
170 self.next_single_filename = os.path.join(self.tmp_dir, 'pynexttest')
171 try:
172 with open(self.next_single_filename, 'r') as fp:
173 next_test = fp.read().strip()
174 tests = [next_test]
175 except OSError:
176 pass
177
178 if self.fromfile:
179 tests = []
180 # regex to match 'test_builtin' in line:
181 # '0:00:00 [ 4/400] test_builtin -- test_dict took 1 sec'
182 regex = re.compile(r'\btest_[a-zA-Z0-9_]+\b')
183 with open(os.path.join(os_helper.SAVEDCWD, self.fromfile)) as fp:
184 for line in fp:
185 line = line.split('#', 1)[0]
186 line = line.strip()
187 match = regex.search(line)
188 if match is not None:
189 tests.append(match.group())
190
191 strip_py_suffix(tests)
192
193 exclude_tests = set()
194 if self.exclude:
195 for arg in self.cmdline_args:
196 exclude_tests.add(arg)
197 self.cmdline_args = []
198
199 if self.pgo:
200 # add default PGO tests if no tests are specified
201 setup_pgo_tests(self.cmdline_args, self.pgo_extended)
202
203 if self.tsan:
204 setup_tsan_tests(self.cmdline_args)
205
206 if self.tsan_parallel:
207 setup_tsan_parallel_tests(self.cmdline_args)
208
209 alltests = findtests(testdir=self.test_dir,
210 exclude=exclude_tests)
211
212 if not self.fromfile:
213 selected = tests or self.cmdline_args
214 if exclude_tests:
215 # Support "--pgo/--tsan -x test_xxx" command
216 selected = [name for name in selected
217 if name not in exclude_tests]
218 if selected:
219 selected = split_test_packages(selected)
220 else:
221 selected = alltests
222 else:
223 selected = tests
224
225 if self.single_test_run:
226 selected = selected[:1]
227 try:
228 pos = alltests.index(selected[0])
229 self.next_single_test = alltests[pos + 1]
230 except IndexError:
231 pass
232
233 # Remove all the selected tests that precede start if it's set.
234 if self.starting_test:
235 try:
236 del selected[:selected.index(self.starting_test)]
237 except ValueError:
238 print(f"Cannot find starting test: {self.starting_test}")
239 sys.exit(1)
240
241 random.seed(self.random_seed)
242 if self.randomize:
243 random.shuffle(selected)
244
245 for priority_test in reversed(self.prioritize_tests):
246 try:
247 selected.remove(priority_test)
248 except ValueError:
249 print(f"warning: --prioritize={priority_test} used"
250 f" but test not actually selected")
251 continue
252 else:
253 selected.insert(0, priority_test)
254
255 return (tuple(selected), tests)
256
257 @staticmethod
258 def list_tests(tests: TestTuple) -> None:
259 for name in tests:
260 print(name)
261
262 def _rerun_failed_tests(self, runtests: RunTests) -> RunTests:
263 # Configure the runner to re-run tests
264 if self.num_workers == 0 and not self.single_process:
265 # Always run tests in fresh processes to have more deterministic
266 # initial state. Don't re-run tests in parallel but limit to a
267 # single worker process to have side effects (on the system load
268 # and timings) between tests.
269 self.num_workers = 1
270
271 tests, match_tests_dict = self.results.prepare_rerun()
272
273 # Re-run failed tests
274 runtests = runtests.copy(
275 tests=tests,
276 rerun=True,
277 verbose=True,
278 forever=False,
279 fail_fast=False,
280 match_tests_dict=match_tests_dict,
281 output_on_failure=False)
282 self.logger.set_tests(runtests)
283
284 msg = f"Re-running {len(tests)} failed tests in verbose mode"
285 if not self.single_process:
286 msg = f"{msg} in subprocesses"
287 self.log(msg)
288 self._run_tests_mp(runtests, self.num_workers)
289 else:
290 self.log(msg)
291 self.run_tests_sequentially(runtests)
292 return runtests
293
294 def rerun_failed_tests(self, runtests: RunTests) -> None:
295 ansi = get_colors()
296 red, reset = ansi.BOLD_RED, ansi.RESET
297
298 if self.python_cmd:
299 # Temp patch for https://github.com/python/cpython/issues/94052
300 self.log(
301 "Re-running failed tests is not supported with --python "
302 "host runner option."
303 )
304 return
305
306 self.first_state = self.get_state()
307
308 print()
309 rerun_runtests = self._rerun_failed_tests(runtests)
310
311 if self.results.bad:
312 print(
313 f"{red}{count(len(self.results.bad), 'test')} "
314 f"failed again:{reset}"
315 )
316 printlist(self.results.bad)
317
318 self.display_result(rerun_runtests)
319
320 def _run_bisect(self, runtests: RunTests, test: str, progress: str) -> bool:
321 print()
322 title = f"Bisect {test}"
323 if progress:
324 title = f"{title} ({progress})"
325 print(title)
326 print("#" * len(title))
327 print()
328
329 cmd = runtests.create_python_cmd()
330 cmd.extend([
331 "-u", "-m", "test.bisect_cmd",
332 # Limit to 25 iterations (instead of 100) to not abuse CI resources
333 "--max-iter", "25",
334 "-v",
335 # runtests.match_tests is not used (yet) for bisect_cmd -i arg
336 ])
337 cmd.extend(runtests.bisect_cmd_args())
338 cmd.append(test)
339 print("+", shlex.join(cmd), flush=True)
340
341 flush_std_streams()
342
343 import subprocess
344 proc = subprocess.run(cmd, timeout=runtests.timeout)
345 exitcode = proc.returncode
346
347 title = f"{title}: exit code {exitcode}"
348 print(title)
349 print("#" * len(title))
350 print(flush=True)
351
352 if exitcode:
353 print(f"Bisect failed with exit code {exitcode}")
354 return False
355
356 return True
357
358 def run_bisect(self, runtests: RunTests) -> None:
359 tests, _ = self.results.prepare_rerun(clear=False)
360
361 for index, name in enumerate(tests, 1):
362 if len(tests) > 1:
363 progress = f"{index}/{len(tests)}"
364 else:
365 progress = ""
366 if not self._run_bisect(runtests, name, progress):
367 return
368
369 def display_result(self, runtests: RunTests) -> None:
370 # If running the test suite for PGO then no one cares about results.
371 if runtests.pgo:
372 return
373
374 state = self.get_state()
375 print()
376 print(f"== Tests result: {state} ==")
377
378 self.results.display_result(runtests.tests,
379 self.quiet, self.print_slowest)
380
381 def run_test(
382 self, test_name: TestName, runtests: RunTests, tracer: trace.Trace | None
383 ) -> TestResult:
384 if tracer is not None:
385 # If we're tracing code coverage, then we don't exit with status
386 # if on a false return value from main.
387 cmd = ('result = run_single_test(test_name, runtests)')
388 namespace = dict(locals())
389 tracer.runctx(cmd, globals=globals(), locals=namespace)
390 result = namespace['result']
391 result.covered_lines = list(tracer.counts)
392 else:
393 result = run_single_test(test_name, runtests)
394
395 self.results.accumulate_result(result, runtests)
396
397 return result
398
399 def run_tests_sequentially(self, runtests: RunTests) -> None:
400 if self.coverage:
401 tracer = trace.Trace(trace=False, count=True)
402 else:
403 tracer = None
404
405 save_modules = set(sys.modules)
406
407 jobs = runtests.get_jobs()
408 if jobs is not None:
409 tests = count(jobs, 'test')
410 else:
411 tests = 'tests'
412 msg = f"Run {tests} sequentially in a single process"
413 if runtests.timeout:
414 msg += " (timeout: %s)" % format_duration(runtests.timeout)
415 self.log(msg)
416
417 tests_iter = runtests.iter_tests()
418 for test_index, test_name in enumerate(tests_iter, 1):
419 start_time = time.perf_counter()
420
421 self.logger.display_progress(test_index, test_name)
422
423 result = self.run_test(test_name, runtests, tracer)
424
425 # Unload the newly imported test modules (best effort finalization)
426 new_modules = [module for module in sys.modules
427 if module not in save_modules and
428 module.startswith(("test.", "test_"))]
429 for module in new_modules:
430 sys.modules.pop(module, None)
431 # Remove the attribute of the parent module.
432 parent, _, name = module.rpartition('.')
433 try:
434 delattr(sys.modules[parent], name)
435 except (KeyError, AttributeError):
436 pass
437
438 text = str(result)
439 test_time = time.perf_counter() - start_time
440 if test_time >= PROGRESS_MIN_TIME:
441 text = f"{text} in {format_duration(test_time)}"
442 self.logger.display_progress(test_index, text)
443
444 if result.must_stop(self.fail_fast, self.fail_env_changed):
445 break
446
447 def get_state(self) -> str:
448 state = self.results.get_state(self.fail_env_changed)
449 if self.first_state:
450 state = f'{self.first_state} then {state}'
451 return state
452
453 def _run_tests_mp(self, runtests: RunTests, num_workers: int) -> None:
454 from .run_workers import RunWorkers
455 RunWorkers(num_workers, runtests, self.logger, self.results).run()
456
457 def finalize_tests(self, coverage: trace.CoverageResults | None) -> None:
458 if self.next_single_filename:
459 if self.next_single_test:
460 with open(self.next_single_filename, 'w') as fp:
461 fp.write(self.next_single_test + '\n')
462 else:
463 os.unlink(self.next_single_filename)
464
465 if coverage is not None:
466 # uses a new-in-Python 3.13 keyword argument that mypy doesn't know about yet:
467 coverage.write_results(show_missing=True, summary=True, # type: ignore[call-arg]
468 coverdir=self.coverage_dir,
469 ignore_missing_files=True)
470
471 if self.want_run_leaks:
472 os.system("leaks %d" % os.getpid())
473
474 if self.junit_filename:
475 self.results.write_junit(self.junit_filename)
476
477 def display_summary(self) -> None:
478 if self.first_runtests is None:
479 raise ValueError(
480 "Should never call `display_summary()` before calling `_run_test()`"
481 )
482
483 duration = time.perf_counter() - self.logger.start_time
484 filtered = bool(self.match_tests)
485
486 # Total duration
487 print()
488 print("Total duration: %s" % format_duration(duration))
489
490 self.results.display_summary(self.first_runtests, filtered)
491
492 # Result
493 state = self.get_state()
494 print(f"Result: {state}")
495
496 def create_run_tests(self, tests: TestTuple) -> RunTests:
497 return RunTests(
498 tests,
499 fail_fast=self.fail_fast,
500 fail_env_changed=self.fail_env_changed,
501 match_tests=self.match_tests,
502 match_tests_dict=None,
503 rerun=False,
504 forever=self.forever,
505 pgo=self.pgo,
506 pgo_extended=self.pgo_extended,
507 output_on_failure=self.output_on_failure,
508 timeout=self.timeout,
509 verbose=self.verbose,
510 quiet=self.quiet,
511 hunt_refleak=self.hunt_refleak,
512 test_dir=self.test_dir,
513 use_junit=(self.junit_filename is not None),
514 coverage=self.coverage,
515 memory_limit=self.memory_limit,
516 gc_threshold=self.gc_threshold,
517 use_resources=self.use_resources,
518 python_cmd=self.python_cmd,
519 randomize=self.randomize,
520 random_seed=self.random_seed,
521 parallel_threads=self.parallel_threads,
522 )
523
524 def _run_tests(self, selected: TestTuple, tests: TestList | None) -> int:
525 if self.hunt_refleak and self.hunt_refleak.warmups < 3:
526 msg = ("WARNING: Running tests with --huntrleaks/-R and "
527 "less than 3 warmup repetitions can give false positives!")
528 print(msg, file=sys.stdout, flush=True)
529
530 if self.num_workers < 0:
531 # Use all CPUs + 2 extra worker processes for tests
532 # that like to sleep
533 #
534 # os.process.cpu_count() is new in Python 3.13;
535 # mypy doesn't know about it yet
536 self.num_workers = (os.process_cpu_count() or 1) + 2 # type: ignore[attr-defined]
537
538 # For a partial run, we do not need to clutter the output.
539 if (self.want_header
540 or not(self.pgo or self.quiet or self.single_test_run
541 or tests or self.cmdline_args)):
542 display_header(self.use_resources, self.python_cmd)
543
544 print("Using random seed:", self.random_seed)
545
546 runtests = self.create_run_tests(selected)
547 self.first_runtests = runtests
548 self.logger.set_tests(runtests)
549
550 if (runtests.hunt_refleak is not None) and (not self.num_workers):
551 # gh-109739: WindowsLoadTracker thread interferes with refleak check
552 use_load_tracker = False
553 else:
554 # WindowsLoadTracker is only needed on Windows
555 use_load_tracker = MS_WINDOWS
556
557 if use_load_tracker:
558 self.logger.start_load_tracker()
559 try:
560 if self.num_workers:
561 self._run_tests_mp(runtests, self.num_workers)
562 else:
563 self.run_tests_sequentially(runtests)
564
565 coverage = self.results.get_coverage_results()
566 self.display_result(runtests)
567
568 if self.want_rerun and self.results.need_rerun():
569 self.rerun_failed_tests(runtests)
570
571 if self.want_bisect and self.results.need_rerun():
572 self.run_bisect(runtests)
573 finally:
574 if use_load_tracker:
575 self.logger.stop_load_tracker()
576
577 self.display_summary()
578 self.finalize_tests(coverage)
579
580 return self.results.get_exitcode(self.fail_env_changed,
581 self.fail_rerun)
582
583 def run_tests(self, selected: TestTuple, tests: TestList | None) -> int:
584 os.makedirs(self.tmp_dir, exist_ok=True)
585 work_dir = get_work_dir(self.tmp_dir)
586
587 # Put a timeout on Python exit
588 with exit_timeout():
589 # Run the tests in a context manager that temporarily changes the
590 # CWD to a temporary and writable directory. If it's not possible
591 # to create or change the CWD, the original CWD will be used.
592 # The original CWD is available from os_helper.SAVEDCWD.
593 with os_helper.temp_cwd(work_dir, quiet=True):
594 # When using multiprocessing, worker processes will use
595 # work_dir as their parent temporary directory. So when the
596 # main process exit, it removes also subdirectories of worker
597 # processes.
598 return self._run_tests(selected, tests)
599
600 def _add_cross_compile_opts(self, regrtest_opts):
601 # WASM/WASI buildbot builders pass multiple PYTHON environment
602 # variables such as PYTHONPATH and _PYTHON_HOSTRUNNER.
603 keep_environ = bool(self.python_cmd)
604 environ = None
605
606 # Are we using cross-compilation?
607 cross_compile = is_cross_compiled()
608
609 # Get HOSTRUNNER
610 hostrunner = get_host_runner()
611
612 if cross_compile:
613 # emulate -E, but keep PYTHONPATH + cross compile env vars,
614 # so test executable can load correct sysconfigdata file.
615 keep = {
616 '_PYTHON_PROJECT_BASE',
617 '_PYTHON_HOST_PLATFORM',
618 '_PYTHON_SYSCONFIGDATA_NAME',
619 "_PYTHON_SYSCONFIGDATA_PATH",
620 'PYTHONPATH'
621 }
622 old_environ = os.environ
623 new_environ = {
624 name: value for name, value in os.environ.items()
625 if not name.startswith(('PYTHON', '_PYTHON')) or name in keep
626 }
627 # Only set environ if at least one variable was removed
628 if new_environ != old_environ:
629 environ = new_environ
630 keep_environ = True
631
632 if cross_compile and hostrunner:
633 if self.num_workers == 0 and not self.single_process:
634 # For now use only two cores for cross-compiled builds;
635 # hostrunner can be expensive.
636 regrtest_opts.extend(['-j', '2'])
637
638 # If HOSTRUNNER is set and -p/--python option is not given, then
639 # use hostrunner to execute python binary for tests.
640 if not self.python_cmd:
641 buildpython = sysconfig.get_config_var("BUILDPYTHON")
642 python_cmd = f"{hostrunner} {buildpython}"
643 regrtest_opts.extend(["--python", python_cmd])
644 keep_environ = True
645
646 return (environ, keep_environ)
647
648 def _add_ci_python_opts(self, python_opts, keep_environ):
649 # --fast-ci and --slow-ci add options to Python.
650 #
651 # Some platforms run tests in embedded mode and cannot change options
652 # after startup, so if this function changes, consider also updating:
653 # * gradle_task in Android/android.py
654
655 # Unbuffered stdout and stderr. This isn't helpful on Android, because
656 # it would cause lines to be split into multiple log messages.
657 if not sys.stdout.write_through and sys.platform != "android":
658 python_opts.append('-u')
659
660 # Add warnings filter 'error', unless the user specified a different
661 # filter. Ignore BytesWarning since it's controlled by '-b' below.
662 if not [
663 opt for opt in sys.warnoptions
664 if not opt.endswith("::BytesWarning")
665 ]:
666 python_opts.extend(('-W', 'error'))
667
668 # Error on bytes/str comparison
669 if sys.flags.bytes_warning < 2:
670 python_opts.append('-bb')
671
672 if not keep_environ:
673 # Ignore PYTHON* environment variables
674 if not sys.flags.ignore_environment:
675 python_opts.append('-E')
676
677 def _execute_python(self, cmd, environ):
678 # Make sure that messages before execv() are logged
679 sys.stdout.flush()
680 sys.stderr.flush()
681
682 cmd_text = shlex.join(cmd)
683 try:
684 # Android and iOS run tests in embedded mode. To update their
685 # Python options, see the comment in _add_ci_python_opts.
686 if not cmd[0]:
687 raise ValueError("No Python executable is present")
688
689 print(f"+ {cmd_text}", flush=True)
690 if hasattr(os, 'execv') and not MS_WINDOWS:
691 os.execv(cmd[0], cmd)
692 # On success, execv() do no return.
693 # On error, it raises an OSError.
694 else:
695 import subprocess
696 with subprocess.Popen(cmd, env=environ) as proc:
697 try:
698 proc.wait()
699 except KeyboardInterrupt:
700 # There is no need to call proc.terminate(): on CTRL+C,
701 # SIGTERM is also sent to the child process.
702 try:
703 proc.wait(timeout=EXIT_TIMEOUT)
704 except subprocess.TimeoutExpired:
705 proc.kill()
706 proc.wait()
707 sys.exit(EXITCODE_INTERRUPTED)
708
709 sys.exit(proc.returncode)
710 except Exception as exc:
711 print_warning(f"Failed to change Python options: {exc!r}\n"
712 f"Command: {cmd_text}")
713 # continue executing main()
714
715 def _add_python_opts(self) -> None:
716 python_opts: list[str] = []
717 regrtest_opts: list[str] = []
718
719 environ, keep_environ = self._add_cross_compile_opts(regrtest_opts)
720 if self.ci_mode:
721 self._add_ci_python_opts(python_opts, keep_environ)
722
723 if (not python_opts) and (not regrtest_opts) and (environ is None):
724 # Nothing changed: nothing to do
725 return
726
727 # Create new command line
728 cmd = list(sys.orig_argv)
729 if python_opts:
730 cmd[1:1] = python_opts
731 if regrtest_opts:
732 cmd.extend(regrtest_opts)
733 cmd.append("--dont-add-python-opts")
734
735 self._execute_python(cmd, environ)
736
737 def _init(self):
738 setup_process()
739
740 if self.junit_filename and not os.path.isabs(self.junit_filename):
741 self.junit_filename = os.path.abspath(self.junit_filename)
742
743 strip_py_suffix(self.cmdline_args)
744
745 self._tmp_dir = get_temp_dir(self._tmp_dir)
746
747 @property
748 def tmp_dir(self) -> StrPath:
749 if self._tmp_dir is None:
750 raise ValueError(
751 "Should never use `.tmp_dir` before calling `.main()`"
752 )
753 return self._tmp_dir
754
755 def main(self, tests: TestList | None = None) -> NoReturn:
756 if self.want_add_python_opts:
757 self._add_python_opts()
758
759 self._init()
760
761 if self.want_cleanup:
762 cleanup_temp_dir(self.tmp_dir)
763 sys.exit(0)
764
765 if self.want_wait:
766 input("Press any key to continue...")
767
768 setup_test_dir(self.test_dir)
769 selected, tests = self.find_tests(tests)
770
771 exitcode = 0
772 if self.want_list_tests:
773 self.list_tests(selected)
774 elif self.want_list_cases:
775 list_cases(selected,
776 match_tests=self.match_tests,
777 test_dir=self.test_dir)
778 else:
779 exitcode = self.run_tests(selected, tests)
780
781 sys.exit(exitcode)
782
783
784 def main(tests=None, _add_python_opts=False, **kwargs) -> NoReturn:
785 """Run the Python suite."""
786 ns = _parse_args(sys.argv[1:], **kwargs)
787 Regrtest(ns, _add_python_opts=_add_python_opts).main(tests=tests)