| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
from typing import TYPE_CHECKING, Final, NoReturn, cast |
| 5 |
|
| 6 |
from capabilities import CAPABILITIES |
| 7 |
|
| 8 |
if TYPE_CHECKING: |
| 9 |
from collections.abc import Callable |
| 10 |
from typing import Protocol |
| 11 |
|
| 12 |
class _RegisterAtFork(Protocol): |
| 13 |
def __call__(self, *, after_in_child: Callable[[], None] | None = None) -> None: ... |
| 14 |
|
| 15 |
|
| 16 |
_FORK: Final[Callable[[], int] | None] = cast( |
| 17 |
"Callable[[], int] | None", |
| 18 |
getattr(os, "fork", None), # fork is absent from Windows at runtime and in its type interface |
| 19 |
) |
| 20 |
_REGISTER_AT_FORK: Final[_RegisterAtFork | None] = cast( |
| 21 |
"_RegisterAtFork | None", |
| 22 |
getattr( # register_at_fork is absent from Windows at runtime and in its type interface |
| 23 |
os, |
| 24 |
"register_at_fork", |
| 25 |
None, |
| 26 |
), |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
def fork_process(child: Callable[[], NoReturn] | None = None) -> int: # pragma: win32 no cover |
| 31 |
if _FORK is None: # pragma: no cover - platform without os.fork |
| 32 |
msg = "os.fork is unavailable" |
| 33 |
raise RuntimeError(msg) |
| 34 |
child_pid = _FORK() |
| 35 |
if child_pid == 0 and child is not None: # pragma: win32 no cover |
| 36 |
child() # pragma: no cover - child coverage starts after fork returns to this frame |
| 37 |
return child_pid |
| 38 |
|
| 39 |
|
| 40 |
def exit_child(status: int) -> NoReturn: |
| 41 |
try: |
| 42 |
_flush_coverage() |
| 43 |
finally: |
| 44 |
# A coverage write failure must not return the fork child to pytest. |
| 45 |
os._exit(status) |
| 46 |
|
| 47 |
|
| 48 |
def _flush_coverage() -> None: # pragma: win32 no cover - a spawned child inherits no coverage to flush |
| 49 |
# An unmeasured run has nothing to write, and importing coverage there would stop the suite from running at all. |
| 50 |
if not CAPABILITIES["coverage"]: # pragma: lacks coverage |
| 51 |
return |
| 52 |
from coverage import Coverage |
| 53 |
|
| 54 |
# Reaching the other side needs coverage inactive, which is when nothing gets recorded anyway. |
| 55 |
if (coverage := Coverage.current()) is not None: # pragma: no branch |
| 56 |
coverage.save() |
| 57 |
|
| 58 |
|
| 59 |
def _restart_coverage_after_fork() -> None: # pragma: win32 no cover |
| 60 |
from coverage import Coverage, process_startup |
| 61 |
|
| 62 |
if (coverage := Coverage.current()) is not None: # pragma: win32 no cover |
| 63 |
coverage.stop() |
| 64 |
process_startup(force=True, slug="fork") # pragma: no cover - coverage is stopped until this call returns |
| 65 |
|
| 66 |
|
| 67 |
if _REGISTER_AT_FORK is not None and CAPABILITIES["coverage"]: # pragma: win32 no cover |
| 68 |
_REGISTER_AT_FORK(after_in_child=_restart_coverage_after_fork) |
| 69 |
|
| 70 |
|
| 71 |
__all__ = ["exit_child", "fork_process"] |