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