diff --git a/packages/desktop/tests/conftest.py b/packages/desktop/tests/conftest.py index 3cf264c1d5..cdfb7ce65c 100644 --- a/packages/desktop/tests/conftest.py +++ b/packages/desktop/tests/conftest.py @@ -165,21 +165,88 @@ def no_usage_stats_or_update_check(monkeypatch): monkeypatch.setenv("OPENADAPT_UPDATE_CHECK", "false") +# On the hosted macOS runners a forked copy of the pytest process sometimes never +# reached exec, and pytest then waited inside Popen until the job was cancelled. +# The whole session therefore starts subprocesses without forking. +# +# Python starts a child with posix_spawn instead of fork when the program path +# is absolute, no working directory or new session is asked for, and +# ``close_fds`` is false. Most calls here and in the engine fail only the last +# condition, because ``close_fds`` defaults to true, so the session changes that +# default. Python opens its own descriptors close-on-exec, so a child still +# inherits only its standard streams. A call that would fork anyway fails with +# the reason, unless the test asks for the ``forking_allowed`` fixture. +# Windows has no fork and is left alone. Tests of how the engine itself starts a +# process ask for ``python_subprocess_defaults`` and get none of this. +_FORKS: list[str] = [] +_REAL: dict[str, object] = {} +_FORKING_ALLOWED = False + + +def _spawn_is_available() -> bool: + return bool(getattr(subprocess, "_USE_POSIX_SPAWN", False)) + + +@pytest.fixture(scope="session", autouse=True) +def _subprocesses_do_not_fork(): + if not _spawn_is_available(): + yield + return + + patch = pytest.MonkeyPatch() + real_init = subprocess.Popen.__init__ + real_fork_exec = subprocess._fork_exec + + def init(self, *args, **kwargs): + # close_fds is the eighth positional parameter of Popen. + if len(args) < 8 and "close_fds" not in kwargs and not kwargs.get("pass_fds"): + kwargs["close_fds"] = False + real_init(self, *args, **kwargs) + + def fork_exec(args, *rest, **named): + command = " ".join(os.fsdecode(part) for part in args) + if not _FORKING_ALLOWED: + raise AssertionError( + f"{command!r} would fork pytest. Give the program's absolute path, " + "do not pass cwd, start_new_session, preexec_fn or pass_fds, " + "and run git through native_release.run_git." + ) + _FORKS.append(command) + return real_fork_exec(args, *rest, **named) + + _REAL.update(init=real_init, fork_exec=real_fork_exec) + patch.setattr(subprocess.Popen, "__init__", init) + patch.setattr(subprocess, "_fork_exec", fork_exec) + yield + patch.undo() + _REAL.clear() + + @pytest.fixture -def no_subprocess_fork(monkeypatch: pytest.MonkeyPatch) -> None: - """Fail any subprocess that would fork pytest. - - By the time the release tests run, earlier tests have loaded macOS system - frameworks into the pytest process. On the hosted macOS runners a forked - copy of that process sometimes never reached exec, and the parent waited - inside Popen until the job was cancelled. With this guard a call that - brings the fork back fails at once, on Linux as well as macOS. +def python_subprocess_defaults(monkeypatch: pytest.MonkeyPatch) -> None: + """Give this test Python's own subprocess behaviour, as the installed engine has it. + + A test that checks how production code starts a process must not get the + session's ``close_fds`` default, or it would pass whatever the code did. """ - if not getattr(subprocess, "_USE_POSIX_SPAWN", False): - return + if _REAL: + monkeypatch.setattr(subprocess.Popen, "__init__", _REAL["init"]) + monkeypatch.setattr(subprocess, "_fork_exec", _REAL["fork_exec"]) + + +@pytest.fixture +def forking_allowed(): + """Let this test start subprocesses that Python can only start with fork.""" + + global _FORKING_ALLOWED + _FORKING_ALLOWED = True + yield + _FORKING_ALLOWED = False - def refuse(args, *_rest, **_named): - raise AssertionError(f"{args!r} would fork pytest; run git through native_release.run_git") - monkeypatch.setattr(subprocess, "_fork_exec", refuse) +def pytest_terminal_summary(terminalreporter) -> None: + if _spawn_is_available(): + terminalreporter.write_line(f"subprocesses that forked pytest: {len(_FORKS)}") + for command in _FORKS: + terminalreporter.write_line(f" forked: {command[:200]}") diff --git a/packages/desktop/tests/test_engine/test_child_process.py b/packages/desktop/tests/test_engine/test_child_process.py index 61ccb8e436..3b5f2b3ff5 100644 --- a/packages/desktop/tests/test_engine/test_child_process.py +++ b/packages/desktop/tests/test_engine/test_child_process.py @@ -12,6 +12,10 @@ from openadapt_desktop import child_process +# These tests check what the engine does with Python's real defaults, so they +# opt out of the test session's own no-fork setup (see tests/conftest.py). +pytestmark = pytest.mark.usefixtures("python_subprocess_defaults") + ENGINE = Path(child_process.__file__).resolve().parent STARTERS = {"run", "Popen", "call", "check_call", "check_output", "getoutput", "getstatusoutput"} OS_STARTERS = {"system", "popen", "fork", "forkpty", "posix_spawn", "posix_spawnp"} @@ -76,7 +80,7 @@ def test_run_starts_a_child_without_forking(fork_refused: None) -> None: ) assert done.returncode == 0 and done.stdout.strip() == "ready" with pytest.raises(AssertionError, match="would fork the engine"): - subprocess.run([sys.executable, "-c", "pass"]) + subprocess.run([sys.executable, "-c", "pass"], close_fds=True) def test_popen_with_pipes_starts_a_child_without_forking(fork_refused: None) -> None: diff --git a/packages/desktop/tests/test_native_installer_smoke.py b/packages/desktop/tests/test_native_installer_smoke.py index 1cfd35361c..02974b8535 100644 --- a/packages/desktop/tests/test_native_installer_smoke.py +++ b/packages/desktop/tests/test_native_installer_smoke.py @@ -591,13 +591,17 @@ def _fake_launcher(tmp_path: Path, name: str, python_body: str) -> Path: return launcher -def test_launch_probe_accepts_a_process_that_stays_alive(tmp_path: Path) -> None: +def test_launch_probe_accepts_a_process_that_stays_alive( + tmp_path: Path, forking_allowed: None +) -> None: launcher = _fake_launcher(tmp_path, "healthy", "import time\ntime.sleep(60)\n") smoke._launch_probe(launcher, run_seconds=1.0, timeout=30.0) -def test_launch_probe_rejects_a_startup_crash_and_retries_once(tmp_path: Path) -> None: +def test_launch_probe_rejects_a_startup_crash_and_retries_once( + tmp_path: Path, forking_allowed: None +) -> None: attempts = tmp_path / "attempts.log" body = ( "import pathlib, sys\n" @@ -618,7 +622,9 @@ def test_launch_probe_rejects_a_startup_crash_and_retries_once(tmp_path: Path) - assert attempts.read_text().count("attempt") == 2 -def test_launch_probe_reports_an_unlaunchable_executable(tmp_path: Path) -> None: +def test_launch_probe_reports_an_unlaunchable_executable( + tmp_path: Path, forking_allowed: None +) -> None: with pytest.raises(smoke.SmokeTestError, match="could not launch"): smoke._launch_probe(tmp_path / "absent", run_seconds=1.0, timeout=5.0) diff --git a/packages/desktop/tests/test_native_release.py b/packages/desktop/tests/test_native_release.py index e0379e0c78..8cf3e62a14 100644 --- a/packages/desktop/tests/test_native_release.py +++ b/packages/desktop/tests/test_native_release.py @@ -49,9 +49,6 @@ ) ROOT = Path(__file__).resolve().parents[1] -# These tests run in the same pytest process as the release-intent tests, so -# their git calls must not fork it either; see conftest.py. -pytestmark = pytest.mark.usefixtures("no_subprocess_fork") # Desktop's workflows run from the OpenAdapt monorepo root. MONOREPO_WORKFLOWS = ROOT.parents[1] / ".github" / "workflows" WORKFLOW_FILES = { diff --git a/packages/desktop/tests/test_release_intent.py b/packages/desktop/tests/test_release_intent.py index 59f8f28a59..79793236b2 100644 --- a/packages/desktop/tests/test_release_intent.py +++ b/packages/desktop/tests/test_release_intent.py @@ -48,9 +48,6 @@ def _load(name: str): check_release_intent = _load("check_release_intent") check_release_consistency = _load("check_release_consistency") -# Any subprocess in this module that would fork pytest fails; see conftest.py. -pytestmark = pytest.mark.usefixtures("no_subprocess_fork") - # These tests start thousands of real git processes, many of them from the # release scripts under test. Each git call gets no terminal input, no editor, diff --git a/packages/desktop/tests/test_wheel_layout.py b/packages/desktop/tests/test_wheel_layout.py index 869818367c..cababd1fc5 100644 --- a/packages/desktop/tests/test_wheel_layout.py +++ b/packages/desktop/tests/test_wheel_layout.py @@ -39,8 +39,9 @@ def built_wheel(tmp_path_factory: pytest.TempPathFactory) -> Path: pytest.skip("uv is required to build the wheel") out_dir = tmp_path_factory.mktemp("wheel") subprocess.run( - [uv, "build", "--wheel", "--out-dir", str(out_dir)], - cwd=ROOT, + # The project is named as an argument, not through cwd, so Python can + # start uv without forking pytest (see conftest.py). + [uv, "build", "--wheel", "--out-dir", str(out_dir), str(ROOT)], check=True, capture_output=True, text=True, @@ -57,9 +58,7 @@ def test_wheel_installs_only_the_namespaced_package(built_wheel: Path) -> None: assert top_level == {IMPORT_PACKAGE, f"openadapt_desktop-{_version()}.dist-info"} -def test_console_script_runs_from_the_installed_wheel( - built_wheel: Path, tmp_path: Path -) -> None: +def test_console_script_runs_from_the_installed_wheel(built_wheel: Path, tmp_path: Path) -> None: with zipfile.ZipFile(built_wheel) as wheel: entry_points = next( wheel.read(name).decode("utf-8") @@ -69,20 +68,19 @@ def test_console_script_runs_from_the_installed_wheel( site = tmp_path / "site-packages" wheel.extractall(site) - scripts = dict( - line.split(" = ", 1) - for line in entry_points.splitlines() - if " = " in line - ) + scripts = dict(line.split(" = ", 1) for line in entry_points.splitlines() if " = " in line) assert scripts == {"openadapt-desktop": f"{IMPORT_PACKAGE}.cli:main"} module, function = scripts["openadapt-desktop"].split(":") # Put the extracted wheel first so the run proves the installed files work, - # not the editable checkout. ``-I`` keeps PYTHONPATH and the cwd out. + # not the editable checkout. ``-I`` keeps PYTHONPATH and the cwd out. The + # probe changes directory itself, because passing cwd would make Python + # fork pytest to start it (see conftest.py). probe = textwrap.dedent( f""" - import importlib, sys + import importlib, os, sys site = sys.argv[1] + os.chdir(os.path.dirname(site)) sys.path.insert(0, site) module = importlib.import_module({module!r}) assert module.__file__.startswith(site), module.__file__ @@ -92,7 +90,6 @@ def test_console_script_runs_from_the_installed_wheel( ) result = subprocess.run( [sys.executable, "-I", "-c", probe, str(site)], - cwd=tmp_path, capture_output=True, text=True, timeout=120,