Debian Codegraph @

Lib/test/support/isolation.py

raw
1 """Run tests in isolated subprocesses (the test.support.isolation.runInSubprocess decorator).
2
3 A failure, error or skip that happens in the subprocess is replayed in the
4 parent process so that the test runner records it. The original (subprocess)
5 traceback is attached as the cause of the replayed exception, the same way
6 :mod:`concurrent.futures` surfaces tracebacks from worker processes.
7 """
8
9 import functools
10 import os
11 import sys
12 import unittest
13
14 # Let unittest strip this module's frames from tracebacks, so only the original
15 # subprocess traceback (attached as the cause) is shown, not the replay frames.
16 __unittest = True
17
18 # test.support globals set by regrtest (libregrtest/setup.py) that affect how
19 # tests run and which are skipped at runtime in the subprocess.
20 _PROPAGATED_CONFIG = (
21 'use_resources', # -u (is_resource_enabled/requires)
22 'max_memuse', 'real_max_memuse', # -M (bigmemtest)
23 'verbose', # -v
24 'failfast', # -f
25 )
26
27 def _child_config():
28 import test.support as support
29 return {name: getattr(support, name) for name in _PROPAGATED_CONFIG}
30
31 def _apply_child_config(config):
32 """Set up the child to run the test like a regrtest worker would.
33
34 Mark this process as the subprocess, mirror the parent's -u/-M/-v config,
35 then suppress the Windows CRT assertion dialogs, which would block a debug
36 build on a modal dialog and hang the parent.
37 """
38 global runningInSubprocess
39 import marshal
40 import test.support as support
41 runningInSubprocess = True
42 for name, value in marshal.loads(bytes.fromhex(config)).items():
43 setattr(support, name, value)
44 support.suppress_msvcrt_asserts(support.verbose >= 2)
45
46 # True inside the subprocess spawned by @runInSubprocess(), set by
47 # _apply_child_config() before the test is imported. Fixtures can test it to
48 # decide what to run in the subprocess as opposed to the parent process.
49 runningInSubprocess = False
50
51
52 class _RemoteTraceback(Exception):
53 """Carry a formatted traceback string from the subprocess for display.
54
55 Attached as the ``__cause__`` of the replayed failure/error, so that the
56 original traceback is shown by the traceback machinery.
57 """
58 def __init__(self, tb):
59 self.tb = tb
60
61 def __str__(self):
62 return self.tb
63
64
65 class _SubprocessTestError(Exception):
66 """Replay a subprocess error (as opposed to a failure) in the parent."""
67
68
69 def _decode(data):
70 # Decode the child output, which is only ever shown as a diagnostic: an
71 # undecodable byte must not hide the failure it is part of.
72 if not data:
73 return ''
74 import locale
75 encoding = 'utf-8' if sys.flags.utf8_mode else locale.getencoding()
76 return data.decode(encoding, 'backslashreplace').replace('\r\n', '\n')
77
78
79 def _remote(detail):
80 # Wrap the subprocess traceback the way concurrent.futures does, so it is
81 # clearly delimited when shown as the cause. Return None if the subprocess
82 # said nothing (a hung one usually does not), so that "raise ... from None"
83 # suppresses an empty cause.
84 if not detail:
85 return None
86 return _RemoteTraceback(f'\n"""\n{detail}"""')
87
88
89 def _check_subprocess_support():
90 # runInSubprocess() always runs the test in a subprocess, so skip (in the
91 # parent) on platforms that do not support spawning one.
92 import test.support as support
93 if not support.has_subprocess_support:
94 raise unittest.SkipTest('requires subprocess support')
95
96
97 def _child_environ(env):
98 # Start from the inherited environment, so that *env* only has to name what
99 # the test changes.
100 if not env:
101 return None
102 environ = dict(os.environ)
103 for name, value in env.items():
104 if value is None:
105 environ.pop(name, None)
106 else:
107 environ[name] = value
108 return environ
109
110
111 def _run_in_subprocess(module, qualname, options, env, timeout):
112 """Run module.qualname (a test method or class) in a fresh subprocess.
113
114 Return ``(payload, output, returncode)``, where *payload* is the decoded
115 ``{'outcomes': ..., 'durations': ...}`` mapping from the subprocess, or
116 ``None`` if it did not run to completion (crash, import error, ...).
117 """
118 import marshal
119 import subprocess
120 import tempfile
121 fd, result_path = tempfile.mkstemp(suffix='.json')
122 os.close(fd)
123 try:
124 # Pass the config on the command line, not in the environment, so that
125 # the test cannot pass it on to the processes it spawns itself, and so
126 # that it survives the -E and -I options. Use marshal, not json: it is
127 # built in, so the child imports nothing that the test would not see in
128 # a normal test run.
129 cmd = [sys.executable, *options, '-m', 'test.support.subprocess_runner',
130 module, qualname, result_path,
131 marshal.dumps(_child_config()).hex()]
132 try:
133 proc = subprocess.run(cmd, capture_output=True,
134 env=_child_environ(env), timeout=timeout)
135 except subprocess.TimeoutExpired as exc:
136 # Report the hang rather than leaving the test runner stuck.
137 output = _decode(exc.stdout) + _decode(exc.stderr)
138 raise _SubprocessTestError(
139 f'test did not complete in a subprocess '
140 f'within {timeout} seconds') from _remote(output)
141 try:
142 with open(result_path, 'rb') as f:
143 payload = marshal.load(f)
144 except (OSError, EOFError, ValueError):
145 payload = None
146 finally:
147 try:
148 os.unlink(result_path)
149 except OSError:
150 pass
151 return payload, _decode(proc.stdout) + _decode(proc.stderr), proc.returncode
152
153
154 def _replay_outcome(test, outcome):
155 kind = outcome['kind']
156 detail = outcome['detail']
157 if kind == 'skipped':
158 test.skipTest(detail) # the detail is the skip reason, not a traceback
159 elif kind in ('failure', 'expected_failure'):
160 # Replay an expected failure like a failure: the wrapper keeps the
161 # @expectedFailure marker (via functools.wraps), so the parent records
162 # the raised exception as an expectedFailure.
163 exc = test.failureException('test failed in the subprocess')
164 raise exc from _remote(detail)
165 else: # 'error'
166 exc = _SubprocessTestError('test failed in the subprocess')
167 raise exc from _remote(detail)
168
169
170 def _replay_outcomes(test, outcomes):
171 # Replay each subtest outcome in its own subTest() context so that they are
172 # reported individually, then replay the whole-test outcome (if any).
173 main = []
174 for outcome in outcomes:
175 if outcome['subtest']:
176 with test.subTest(outcome['desc']):
177 _replay_outcome(test, outcome)
178 else:
179 main.append(outcome)
180 for outcome in main:
181 _replay_outcome(test, outcome)
182
183
184 def _raise_fixture_outcome(outcome):
185 # Reproduce a setUpClass()/setUpModule() failure or skip from the
186 # subprocess in a parent-process fixture, so it applies to every test.
187 if outcome['kind'] == 'skipped':
188 raise unittest.SkipTest(outcome['detail'])
189 exc = _SubprocessTestError('class failed in the subprocess')
190 raise exc from _remote(outcome['detail'])
191
192
193 def _check_returncode(returncode, output, what):
194 # The subprocess writes its result before exiting, so a non-zero exit code
195 # means it died afterwards, during finalization, unnoticed by the result.
196 if returncode:
197 exc = _SubprocessTestError(
198 f'the subprocess exited with code {returncode} '
199 f'after running the {what}')
200 raise exc from _remote(output)
201
202
203 def _isolate_method(func, options, env, timeout):
204 @functools.wraps(func)
205 def wrapper(self, /, *args, **kwargs):
206 if runningInSubprocess:
207 # Already running in the subprocess: run the real test.
208 return func(self, *args, **kwargs)
209 _check_subprocess_support()
210 cls = type(self)
211 qualname = f'{cls.__qualname__}.{func.__name__}'
212 payload, output, returncode = _run_in_subprocess(cls.__module__,
213 qualname, options,
214 env, timeout)
215 if payload is None:
216 exc = _SubprocessTestError(
217 f'test did not complete in a subprocess (exit code {returncode})')
218 raise exc from _remote(output)
219 # The parent measures this method's own duration (the real cost of the
220 # isolated run, subprocess startup included), so nothing to forward here.
221 # Replay the outcomes first: a failure of the test itself is more useful.
222 _replay_outcomes(self, payload['outcomes'])
223 _check_returncode(returncode, output, 'test')
224 return wrapper
225
226
227 def _isolate_class(cls, options, env, timeout):
228 # Unwrap to the plain functions so the replacements can call them with the
229 # runtime cls; a bound classmethod would freeze the decoration-time class
230 # and a subclass would run the fixtures bound to the base class.
231 orig_setUpClass = cls.setUpClass.__func__
232 orig_tearDownClass = cls.tearDownClass.__func__
233 # Hook the _call*() indirections rather than setUp(), tearDown() and the
234 # test methods themselves, to cover what a subclass adds or overrides too.
235 orig_callSetUp = cls._callSetUp
236 orig_callTearDown = cls._callTearDown
237 orig_callTestMethod = cls._callTestMethod
238 orig_addDuration = cls._addDuration
239
240 def setUpClass(cls):
241 if runningInSubprocess:
242 orig_setUpClass(cls)
243 return
244 _check_subprocess_support()
245 # Run the whole class in a single subprocess and stash the outcomes
246 # for the test methods to replay.
247 payload, output, returncode = _run_in_subprocess(cls.__module__,
248 cls.__qualname__,
249 options, env, timeout)
250 if payload is None:
251 exc = _SubprocessTestError(
252 f'class did not complete in a subprocess (exit code {returncode})')
253 raise exc from _remote(output)
254 by_id = {}
255 for outcome in payload['outcomes']:
256 if outcome['fixture']:
257 # A setUpClass()/setUpModule() failure or skip: apply it to the
258 # whole class by raising it here, in the parent's setUpClass().
259 _raise_fixture_outcome(outcome)
260 by_id.setdefault(outcome['id'], []).append(outcome)
261 cls._isolated_outcomes = by_id
262 cls._isolated_durations = dict(payload.get('durations', ()))
263 # Report the crash from tearDownClass(), after replaying the outcomes.
264 cls._isolated_exit = (returncode, output)
265
266 def tearDownClass(cls):
267 if runningInSubprocess:
268 orig_tearDownClass(cls)
269 return
270 cls._isolated_outcomes = None
271 cls._isolated_durations = None
272 # Missing if an overriding setUpClass() bypassed the subprocess.
273 exited = getattr(cls, '_isolated_exit', None)
274 cls._isolated_exit = None
275 if exited is not None:
276 _check_returncode(*exited, 'class')
277
278 def _callSetUp(self):
279 # In the parent the real test does not run, so neither should setUp().
280 if runningInSubprocess:
281 orig_callSetUp(self)
282
283 def _callTearDown(self):
284 if runningInSubprocess:
285 orig_callTearDown(self)
286
287 def _callTestMethod(self, method):
288 if runningInSubprocess:
289 orig_callTestMethod(self, method)
290 return
291 by_id = getattr(type(self), '_isolated_outcomes', None)
292 if by_id is None:
293 raise _SubprocessTestError(
294 f'{type(self).__name__} did not run in a subprocess; '
295 f'an overriding setUpClass() must call super().setUpClass()')
296 _replay_outcomes(self, by_id.get(self.id(), []))
297
298 def _addDuration(self, result, elapsed):
299 # In the parent, report the subprocess timing rather than the (instant)
300 # replay time; subprocess startup is paid once, in setUpClass.
301 if not runningInSubprocess:
302 durations = getattr(type(self), '_isolated_durations', None) or {}
303 elapsed = durations.get(self.id(), elapsed)
304 orig_addDuration(self, result, elapsed)
305
306 cls.setUpClass = classmethod(setUpClass)
307 cls.tearDownClass = classmethod(tearDownClass)
308 cls._callSetUp = _callSetUp
309 cls._callTearDown = _callTearDown
310 cls._callTestMethod = _callTestMethod
311 cls._addDuration = _addDuration
312 return cls
313
314
315 def runInSubprocess(*, options=(), env=None, timeout=None):
316 """Decorator to run a test method or class in a fresh subprocess.
317
318 The decorated test runs in a separate, fresh Python process, so it does not
319 share global or interpreter state with the rest of the test run. When a
320 :class:`~unittest.TestCase` subclass is decorated, the whole class runs in a
321 single subprocess and its ``setUpClass()``/``setUpModule()`` fixtures run
322 once there; when a method is decorated, only that method runs in a
323 subprocess. Decorated methods must take no extra arguments.
324
325 *options* is a sequence of interpreter command line options for the
326 subprocess, and *env* is a mapping of environment variables to set in it,
327 on top of the inherited environment; a value of ``None`` unsets a variable.
328 Note that ``-E`` and ``-I`` make the subprocess ignore the ``PYTHON*``
329 variables, including ``PYTHONPATH``.
330
331 *timeout* is the number of seconds to wait for the subprocess; the test is
332 reported as an error if it does not complete in time. By default there is
333 no timeout, and a hung test is left to the timeout of the test runner.
334
335 A failure, error or skip of the whole test is reported for the test, and
336 individual subtests (:meth:`~unittest.TestCase.subTest`) that fail or are
337 skipped are reported individually. The original subprocess traceback is
338 shown as the cause of a reported failure or error. Use
339 :data:`runningInSubprocess` in fixtures to choose what to run in the subprocess.
340
341 The test is skipped on platforms without subprocess support, since it must
342 spawn one.
343 """
344 def decorator(obj):
345 if isinstance(obj, type) and issubclass(obj, unittest.TestCase):
346 return _isolate_class(obj, options, env, timeout)
347 return _isolate_method(obj, options, env, timeout)
348 return decorator