Debian Codegraph @

Lib/test/libregrtest/worker.py

raw
1 import subprocess
2 import sys
3 import os
4 from _colorize import can_colorize # type: ignore[import-not-found]
5 from typing import Any, NoReturn
6
7 from test.support import os_helper, Py_DEBUG
8
9 from .setup import setup_process, setup_test_dir
10 from .runtests import WorkerRunTests, JsonFile, JsonFileType
11 from .single import run_single_test
12 from .utils import (
13 StrPath, StrJSON, TestFilter,
14 get_temp_dir, get_work_dir, exit_timeout)
15
16
17 USE_PROCESS_GROUP = (hasattr(os, "setsid") and hasattr(os, "killpg"))
18
19
20 def create_worker_process(runtests: WorkerRunTests, output_fd: int,
21 tmp_dir: StrPath | None = None) -> subprocess.Popen[str]:
22 worker_json = runtests.as_json()
23
24 cmd = runtests.create_python_cmd()
25 cmd.extend(['-m', 'test.libregrtest.worker', worker_json])
26
27 env = dict(os.environ)
28 if tmp_dir is not None:
29 env['TMPDIR'] = tmp_dir
30 env['TEMP'] = tmp_dir
31 env['TMP'] = tmp_dir
32
33 # The subcommand is run with a temporary output which means it is not a TTY
34 # and won't auto-color. The test results are printed to stdout so if we can
35 # color that have the subprocess use color.
36 if can_colorize(file=sys.stdout):
37 env['FORCE_COLOR'] = '1'
38
39 # Running the child from the same working directory as regrtest's original
40 # invocation ensures that TEMPDIR for the child is the same when
41 # sysconfig.is_python_build() is true. See issue 15300.
42 #
43 # Emscripten and WASI Python must start in the Python source code directory
44 # to get 'python.js' or 'python.wasm' file. Then worker_process() changes
45 # to a temporary directory created to run tests.
46 work_dir = os_helper.SAVEDCWD
47
48 kwargs: dict[str, Any] = dict(
49 env=env,
50 stdout=output_fd,
51 # bpo-45410: Write stderr into stdout to keep messages order
52 stderr=output_fd,
53 text=True,
54 close_fds=True,
55 cwd=work_dir,
56 )
57 if USE_PROCESS_GROUP:
58 kwargs['start_new_session'] = True
59
60 # Pass json_file to the worker process
61 json_file = runtests.json_file
62 json_file.configure_subprocess(kwargs)
63
64 with json_file.inherit_subprocess():
65 return subprocess.Popen(cmd, **kwargs)
66
67
68 def worker_process(worker_json: StrJSON) -> NoReturn:
69 runtests = WorkerRunTests.from_json(worker_json)
70 test_name = runtests.tests[0]
71 match_tests: TestFilter = runtests.match_tests
72 json_file: JsonFile = runtests.json_file
73
74 setup_test_dir(runtests.test_dir)
75 setup_process()
76
77 if runtests.rerun:
78 if match_tests:
79 matching = "matching: " + ", ".join(pattern for pattern, result in match_tests if result)
80 print(f"Re-running {test_name} in verbose mode ({matching})", flush=True)
81 else:
82 print(f"Re-running {test_name} in verbose mode", flush=True)
83
84 result = run_single_test(test_name, runtests)
85 if runtests.coverage:
86 if "test.cov" in sys.modules: # imported by -Xpresite=
87 result.covered_lines = list(sys.modules["test.cov"].coverage)
88 elif not Py_DEBUG:
89 print(
90 "Gathering coverage in worker processes requires --with-pydebug",
91 flush=True,
92 )
93 else:
94 raise LookupError(
95 "`test.cov` not found in sys.modules but coverage wanted"
96 )
97
98 if json_file.file_type == JsonFileType.STDOUT:
99 print()
100 result.write_json_into(sys.stdout)
101 else:
102 with json_file.open('w', encoding='utf-8') as json_fp:
103 result.write_json_into(json_fp)
104
105 sys.exit(0)
106
107
108 def main() -> NoReturn:
109 if len(sys.argv) != 2:
110 print("usage: python -m test.libregrtest.worker JSON")
111 sys.exit(1)
112 worker_json = sys.argv[1]
113
114 tmp_dir = get_temp_dir()
115 # get_temp_dir() can be different in the worker and the parent process.
116 # For example, if --tempdir option is used.
117 os.makedirs(tmp_dir, exist_ok=True)
118 work_dir = get_work_dir(tmp_dir, worker=True)
119
120 with exit_timeout():
121 with os_helper.temp_cwd(work_dir, quiet=True):
122 worker_process(worker_json)
123
124
125 if __name__ == "__main__":
126 main()