diff --git a/docs/TESTING.md b/docs/TESTING.md index a575d93d66..cd09260a60 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -227,7 +227,7 @@ Every new test follows these rules. Some of them name a path, fixture or check t ### Floor and ratchets -- Every test runs inside the hermetic floor, which the root conftest supplies: the network block, which also refuses a loopback connect to a port no socket in the test process binds and fails the test that made it, even when the code under test swallowed the refusal; the host path guard in `tests/conftest.py`, which fails a test that opens a file outside the checkout, the run's temporary directory and the interpreter. `tests/support/host_paths.py` holds the allowed roots. For a linked worktree it adds the common git directory. So a test in a worktree outside its main checkout can read the `HEAD` file of its own git directory. Such a worktree is the replay tree of `devops ci fail-to-pass` or the worktree of a runner. `tests/invariants/test_host_path_roots.py` holds the roots; the refusal to start a real gh or security scanner; the test's own data directory, config and gh config, with no way onto the session bus; a pinned GitHub identity, so a gh or git child gets a placeholder token, never the developer's login; a throwaway kubeconfig for the run; the config write guard, which fails a test when it opens a config file for writing, renames a file onto one or removes one outside the run's temporary directory, and names the test and the stack; the spend ledger write guard, which fails a test when it writes to the spend ledger outside the run's temporary directory; and the workspace tripwire, which fails the run when a test writes to the workspace's `config.yaml` or to a tracked file. +- Every test runs inside the hermetic floor, which the root conftest supplies: the network block, which also refuses a loopback connect to a port no socket in the test process binds and fails the test that made it, even when the code under test swallowed the refusal; the host path guard in `tests/conftest.py`, which fails a test that opens a file outside the checkout, the run's temporary directory and the interpreter. `tests/support/host_paths.py` holds the allowed roots. For a linked worktree it adds the common git directory. So a test in a worktree outside its main checkout can read the `HEAD` file of its own git directory. Such a worktree is the replay tree of `devops ci fail-to-pass` or the worktree of a runner. `tests/invariants/test_host_path_roots.py` holds the roots; the refusal to start a real gh or security scanner; the test's own data directory, config and gh config, with no way onto the session bus; a pinned GitHub identity, so a gh or git child gets a placeholder token, never the developer's login; a throwaway kubeconfig for the run; the config write guard, which fails a test when it opens a config file for writing, renames a file onto one or removes one outside the run's temporary directory, and names the test and the stack; the spend ledger write guard, which fails a test when it writes to the spend ledger outside the run's temporary directory; the home write guard, which fails a test when it opens a file for writing, renames a file onto one or removes one under the real home, the HOME that the floor replaces, outside the run's temporary directory, the checkout and the interpreter, and names the test and the stack; the refusal of a support helper to write outside the run's temporary directory, or at all outside a pytest run; and the workspace tripwire, which fails the run when a test writes to the workspace's `config.yaml` or to a tracked file. - The floor fails a test that reaches a faked edge without its fake, with an error naming the edge. - A test that checks a service that is down refuses it through `refusing_port`, a loopback port the test binds and never listens on, so the kernel refuses each connect as a stopped service would, and the service's retry waits return at once, as [Clock](#clock) says. A test that needs a service's answers fakes it at its edge, such as the model through `model_fake`. - After every test, the floor calls the public reset of every process-wide cache and singleton, and an invariant test fails a module-level cache or `global` in `src/devops_cli` that has no reset there. @@ -240,7 +240,7 @@ Every new test follows these rules. Some of them name a path, fixture or check t The suite moves to these conventions package by package ([ADR 0007](adr/0007-tests-double-only-process-edges.md)). Until the move is done: -- **Exists today**: the network block, with its failure of a test that connects to a loopback port or `AF_UNIX` socket the test process does not bind or looks up an external DNS name, the `refusing_port` double and the side-channel port; the floor's default deny of processes (with real child processes staying only in the process runner's contract suite) and of the keyring and D-Bus (a deny edge that the keyring seam `devops_cli.config.os_keyring` takes before each test, and `_DenyKeyring`, which the `keyring` library takes before the first test for third-party code, such as fastmcp's key-value store, that calls the library itself); the reset of every piece of process-wide state in `src/devops_cli` after each test, guarded by an invariant test; the wait for the dispatch workers that a timeout abandoned, in `finish_abandoned_dispatch_workers`; telemetry export off by default unless a test opts in through `config` or the OTLP fake; the OTLP fake, `FakeCollector` in `tests/support/fakes/otlp.py` behind its `otlp` fixture, which `install_exporter` makes the exporter of every tracer `get_tracer()` builds, with export on, until `remove_exporter`, and which reads back exported spans, metric data points and log records as plain values, from OTLP/JSON requests and from the OTLP protobuf trace requests of library spans, with its contract suite, `tests/telemetry/test_otlp_exporter_contract.py`, which runs each case through a telemetry client over the fake and over `HttpOtlpExporter`, which posts to a loopback OTLP/HTTP receiver or to `refusing_port`; the `cli` and `config` fixtures; the refusal to start a real gh or security scanner, by the names `tests/support/refused_programs.py` reads from the scanner registry; each test's own data directory, config and gh config, with no way onto the session bus; the pinned GitHub identity; one throwaway kubeconfig for the whole run; the config write guard, a PEP 578 audit hook in the test process in `tests/support/config_write_guard.py`, which refuses a write of a file named like a devops-cli config file, such as `config.yaml` or its copy `config.yaml.bak-`, outside the run's temporary directory, also when the code under test catches the refusal; the spend ledger write guard, a PEP 578 audit hook in `tests/support/spend_write_guard.py`, which refuses an open, modification or SQLite write to a spend ledger database outside the run's temporary directory; the workspace tripwire, in `tests/support/workspace_tripwire.py`; `tests/support/` with `paths.py`, `waits.py`, the builders in `builders.py`, the `fakes/` package, the pinned identity's `github_identity.py`, and the registration of its modules through `bootstrap.py`, the root conftest's one `pytest_plugins` entry, with the checks that hold a helper's top level and class bodies to statements that bind names, that keep a module from holding `tests.support` or a package under it, and that fail a run on a support fixture or hook its source does not show or on a test module or conftest under `tests/support/`; the check, in the full gate, against reading `__file__` outside `tests/support/` and importing a test module or a conftest; the GitHub session's fake, `GitHubApiFake` in `tests/support/fakes/github.py` behind its `github_api` fixture, which refuses any gh command the rate limiter would run (`run_gh` and the quota refresh), with its contract suite, `tests/github/test_github_contract.py`, which runs each case through the session over the fake and over GitHub's recorded answers; the `github_api_and_gh` fixture, which serves the session over that fake and sends the gh commands of the rate limiter to `process_fake`, for code that reads GitHub both ways, such as merge readiness; the `gh_edge` fixture of `tests/support/gh_process.py`, which records a fresh quota in the rate limiter and returns `process_fake`, so a command test scripts each gh answer (`answer_gh` for a prefix, `script_gh` for answers in order, `mentions` for a GraphQL query by name), the origin remote (`answer_origin`) and reads back the gh commands (`gh_argv`), and `ProjectGitHub.install` in `tests/support/project_reconcile_fake.py`, which serves a project board on `process_fake` and `github_api`; the Kubernetes API's fake, `FakeCluster` in `tests/support/fakes/kubernetes.py` behind its `cluster` fixture, which `KubernetesService.install` makes the source of the process's service (`k8s/api.py`) over fake `CoreV1Api`, `CustomObjectsApi` and `VersionApi` objects, with its contract suite, `tests/k8s/test_kubernetes_contract.py`, which runs each case through the service over the fake and over the real client, whose kubeconfig under `tmp_path` points at a loopback server that replays the API responses in `tests/fixtures/kubernetes/`; a test makes one API method fail with `cluster.core.fail(method, error)` or `cluster.custom_objects.fail(method, error)`, which raises `error` on each later call of `method`, as the API server's refusal does; the Docker engine's fake, `DockerEngineFake` in `tests/support/fakes/docker_engine.py` behind its `docker_daemon` fixture, with its contract suite, `tests/docker/test_engine_contract.py` (Docker engine, below); the security scanners' fake, `ScannerFake` in `tests/support/fakes/scanners.py` behind its `scanner_fake` fixture, a `ToolExecutorFake` that answers Semgrep, Gitleaks, Bandit and osv-scanner with their recorded runs, with its contract suite, `tests/security/test_scanner_contract.py`, which holds each recording to its adapter's command and the tools lock's version; the git fake, `GitFake` in `tests/support/fakes/git.py` behind its `git_fake` fixture, which answers `git` from the transcripts of `tests/fixtures/git/` and refuses a real git for the rest of the test, with its contract suite, `tests/core/test_git_contract.py`, which replays each transcript over the code of `src/` with `ProcessFake` and with `GitFake` and starts no program, and the `git` row of `devops ci`, which records the transcripts again with the real git (`tests/support/git_recording.py`); the MCP dispatcher's fake, `DispatcherFake` in `tests/support/fakes/mcp_dispatcher.py` behind its `mcp_dispatcher` fixture, which `install_mcp_dispatcher` (`devops_cli.ai.mcp.dispatcher`) makes the dispatcher of every MCP tool until `reset_mcp_dispatcher`, which the floor calls after each test. An MCP tool hands one `devops` argv to the CLI, and the real dispatcher runs the Typer app in the same process, so no process starts and the process fake never sees the argv. The fake records each call as a `DispatchCall` in `calls` (`last`, `call_count`), answers by the arguments after `devops` (`answer`, `time_out`, `fail`), and refuses an argv that is not a `devops` one, as the real dispatcher does. Its contract suite, `tests/ai/mcp/test_dispatcher_contract.py`, runs each case over the fake and over `InProcessDispatcher`; the OpenSpec fake, `OpenSpecFake` in `tests/support/fakes/openspec.py` behind its `openspec_fake` fixture, which answers `openspec` with the pinned tool's recorded runs over the scenarios of `tests/support/openspec_scenarios.py` (`tests/support/openspec_recording.py` records them again) and fails a command the record lacks, with its contract suite, `tests/tools_lock/test_openspec_contract.py`, which holds the record to the tools lock's version and to the commands the gate starts; the roadmap store's fake, `InMemoryRoadmapStore` in `tests/support/fakes/roadmap_store.py` behind the `roadmap_store` fixture, which every test that drives a roadmap command uses and which installs the fake through `install_roadmap_store` (`devops_cli.roadmap.stores.store`) until `reset_roadmap_store`, which the floor calls after each test, so `get_roadmap_store` returns the fake and, without the fixture, opens the GitHub store, whose `gh` the floor refuses, with its contract suite, `tests/roadmap/stores/test_roadmap_store_contract.py`, which runs each case over the fake and over `GitHubRoadmapStore` on the `gh` fake, and with its fault mode: `fail_write` makes one write fail with a 502 or with an error the test gives, before or after it applies, `fail_listing` makes the next directory listing fail, `fail_read` makes the reads of the repository's visibility or of its changes fail, and `reads` names each read of an Item and of a path's last change; `GitHubFake` in `tests/support/fakes/github_repository.py` is the same repository at the `gh` process edge, which `GitHubFake.install` hangs on `process_fake` or `git_fake`; the keyring's fake, `FakeKeyring` in `tests/support/fakes/keyring.py` behind its `keyring_store` fixture, which the fixture installs through the keyring seam, with its contract suite, `tests/config/test_keyring_contract.py`, which runs the session-bus and lock checks over the fake and over `SystemKeyring`, and the entry cases over the fake alone, since a real Secret Service needs gnome-keyring-daemon on a session bus; the in-memory Valkey server behind the `valkey_server` and `valkey_client` fixtures in `tests/support/fakes/valkey.py`, which a `ValkeyClient` reaches through its `connection_pool` parameter, so a test of what the client's own `password`, `db` and decoding arguments send and read binds a loopback listener that records the commands instead, and which has no contract suite yet, since no recorded exchange or local tool stands in for a Valkey server; the HTTP seam's fake, `WebFake` in `tests/support/fakes/http.py` behind its `web` fixture, which `install_transport` (`devops_cli.http.entry`) makes the transport of every client that the entry point builds, pooled or not, until `remove_transport`, and which closes the pooled clients on each swap. It answers by method and URL (`answer`, `page`, `redirect`, `respond`, `serve`), raises httpx2's connect and read-timeout errors (`refuse`, `time_out`), vets each request's host at the client's egress level with `vet_addresses`, and keeps each request that reached it as one `RecordedRequest` in `recorded`. Its contract suite, `tests/http/test_entry_contract.py`, runs each case through a sync and an async client over the fake and over the real egress transport, whose peer is a loopback server that the test owns (status, headers and body; JSON; redirects and their limit; a refused connection; a read timeout; a destination that SSRF validation refuses, before any request). A host that is a name needs a DNS answer, so the `web` fixture requests `dns` and answers every name with one public address; a test that needs another answer calls `dns.add` or `dns.script`. `serve_llm` in `tests/support/llm_stream_fakes.py` serves the replies of a model on the fake and returns the model calls it received, for the tests of `LLMClient`; its `/model/info` query gets an empty list. The dial of httpcore2, one layer below the pool, is faked by `record_connects` and `http_response` in `tests/support/fakes/dial.py`, for the tests of the egress policy, which runs at the connect; the TCP probe of a host and port, which code makes with `socket.create_connection` and which no seam reaches, answered by the `tcp_probe` fixture in `tests/support/tcp_probe.py` (the stdlib fallback for an edge with no seam): it refuses each probe until a test makes an address listen, and records each probe; Hypothesis; syrupy, whose snapshots are the fail-to-pass replay's could-not-run reports in `tests/ci/__snapshots__/test_fail_to_pass.ambr` and the tool listing of the MCP server (name, description and input schema of each tool) in `tests/ai/mcp/__snapshots__/test_mcp_tool_listing/`, which `tests/ai/mcp/test_mcp_tool_listing.py` compares, so a change to a tool shows as a reviewed diff (update it with `--snapshot-update`); the coverage gates; the structural startup budget; the ast-grep rule against an upper bound on elapsed wall-clock time in `tests/`; and the suppression-ceiling and swallowed-failures ratchets. +- **Exists today**: the network block, with its failure of a test that connects to a loopback port or `AF_UNIX` socket the test process does not bind or looks up an external DNS name, the `refusing_port` double and the side-channel port; the floor's default deny of processes (with real child processes staying only in the process runner's contract suite) and of the keyring and D-Bus (a deny edge that the keyring seam `devops_cli.config.os_keyring` takes before each test, and `_DenyKeyring`, which the `keyring` library takes before the first test for third-party code, such as fastmcp's key-value store, that calls the library itself); the reset of every piece of process-wide state in `src/devops_cli` after each test, guarded by an invariant test; the wait for the dispatch workers that a timeout abandoned, in `finish_abandoned_dispatch_workers`; telemetry export off by default unless a test opts in through `config` or the OTLP fake; the OTLP fake, `FakeCollector` in `tests/support/fakes/otlp.py` behind its `otlp` fixture, which `install_exporter` makes the exporter of every tracer `get_tracer()` builds, with export on, until `remove_exporter`, and which reads back exported spans, metric data points and log records as plain values, from OTLP/JSON requests and from the OTLP protobuf trace requests of library spans, with its contract suite, `tests/telemetry/test_otlp_exporter_contract.py`, which runs each case through a telemetry client over the fake and over `HttpOtlpExporter`, which posts to a loopback OTLP/HTTP receiver or to `refusing_port`; the `cli` and `config` fixtures; the refusal to start a real gh or security scanner, by the names `tests/support/refused_programs.py` reads from the scanner registry; each test's own data directory, config and gh config, with no way onto the session bus; the pinned GitHub identity; one throwaway kubeconfig for the whole run; the config write guard, a PEP 578 audit hook in the test process in `tests/support/config_write_guard.py`, which refuses a write of a file named like a devops-cli config file, such as `config.yaml` or its copy `config.yaml.bak-`, outside the run's temporary directory, also when the code under test catches the refusal; the spend ledger write guard, a PEP 578 audit hook in `tests/support/spend_write_guard.py`, which refuses an open, modification or SQLite write to a spend ledger database outside the run's temporary directory; the home write guard, a PEP 578 audit hook in `tests/support/home_write_guard.py`, which refuses, while a test runs, an open for writing, a rename onto and a removal of a file under the real home outside the run's temporary directory, the checkout and the interpreter, also when the code under test catches the refusal. `isolate_home` in `tests/support/bootstrap.py` records the real home, and the controller hands it to each xdist worker, which inherits the isolated HOME. The three write guards read the audit events that change a file from `tests/support/file_changes.py`. A support helper that writes to a path that it does not get from its caller, such as a path that devops-cli resolves, calls `hold_to_the_run` of the same module before the write. It refuses a path outside the run's temporary directory, and each path when no pytest run is active in the process, because outside pytest no floor isolates HOME. `link_at_pin` in `tests/support/tools.py` and the `global_config` fixture call it. A helper runs only through pytest; the workspace tripwire, in `tests/support/workspace_tripwire.py`; `tests/support/` with `paths.py`, `waits.py`, the builders in `builders.py`, the `fakes/` package, the pinned identity's `github_identity.py`, and the registration of its modules through `bootstrap.py`, the root conftest's one `pytest_plugins` entry, with the checks that hold a helper's top level and class bodies to statements that bind names, that keep a module from holding `tests.support` or a package under it, and that fail a run on a support fixture or hook its source does not show or on a test module or conftest under `tests/support/`; the check, in the full gate, against reading `__file__` outside `tests/support/` and importing a test module or a conftest; the GitHub session's fake, `GitHubApiFake` in `tests/support/fakes/github.py` behind its `github_api` fixture, which refuses any gh command the rate limiter would run (`run_gh` and the quota refresh), with its contract suite, `tests/github/test_github_contract.py`, which runs each case through the session over the fake and over GitHub's recorded answers; the `github_api_and_gh` fixture, which serves the session over that fake and sends the gh commands of the rate limiter to `process_fake`, for code that reads GitHub both ways, such as merge readiness; the `gh_edge` fixture of `tests/support/gh_process.py`, which records a fresh quota in the rate limiter and returns `process_fake`, so a command test scripts each gh answer (`answer_gh` for a prefix, `script_gh` for answers in order, `mentions` for a GraphQL query by name), the origin remote (`answer_origin`) and reads back the gh commands (`gh_argv`), and `ProjectGitHub.install` in `tests/support/project_reconcile_fake.py`, which serves a project board on `process_fake` and `github_api`; the Kubernetes API's fake, `FakeCluster` in `tests/support/fakes/kubernetes.py` behind its `cluster` fixture, which `KubernetesService.install` makes the source of the process's service (`k8s/api.py`) over fake `CoreV1Api`, `CustomObjectsApi` and `VersionApi` objects, with its contract suite, `tests/k8s/test_kubernetes_contract.py`, which runs each case through the service over the fake and over the real client, whose kubeconfig under `tmp_path` points at a loopback server that replays the API responses in `tests/fixtures/kubernetes/`; a test makes one API method fail with `cluster.core.fail(method, error)` or `cluster.custom_objects.fail(method, error)`, which raises `error` on each later call of `method`, as the API server's refusal does; the Docker engine's fake, `DockerEngineFake` in `tests/support/fakes/docker_engine.py` behind its `docker_daemon` fixture, with its contract suite, `tests/docker/test_engine_contract.py` (Docker engine, below); the security scanners' fake, `ScannerFake` in `tests/support/fakes/scanners.py` behind its `scanner_fake` fixture, a `ToolExecutorFake` that answers Semgrep, Gitleaks, Bandit and osv-scanner with their recorded runs, with its contract suite, `tests/security/test_scanner_contract.py`, which holds each recording to its adapter's command and the tools lock's version; the git fake, `GitFake` in `tests/support/fakes/git.py` behind its `git_fake` fixture, which answers `git` from the transcripts of `tests/fixtures/git/` and refuses a real git for the rest of the test, with its contract suite, `tests/core/test_git_contract.py`, which replays each transcript over the code of `src/` with `ProcessFake` and with `GitFake` and starts no program, and the `git` row of `devops ci`, which records the transcripts again with the real git (`tests/support/git_recording.py`); the MCP dispatcher's fake, `DispatcherFake` in `tests/support/fakes/mcp_dispatcher.py` behind its `mcp_dispatcher` fixture, which `install_mcp_dispatcher` (`devops_cli.ai.mcp.dispatcher`) makes the dispatcher of every MCP tool until `reset_mcp_dispatcher`, which the floor calls after each test. An MCP tool hands one `devops` argv to the CLI, and the real dispatcher runs the Typer app in the same process, so no process starts and the process fake never sees the argv. The fake records each call as a `DispatchCall` in `calls` (`last`, `call_count`), answers by the arguments after `devops` (`answer`, `time_out`, `fail`), and refuses an argv that is not a `devops` one, as the real dispatcher does. Its contract suite, `tests/ai/mcp/test_dispatcher_contract.py`, runs each case over the fake and over `InProcessDispatcher`; the OpenSpec fake, `OpenSpecFake` in `tests/support/fakes/openspec.py` behind its `openspec_fake` fixture, which answers `openspec` with the pinned tool's recorded runs over the scenarios of `tests/support/openspec_scenarios.py` (`tests/support/openspec_recording.py` records them again) and fails a command the record lacks, with its contract suite, `tests/tools_lock/test_openspec_contract.py`, which holds the record to the tools lock's version and to the commands the gate starts; the roadmap store's fake, `InMemoryRoadmapStore` in `tests/support/fakes/roadmap_store.py` behind the `roadmap_store` fixture, which every test that drives a roadmap command uses and which installs the fake through `install_roadmap_store` (`devops_cli.roadmap.stores.store`) until `reset_roadmap_store`, which the floor calls after each test, so `get_roadmap_store` returns the fake and, without the fixture, opens the GitHub store, whose `gh` the floor refuses, with its contract suite, `tests/roadmap/stores/test_roadmap_store_contract.py`, which runs each case over the fake and over `GitHubRoadmapStore` on the `gh` fake, and with its fault mode: `fail_write` makes one write fail with a 502 or with an error the test gives, before or after it applies, `fail_listing` makes the next directory listing fail, `fail_read` makes the reads of the repository's visibility or of its changes fail, and `reads` names each read of an Item and of a path's last change; `GitHubFake` in `tests/support/fakes/github_repository.py` is the same repository at the `gh` process edge, which `GitHubFake.install` hangs on `process_fake` or `git_fake`; the keyring's fake, `FakeKeyring` in `tests/support/fakes/keyring.py` behind its `keyring_store` fixture, which the fixture installs through the keyring seam, with its contract suite, `tests/config/test_keyring_contract.py`, which runs the session-bus and lock checks over the fake and over `SystemKeyring`, and the entry cases over the fake alone, since a real Secret Service needs gnome-keyring-daemon on a session bus; the in-memory Valkey server behind the `valkey_server` and `valkey_client` fixtures in `tests/support/fakes/valkey.py`, which a `ValkeyClient` reaches through its `connection_pool` parameter, so a test of what the client's own `password`, `db` and decoding arguments send and read binds a loopback listener that records the commands instead, and which has no contract suite yet, since no recorded exchange or local tool stands in for a Valkey server; the HTTP seam's fake, `WebFake` in `tests/support/fakes/http.py` behind its `web` fixture, which `install_transport` (`devops_cli.http.entry`) makes the transport of every client that the entry point builds, pooled or not, until `remove_transport`, and which closes the pooled clients on each swap. It answers by method and URL (`answer`, `page`, `redirect`, `respond`, `serve`), raises httpx2's connect and read-timeout errors (`refuse`, `time_out`), vets each request's host at the client's egress level with `vet_addresses`, and keeps each request that reached it as one `RecordedRequest` in `recorded`. Its contract suite, `tests/http/test_entry_contract.py`, runs each case through a sync and an async client over the fake and over the real egress transport, whose peer is a loopback server that the test owns (status, headers and body; JSON; redirects and their limit; a refused connection; a read timeout; a destination that SSRF validation refuses, before any request). A host that is a name needs a DNS answer, so the `web` fixture requests `dns` and answers every name with one public address; a test that needs another answer calls `dns.add` or `dns.script`. `serve_llm` in `tests/support/llm_stream_fakes.py` serves the replies of a model on the fake and returns the model calls it received, for the tests of `LLMClient`; its `/model/info` query gets an empty list. The dial of httpcore2, one layer below the pool, is faked by `record_connects` and `http_response` in `tests/support/fakes/dial.py`, for the tests of the egress policy, which runs at the connect; the TCP probe of a host and port, which code makes with `socket.create_connection` and which no seam reaches, answered by the `tcp_probe` fixture in `tests/support/tcp_probe.py` (the stdlib fallback for an edge with no seam): it refuses each probe until a test makes an address listen, and records each probe; Hypothesis; syrupy, whose snapshots are the fail-to-pass replay's could-not-run reports in `tests/ci/__snapshots__/test_fail_to_pass.ambr` and the tool listing of the MCP server (name, description and input schema of each tool) in `tests/ai/mcp/__snapshots__/test_mcp_tool_listing/`, which `tests/ai/mcp/test_mcp_tool_listing.py` compares, so a change to a tool shows as a reviewed diff (update it with `--snapshot-update`); the coverage gates; the structural startup budget; the ast-grep rule against an upper bound on elapsed wall-clock time in `tests/`; and the suppression-ceiling and swallowed-failures ratchets. - **Review tools**: `ToolExecutor` in `src/devops_cli/security/tool_executor.py` is the seam of the review-tool edge, and `ToolExecutorFake` in `tests/support/fakes/tool_executor.py` is its fake, behind the `tool_executor_fake` fixture. A test scripts a tool with `ToolAnswer` (version, binary digest, exit code, output, `timed_out`) and reads the requests back from `requests`. `answer_with(tool, responder)` answers each run of a tool with what the responder gives for its request, for a tool whose output depends on its arguments and its files, and `fail(tool, error)` raises the error from each run, as an executor that cannot start the tool raises. A timed-out answer carries `CONST_SANDBOX_TIMEOUT_EXIT_CODE`. On `ScannerFake`, both put a stand-in for the tool first on PATH, as `script` does. No scanner looks for a patched `run_subprocess`, `check_binary` or `is_dry_run`: a test that needs a scanner missing gives it a PATH without the program, and a test of dry-run mode calls `set_dry_run`. The fake builds the rest of each `ToolRun` with the `record_tool_run` that the real executor calls. - **Review tools, programs and canaries**: a request for a tool that the PATH does not name, such as mypy from the interpreter of a `.venv`, names that interpreter as its `program`, and the fake answers it as it answers the tool. Mypy and the canary of each tool take a `tool_executor`, and a review gives them its own. `ScannerFake` answers each canary run, in a working directory named with `CONST_CANARY_WORKDIR_PREFIX`, with the output in `tests/fixtures/review_canary/recorded_outputs.json`, and keeps it in `canaries.requests`, apart from the runs of the scans. A test that builds an orchestrator gives it `scanner_fake` through the constructor (`tool_executor=scanner_fake`), and a test that starts a review through a command asks for `scanner_fake`, so no review starts a real tool for its canaries. The root conftest does not wrap `DirectToolExecutor.run` or `SandboxToolExecutor.run`. - **Review tools, records**: the fake names itself `fake` in the record (`FAKE_EXECUTOR`). A review wraps its executor in a `RecordingToolExecutor`. A test that gives the orchestrator the fake reads the records from `orchestrator.tool_executor.runs`, from `profile.tool_runs` and from the Tool Runs table of the report. The settle of the fake does nothing, as the settle of a real executor does. A test that reads how a run ended, its `exit_code` and `success`, wraps the fake in a `RecordingToolExecutor`. diff --git a/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/.openspec.yaml b/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/.openspec.yaml new file mode 100644 index 0000000000..b3286d52ce --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/.openspec.yaml @@ -0,0 +1,3 @@ +schema: spec-driven +created: 2026-11-11 +skip_specs: true diff --git a/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/design.md b/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/design.md new file mode 100644 index 0000000000..aaf212a095 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/design.md @@ -0,0 +1,22 @@ +# Design + +## Decisions + +- **The real home is the `HOME` that `isolate_home` replaces.** `isolate_home` keeps it in the stash of the config. The controller adds it to the `workerinput` of each xdist worker in `pytest_configure_node`, and a worker reads it from there, because the worker inherits the isolated `HOME` of the controller. A pytester run in the same process records the `HOME` that its test sets, so a test can put the real home of the inner run in its own temporary directory. +- **The guard keeps three roots writable under the real home:** the run's temporary directory, the checkout with its common git directory (`checkout_roots` of `tests/support/host_paths.py`), and the interpreter (`sys.prefix`, `sys.base_prefix`, `sys.exec_prefix`, `sys.base_exec_prefix` and `sys.pycache_prefix` when it is set). Python writes bytecode caches into the interpreter, and a GitHub-hosted runner has the checkout in its home. The workspace tripwire checks the checkout. +- **The guard checks only while a test of the run runs**, from the start of its setup to the end of its teardown (a `pytest_runtest_protocol` wrapper). The issue asks the floor to fail a test. Outside a test, pytest itself writes into the root directory of the run. For a run that pytester starts, that directory is the `HOME` that pytester sets, so it is the real home of the inner run. A first version that checked all the time refused, in each pytester run of `tests/invariants/test_hermetic_floor.py`, the bytecode of the inner test module (`__pycache__/test_inner.cpython-314-pytest-9.1.1.pyc`) and the cache of the inner run (`pytest-cache-files-*/README.md`). +- **`_run_with_floor` gives the inner run the real home `pytester.path / "real-home"`.** The guard tests of the floor put their files outside the inner run under `pytester.path`, which pytester makes the `HOME`. With a real home of its own, such a file lies outside both the inner run and its real home. +- **The hook calls no function that a test can replace.** It compares the written path, made absolute and normalized with no file system call (`os.path.normpath`, and `os.getcwd` as the module took it at import), with the given and the resolved form of each root. A first version resolved the written path with `os.path.realpath`, which calls `os.lstat`. Three worktree tests replace `os.lstat` with a function that removes a file, so the removal started the hook again until the recursion limit (`tests/git/test_repos_worktrees.py`, `tests/git/test_repos_worktrees_reclaim.py`). The hook does not follow a symbolic link in the written path. +- **The guard refuses the same three events as the config write guard:** an open for writing, a rename onto a path and a removal. A path relative to a directory descriptor is not checked, as in the other two guards. +- **`hold_to_the_run` reads the run that the guard records at `pytest_configure`.** No run in the process means no pytest run, so the helper refuses. The refusal is `pytest.fail`, which an `except Exception` in a calling script does not hide. +- **One table of audit events.** `tests/support/file_changes.py` holds the events and the function that gets the changed path from an event. It is in `tests/`, not in `src/`: the fail-to-pass replay runs this `tests/` on the base's source, which lacks a name that the change adds to `src/`. + +## Rejected alternatives + +- **The home from the user database (`pwd.getpwuid(os.getuid()).pw_dir`).** It gives the same home in each worker with no transfer. But a test cannot put the real home of an inner run in its temporary directory without a patch of the user database. Also, the issue defines the real home as the `HOME` before `isolate_home`. +- **The `HOME` of each worker before `isolate_home`.** A worker inherits the isolated `HOME` of the controller (`isolate_home` sets `os.environ["HOME"]` at `pytest_configure`, and xdist starts the workers at session start). That home is in the run, so the guard would keep nothing. +- **An environment variable that carries the real home to the workers.** Each child process of a test would inherit it, and a test that clears the environment would lose it. +- **`PYTEST_VERSION` as the sign of a pytest run.** pytest sets it in `os.environ`, so a child process of a test inherits it, also when no floor runs in that child. The new test runs the helper in such a child process. +- **A refusal when `tests.support` is imported outside pytest.** `devops ci` runs `tests.support.git_recording` and `tests.support.check_test_settings` from plain Python (`src/devops_cli/commands/ci.py`, the `git` and `test-settings` rows). +- **The root directory of the run (`config.rootpath`) as a fourth writable root.** pytester makes its folder both the root directory and the `HOME` of the inner run, so the guard would keep nothing in a pytester run. +- **A third copy of the audit event table in the new guard.** The config write guard and the spend ledger write guard each held a copy. One module now holds it. diff --git a/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/proposal.md b/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/proposal.md new file mode 100644 index 0000000000..3abdbc4743 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/proposal.md @@ -0,0 +1,48 @@ +# Proposal: #4739 + +## Why + +Issue #4739: a helper of `tests/support/` wrote into the real home of a developer. An agent called `link_at_pin` from plain Python, outside pytest. No conftest ran, so the floor did not isolate `HOME` or the user data root. The helper got each path from devops-cli, which put it under `~/.local/share/devops-cli/tools/`, and wrote the stub `#!/bin/sh\necho mytool\n` over 18 real tools. The helper has no guard. Inside pytest, the two write guards of the floor refuse only config files and spend ledgers, and the host path guard sees only `open()`. No guard refuses another write under the real home. + +## What Changes + +- The new floor module `tests/support/home_write_guard.py` adds a PEP 578 audit hook, in the form of the config write guard. While a test runs, in its setup, call and teardown, it fails the test when the test opens a file for writing, renames a file onto one or removes one under the real home and outside the run's temporary directory, the checkout and the interpreter. The failure names the test, and the test also fails at teardown when the code under test catches the failure. `_run_with_floor` in `tests/invariants/test_hermetic_floor.py` gives each inner pytester run a real home of its own. +- `isolate_home` in `tests/support/bootstrap.py` records the real home, the `HOME` that it replaces. An xdist worker inherits the isolated `HOME` of the controller, so the controller gives its real home to each worker through `workerinput`. +- `hold_to_the_run` in the new module refuses a path outside the temporary directory of the pytest run in this process. When no pytest run is active in the process, it refuses each path. `link_at_pin` calls it for each path before it writes, and the write function of the `global_config` fixture calls it before it writes the global config file. +- The new module `tests/support/file_changes.py` holds the audit events that change a file. The config write guard, the spend ledger write guard and the home write guard read them from this one module. +- `docs/TESTING.md` names the home write guard and the rule for a support helper. +- The change alters no behavior a consumer observes. It changes only the test floor, its tests and a document. So it has no spec delta and sets `skip_specs: true`. +- The change fits one pull request. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +None. + +## Impact + +- Tests: a test that writes under the real home fails at the write and names itself. A support helper that is called from plain Python stops before it writes and tells why. +- Files: `tests/support/home_write_guard.py` (new), `tests/support/file_changes.py` (new), `tests/support/bootstrap.py`, `tests/support/tools.py`, `tests/support/config.py`, `tests/support/config_write_guard.py`, `tests/support/spend_write_guard.py`, `tests/invariants/test_hermetic_floor.py`, `docs/TESTING.md`. +- No path under `src/` changes. + +## Feasibility + +- The cause is in the code at `origin/main` (`4b289804`). `link_at_pin` (`tests/support/tools.py`) gets each path from `installed_commands`, which puts it under `tool_dir`, which is `user_data_root() / "tools" / / ` (`src/devops_cli/tools_lock/__init__.py`). With no `DEVOPS_CLI_USER_DATA_ROOT`, `user_data_root()` returns `CONST_USER_DATA_ROOT`, which is `Path.home() / ".local" / "share" / "devops-cli"` (`src/devops_cli/core/repo.py`, `src/devops_cli/config/constants.py`). +- The census of the support helpers that write to a path that devops-cli resolves: `git grep -nE "user_data_root\(|Path\.home\(|expanduser\(|installed_commands\(|CONST_CONFIG_PATH\.(write|parent\.mkdir)" -- tests/support` prints 3 lines in 2 members: `link_at_pin` in `tests/support/tools.py`, a plain function, and the write function of the `global_config` fixture in `tests/support/config.py`. Both call `hold_to_the_run`. +- The floor has no guard for these writes. `config_write_guard.py` and `spend_write_guard.py` refuse a write only when the file name is a config file or a spend ledger. The host path guard in `tests/conftest.py` replaces `builtins.open` and `io.open` only, so `os.open`, `os.replace` and `os.remove` pass it, and its failure in another thread fails no test. +- pytest 9.1.1 and pytest-xdist 3.8.0 are in the lock. `isolate_home` sets `os.environ["HOME"]` at `pytest_configure`, and xdist starts its workers later, at session start, so a worker inherits the isolated `HOME`. In `xdist/workermanage.py`, `WorkerController.setup` builds `workerinput` (line 308), calls `pytest_configure_node` (line 342) and then sends `workerinput` to the worker (line 349). So a hook of the controller can add the real home to `workerinput`. +- The uv interpreter of the devcontainer is under the real home: `sys.base_prefix` is `/home/vscode/.local/share/uv/python/cpython-3.14.10-linux-x86_64-gnu`. Python writes its bytecode cache there. On a GitHub-hosted runner, the checkout is under `/home/runner/work/`, in the home of the runner. So the guard keeps the checkout and the interpreter writable. +- The reproduction of the issue was not run by hand: a support helper is called only through pytest. The new test runs the same call in a child process whose `HOME` is in the test's temporary directory. + +## Existing Tool Considered + +- PEP 578 audit hooks (`sys.addaudithook`, in the standard library since Python 3.8) report each `open`, `os.rename` and `os.remove` with its path. The config write guard and the spend ledger write guard use them. The home write guard uses them too. +- pytest's `Stash` keeps the real home on the config of the run, and the `pytest_configure_node` hook of pytest-xdist with `workerinput` carries it to each worker. +- pyfakefs replaces the file system of a test with a fake. It does not refuse a real write, it would change every test of the suite, and it does not run outside pytest. No maintained pytest plugin fails a test on a write by its path. +- The code to build is small: about 120,000 tokens to build, about 5,000 tokens a year to keep and fix, and about 2 hours of elapsed time. +- The change deletes the two copies of the audit event table and of `_changed_path` in `tests/support/config_write_guard.py` and `tests/support/spend_write_guard.py`. diff --git a/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/tasks.md b/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/tasks.md new file mode 100644 index 0000000000..7fc0073a01 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4739-test-helpers-write-to-the-real/tasks.md @@ -0,0 +1,29 @@ +# Tasks + +## 1. The floor fails a test that writes under the real home + +Kind: behavior. Changes: `tests/invariants/test_hermetic_floor.py`, `tests/support/bootstrap.py`, `tests/support/home_write_guard.py`, `tests/support/file_changes.py`, `tests/support/config_write_guard.py`, `tests/support/spend_write_guard.py`. + +- [x] 1.1 Write a failing test: in a pytester run whose real home is in the test's temporary directory, a test that opens a file for writing, opens a descriptor for writing, renames a file onto one or removes one under that home fails and is named, also when it catches the failure. A read under the home, and a write under `tmp_path`, under the isolated `HOME` and outside the home pass. No file under the home changes. + - Verification: `$ uv run devops ci test tests/invariants/test_hermetic_floor.py` +- [x] 1.2 Record the real home in `isolate_home` and give it to each xdist worker. Add the home write guard. Move the audit event table into `tests/support/file_changes.py` and read it in the three guards. + - Verification: `$ uv run devops ci test tests/invariants/test_hermetic_floor.py tests/config/test_isolation_tripwire.py` + +- [x] 1.3 Write a failing test: in a pytester run, a test that replaces `os.lstat` with a function that removes a file passes, and the function runs once. Then compare the written path with no file system call in the hook. + - Verification: `$ uv run devops ci test tests/invariants/test_hermetic_floor.py tests/git/test_repos_worktrees.py tests/git/test_repos_worktrees_reclaim.py` + +## 2. A support helper writes only inside a pytest run + +Kind: behavior. Changes: `tests/invariants/test_hermetic_floor.py`, `tests/support/home_write_guard.py`, `tests/support/tools.py`, `tests/support/config.py`. + +- [x] 2.1 Write failing tests: `link_at_pin`, called from plain Python with `HOME` in the test's temporary directory, exits with the refusal and writes nothing. In a pytester run, `link_at_pin` with a user data root outside the run's temporary directory refuses and writes nothing. + - Verification: `$ uv run devops ci test tests/invariants/test_hermetic_floor.py` +- [x] 2.2 Add `hold_to_the_run`, and call it in `link_at_pin` for each path and in the write function of `global_config` before each write. + - Verification: `$ uv run devops ci test tests/invariants/test_hermetic_floor.py tests/commands/test_install_tools.py tests/commands/test_devcontainer_install_tools_dry_run.py tests/config/test_setting_sources.py` + +## 3. Documents + +Kind: documents. Changes: `docs/TESTING.md`. + +- [x] 3.1 Name the home write guard and the rule for a support helper in the hermetic floor of `docs/TESTING.md`. + - Verification: `$ uv run devops ci docs` diff --git a/tests/invariants/test_hermetic_floor.py b/tests/invariants/test_hermetic_floor.py index fde847eabe..7f32451839 100644 --- a/tests/invariants/test_hermetic_floor.py +++ b/tests/invariants/test_hermetic_floor.py @@ -6,6 +6,8 @@ import ast import os import socket +import subprocess +import sys from collections.abc import Callable from pathlib import Path from typing import Any @@ -25,9 +27,13 @@ def _run_with_floor( monkeypatch: pytest.MonkeyPatch, source: str, ) -> pytest.RunResult: - """Run `source` inside `pytester` with the root conftest floor loaded in-process.""" - home = os.environ.get("HOME", str(pytester.path)) - monkeypatch.setenv("HOME", home) + """Run `source` inside `pytester` with the root conftest floor loaded in-process. The real + home of the inner run, the HOME that its floor replaces, is `pytester.path / "real-home"`. + pytester sets HOME to `pytester.path`, where the inner run writes its cache, so another + path under `pytester.path` lies outside both the inner run and its real home.""" + real_home = pytester.path / "real-home" + real_home.mkdir(exist_ok=True) + monkeypatch.setenv("HOME", str(real_home)) pytester.makepyfile(test_inner=source) return pytester.runpytest( "-p", @@ -558,6 +564,186 @@ def test_writes_another_db_outside(): assert named == failing +def test_a_write_under_the_real_home_fails_at_the_write_naming_the_test( + pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch +) -> None: + """A test that opens a file for writing, opens a descriptor for writing, renames a file onto + one or removes one under the real home, the HOME that the floor replaces, fails at that + operation, naming itself, also when it catches the failure. The files stay as they were. A + read under the real home, and a write under `tmp_path`, under the isolated HOME and outside + the real home pass (#4739). + + The real home of the inner run lies in this test's own temporary directory, so a guard that + lets a write through changes nothing a person keeps.""" + real_home = pytester.path / "real-home" + (real_home / "tools").mkdir(parents=True) + (real_home / "tools" / "gitleaks").write_text("real\n", encoding="utf-8") + outside = pytester.path / "outside" + outside.mkdir() + before = _tree(real_home) + result = _run_with_floor( + pytester, + monkeypatch, + f""" + import os + from pathlib import Path + + REAL_HOME = Path({str(real_home)!r}) + OUTSIDE = Path({str(outside)!r}) + + def test_opens_for_writing(): + (REAL_HOME / "notes.txt").write_text("notes\\n", encoding="utf-8") + + def test_opens_a_descriptor_for_writing(): + os.close(os.open(REAL_HOME / "tools" / "gitleaks", os.O_WRONLY | os.O_TRUNC)) + + def test_renames_onto(tmp_path): + staged = tmp_path / "gitleaks" + staged.write_text("#!/bin/sh\\necho mytool\\n", encoding="utf-8") + os.replace(staged, REAL_HOME / "tools" / "gitleaks") + + def test_removes(): + os.remove(REAL_HOME / "tools" / "gitleaks") + + def test_catches_the_failure(): + try: + (REAL_HOME / "tools" / "gitleaks").write_text("stub\\n", encoding="utf-8") + except Exception: + pass + + def test_reads_under_the_real_home(): + assert (REAL_HOME / "tools" / "gitleaks").read_text(encoding="utf-8") == "real\\n" + + def test_writes_under_tmp_path(tmp_path): + (tmp_path / "notes.txt").write_text("notes\\n", encoding="utf-8") + + def test_writes_under_the_isolated_home(): + (Path.home() / "notes.txt").write_text("notes\\n", encoding="utf-8") + + def test_writes_outside_the_real_home(): + (OUTSIDE / "notes.txt").write_text("notes\\n", encoding="utf-8") + """, + ) + result.assert_outcomes(passed=4, failed=5, errors=5) + output = result.stdout.str() + refused = [line for line in output.splitlines() if "write under the real home" in line] + failing = { + "test_opens_for_writing", + "test_opens_a_descriptor_for_writing", + "test_renames_onto", + "test_removes", + "test_catches_the_failure", + } + named = {test for test in failing for line in refused if f"::{test} (call)" in line} + assert named == failing + assert _tree(real_home) == before + + +def test_the_home_write_guard_calls_no_function_that_a_test_replaces( + pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch +) -> None: + """A test that replaces `os.lstat` with a function that removes a file, as the worktree + reclaim tests do, passes. The guard checks the removal and calls no replaced function, so the + function runs once and the removal does not start the guard again (#4739).""" + result = _run_with_floor( + pytester, + monkeypatch, + """ + import os + + def test_replaces_lstat_with_a_function_that_removes_a_file(tmp_path, monkeypatch): + doomed = tmp_path / "doomed.txt" + doomed.write_text("doomed\\n", encoding="utf-8") + real_lstat = os.lstat + calls = [] + + def removing_lstat(path, *args, **kwargs): + calls.append(os.fspath(path)) + if os.fspath(path) == os.fspath(doomed) and doomed.exists(): + doomed.unlink() + return real_lstat(path, *args, **kwargs) + + monkeypatch.setattr(os, "lstat", removing_lstat) + try: + os.lstat(doomed) + except FileNotFoundError: + pass + assert calls == [os.fspath(doomed)] + assert not doomed.exists() + """, + ) + result.assert_outcomes(passed=1) + + +def test_a_support_helper_writes_nothing_outside_the_run( + pytester: pytest.Pytester, monkeypatch: pytest.MonkeyPatch +) -> None: + """A support helper refuses a path outside the run's temporary directory before its first + write: `link_at_pin` with a user data root outside the run writes nothing (#4739). + + The user data root lies in this test's own temporary directory, so a helper that writes + changes nothing a person keeps.""" + outside = pytester.path / "outside" + outside.mkdir() + result = _run_with_floor( + pytester, + monkeypatch, + f""" + import pytest + + from tests.support.tools import link_at_pin + + def test_links_a_tool_under_a_user_data_root_outside_the_run(tmp_path, monkeypatch): + monkeypatch.setenv("DEVOPS_CLI_USER_DATA_ROOT", {str(outside)!r}) + with pytest.raises(pytest.fail.Exception, match="outside the run's temporary"): + link_at_pin("gitleaks", tmp_path / "links") + """, + ) + result.assert_outcomes(passed=1) + assert _tree(outside) == {} + + +_LINK_A_TOOL_FROM_PLAIN_PYTHON = ( + "import sys\n" + "from pathlib import Path\n" + "sys.path.insert(0, sys.argv[1])\n" + "from tests.support.tools import link_at_pin\n" + "link_at_pin('gitleaks', Path(sys.argv[2]))\n" +) + + +@pytest.mark.live("python") +def test_a_support_helper_called_outside_pytest_writes_nothing(tmp_path: Path) -> None: + """`link_at_pin`, called from plain Python with no pytest run, as an agent once called it, + stops before its first write and says why (#4739). + + The HOME of the child process lies in this test's own temporary directory, so a helper that + writes changes nothing a person keeps.""" + home = tmp_path / "home" + home.mkdir() + env = {name: value for name, value in os.environ.items() if name != "DEVOPS_CLI_USER_DATA_ROOT"} + env["HOME"] = str(home) + child = subprocess.run( + [ + sys.executable, + "-I", + "-c", + _LINK_A_TOOL_FROM_PLAIN_PYTHON, + str(REPO_ROOT), + str(tmp_path / "links"), + ], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + check=False, + timeout=120, + ) + assert child.returncode != 0 + assert "no pytest run is active" in child.stderr + assert sorted(home.rglob("*")) == [] + + def test_test_modules_repeat_no_floor_resets() -> None: """None of the 15 autouse fixtures repeating floor resets remain in test modules (#2173).""" target_fixtures = { diff --git a/tests/support/bootstrap.py b/tests/support/bootstrap.py index 60ef690e4f..c4d3a0b2d5 100644 --- a/tests/support/bootstrap.py +++ b/tests/support/bootstrap.py @@ -21,11 +21,17 @@ from collections.abc import Callable from pathlib import Path from types import ModuleType +from typing import Any import pytest from tests import support +# The real home: the HOME that `isolate_home` replaces, which the home write guard keeps (#4739). +REAL_HOME = pytest.StashKey[Path]() +# The key of `workerinput` by which the controller hands the real home to an xdist worker. +_REAL_HOME_INPUT = "devops_cli_real_home" + def is_xdist_worker(config: pytest.Config) -> bool: """Report whether the pytest process is an xdist worker rather than the controller.""" @@ -51,9 +57,18 @@ def run_temp_root(config: pytest.Config) -> Path: return basetemp.parent if is_xdist_worker(config) else basetemp +def _real_home(config: pytest.Config) -> Path: + """The HOME that `isolate_home` replaces. An xdist worker inherits the controller's isolated + HOME, so it takes the real home that the controller hands it in `workerinput` (#4739).""" + workerinput = getattr(config, "workerinput", None) + return Path(workerinput[_REAL_HOME_INPUT]) if workerinput is not None else Path.home() + + def isolate_home(config: pytest.Config) -> None: """Isolate HOME into an empty directory under pytest basetemp, with a git identity on - `example.com`, and record it for the workspace tripwire's worker-home check (#1311).""" + `example.com`, and record it for the workspace tripwire's worker-home check (#1311). Record + the real home that it replaces for the home write guard (#4739).""" + config.stash[REAL_HOME] = _real_home(config) basetemp = _basetemp(config) home_dir = basetemp / "home" home_dir.mkdir(parents=True, exist_ok=True) @@ -192,3 +207,10 @@ def pytest_configure(config: pytest.Config) -> None: its paths under the isolated HOME (#1311, #1312).""" isolate_home(config) register_support_plugins(config.pluginmanager, support) + + +@pytest.hookimpl(optionalhook=True) +def pytest_configure_node(node: Any) -> None: + """Hand each xdist worker the real home, since the worker inherits the controller's isolated + HOME (#4739).""" + node.workerinput[_REAL_HOME_INPUT] = str(node.config.stash[REAL_HOME]) diff --git a/tests/support/config.py b/tests/support/config.py index 6a78f0a6d6..343ad7d738 100644 --- a/tests/support/config.py +++ b/tests/support/config.py @@ -55,12 +55,14 @@ def global_config() -> Iterator[Callable[[dict[str, Any]], None]]: from devops_cli.config.constants import CONST_CONFIG_PATH from devops_cli.config.settings import reset_settings_cache + from tests.support.home_write_guard import hold_to_the_run made = [ d for d in (CONST_CONFIG_PATH.parent, *CONST_CONFIG_PATH.parent.parents) if not d.exists() ] def write(data: dict[str, Any]) -> None: + hold_to_the_run(CONST_CONFIG_PATH) CONST_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) CONST_CONFIG_PATH.write_text(yaml.safe_dump(data), encoding="utf-8") reset_settings_cache() diff --git a/tests/support/config_write_guard.py b/tests/support/config_write_guard.py index 9e19db7dcc..2de566e64e 100644 --- a/tests/support/config_write_guard.py +++ b/tests/support/config_write_guard.py @@ -27,19 +27,8 @@ import pytest from tests.support.bootstrap import run_temp_root +from tests.support.file_changes import changed_path -# The PEP 578 audit events that change a file, from CPython's table of audit events, each with -# the position of the changed path in the event's arguments and of the directory descriptor the -# path is relative to, if any: `open` (a copy opens its destination too), `os.rename` (also -# `os.replace`) and `os.remove` (also `os.unlink`). Only this guard reads them, and it holds them -# itself: the fail-to-pass replay runs this `tests/` on the base's source, which lacks a name added -# to `src` with the guard. -_FILE_CHANGE_EVENTS: dict[str, tuple[int, int | None]] = { - "open": (0, None), - "os.rename": (1, 3), - "os.remove": (0, 1), -} -_WRITE_FLAGS: int = os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_CREAT | os.O_TRUNC _RUN_ROOTS: list[str] = [] _REFUSED: list[str] = [] _HOOKS: list[object] = [] @@ -59,18 +48,6 @@ def _is_config_name(name: str, names: frozenset[str]) -> bool: return any(name == config or name.startswith(f"{config}.") for config in names) -def _changed_path(event: str, args: tuple[Any, ...], spot: tuple[int, int | None]) -> str | None: - """The path an audit event changes, or None for an open that only reads, a path relative to - a directory descriptor and a descriptor in place of a path.""" - path_at, dir_fd_at = spot - if event == "open" and not args[2] & _WRITE_FLAGS: - return None - if dir_fd_at is not None and args[dir_fd_at] not in (None, -1): - return None - target = args[path_at] - return None if isinstance(target, int) else os.fsdecode(target) - - def _outside_the_run(path: str) -> bool: """Report whether `path` lies outside the temporary directory of the run in progress.""" if not _RUN_ROOTS: @@ -95,14 +72,10 @@ def _install() -> None: """Add the audit hook once per process.""" if _HOOKS: return - events = _FILE_CHANGE_EVENTS names = _config_names() def guard(event: str, args: tuple[Any, ...]) -> None: - spot = events.get(event) - if spot is None: - return - path = _changed_path(event, args, spot) + path = changed_path(event, args) if ( path is not None and _is_config_name(os.path.basename(path), names) diff --git a/tests/support/file_changes.py b/tests/support/file_changes.py new file mode 100644 index 0000000000..568536e0e5 --- /dev/null +++ b/tests/support/file_changes.py @@ -0,0 +1,38 @@ +"""The PEP 578 audit events that change a file, which the write guards of the floor read (#1921, +#2192, #4739). + +The table holds each event of CPython's table of audit events that changes a file, with the +position of the changed path in the event's arguments and of the directory descriptor the path is +relative to, if any: `open` (a copy opens its destination too), `os.rename` (also `os.replace`) +and `os.remove` (also `os.unlink`). The guards hold it in `tests/`, not in `src/`: the +fail-to-pass replay runs this `tests/` on the base's source, which lacks a name added to `src` +with a guard. +""" + +from __future__ import annotations + +import os +from typing import Any + +_FILE_CHANGE_EVENTS: dict[str, tuple[int, int | None]] = { + "open": (0, None), + "os.rename": (1, 3), + "os.remove": (0, 1), +} +_WRITE_FLAGS: int = os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_CREAT | os.O_TRUNC + + +def changed_path(event: str, args: tuple[Any, ...]) -> str | None: + """The path that the audit event `event` changes, or None for an event that changes no file, + an open that only reads, a path relative to a directory descriptor and a descriptor in place + of a path.""" + spot = _FILE_CHANGE_EVENTS.get(event) + if spot is None: + return None + path_at, dir_fd_at = spot + if event == "open" and not args[2] & _WRITE_FLAGS: + return None + if dir_fd_at is not None and args[dir_fd_at] not in (None, -1): + return None + target = args[path_at] + return None if isinstance(target, int) else os.fsdecode(target) diff --git a/tests/support/home_write_guard.py b/tests/support/home_write_guard.py new file mode 100644 index 0000000000..c961ab8f5f --- /dev/null +++ b/tests/support/home_write_guard.py @@ -0,0 +1,191 @@ +"""The home write guard: a test that writes a file under the real home, outside its run's +temporary directory, fails at that write, naming itself (#4739). + +The floor sets HOME to a directory of the run before devops-cli is imported, so a path that +devops-cli resolves lies in the run. A test can still name a path under the real home, the HOME +that `isolate_home` replaced. This guard is a PEP 578 audit hook in the test process, in the form +of the config write guard. While a test of the run runs, in its setup, call and teardown, it +refuses an open for writing, a rename onto and a removal of a file under the real home, outside +the run's temporary directory and outside the two roots that a run writes to itself: the checkout +with its common git directory, which the workspace tripwire checks, and the interpreter, where +Python writes its bytecode cache. A GitHub-hosted runner has its checkout in its home, and uv +installs an interpreter in the home. Outside a test, pytest itself writes its cache and the +bytecode of the test modules into the root directory of the run: the checkout, or for a run that +pytester starts, the HOME that pytester sets, which is the real home of that run. The refusal is +`pytest.fail`, which no `except Exception` in the code under test hides. It names the test from +`PYTEST_CURRENT_TEST` and shows the stack. The test also fails at teardown, because a refused +write in another thread fails no test by itself. + +The hook calls no function that a test can replace. A test replaces `os.lstat` with a function +that removes a file, and `os.path.realpath` calls `os.lstat`, so a hook that resolved the path +started itself again until Python stopped it at the recursion limit. The hook compares the written path, made absolute and +normalized with no file system call, with the given and the resolved form of each root. It does +not follow a symbolic link in the written path. + +A support helper can also run outside pytest, where no floor isolates HOME: on 2026-11-09 a +helper called from plain Python wrote stubs over 18 real tools. So a helper that writes to a path +that it does not get from its caller, such as a path that devops-cli resolves, calls +`hold_to_the_run` before the write. + +An audit hook cannot be removed, so the hook stays for the life of the process. Each run's +temporary directory and real home are pushed at `pytest_configure` and popped at +`pytest_unconfigure`, so a run that pytester starts in this process holds its tests to its own +directory and home. +""" + +from __future__ import annotations + +import os +import sys +from collections.abc import Generator, Iterator +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import pytest + +from tests.support.bootstrap import REAL_HOME, run_temp_root +from tests.support.file_changes import changed_path +from tests.support.host_paths import checkout_roots +from tests.support.paths import REPO_ROOT + + +@dataclass +class _Run: + """The resolved temporary directory of a pytest run, the forms of its real home and of the + roots that it writes to itself, and whether a test of the run runs.""" + + root: str + homes: tuple[str, ...] + kept: tuple[str, ...] + testing: bool = False + + +_RUNS: list[_Run] = [] +_REFUSED: list[str] = [] +_HOOKS: list[object] = [] +# The hook's own reference, so a test that replaces `os.getcwd` changes no check. +_GETCWD = os.getcwd + + +def _within(path: str, root: str) -> bool: + """Report whether the resolved `path` is `root` or lies under it.""" + return path == root or path.startswith(f"{root}{os.sep}") + + +def _forms(*roots: str | Path) -> tuple[str, ...]: + """The absolute form of each root as given and its resolved form.""" + forms = (form for root in roots for form in (os.path.abspath(root), os.path.realpath(root))) + return tuple(dict.fromkeys(forms)) + + +def _written(path: str) -> str: + """The written `path`, made absolute and normalized with no file system call.""" + return os.path.normpath(path if os.path.isabs(path) else os.path.join(_GETCWD(), path)) + + +def _kept_roots() -> tuple[str | Path, ...]: + """The roots that a run writes to itself: the checkout with its common git directory, and + the interpreter with its bytecode cache.""" + interpreter = ( + sys.prefix, + sys.base_prefix, + sys.exec_prefix, + sys.base_exec_prefix, + sys.pycache_prefix, + ) + return (*checkout_roots(REPO_ROOT), *(root for root in interpreter if root)) + + +def hold_to_the_run(path: Path) -> None: + """Fail when `path` lies outside the temporary directory of the pytest run in this process, + and for each path when no pytest run is active in the process. A support helper that writes + to a path that it does not get from its caller calls this before the write (#4739).""" + if not _RUNS: + pytest.fail( + f"no pytest run is active in this process, so a support helper writes nothing: " + f"{path}. Call the helper from a test, where the floor isolates HOME and the user " + "data root." + ) + root = _RUNS[-1].root + if not _within(os.path.realpath(path), root): + pytest.fail( + f"a support helper write outside the run's temporary directory {root}: {path}. " + "Give the helper a path under `tmp_path`." + ) + + +def _refuse(path: str) -> None: + """Record the refused write of the written `path` for the test's teardown and fail the test + at the write.""" + test = os.environ.get("PYTEST_CURRENT_TEST", "(no test)") + message = ( + f"write under the real home outside the run's temporary directory: {path} " + f"(test: {test}). Write under `tmp_path` or under HOME, which the floor puts in the run." + ) + _REFUSED.append(message) + pytest.fail(message) + + +def _install() -> None: + """Add the audit hook once per process.""" + if _HOOKS: + return + + def guard(event: str, args: tuple[Any, ...]) -> None: + if not _RUNS or not _RUNS[-1].testing: + return + path = changed_path(event, args) + if path is None: + return + run = _RUNS[-1] + written = _written(path) + if any(_within(written, home) for home in run.homes) and not any( + _within(written, root) for root in run.kept + ): + _refuse(written) + + _HOOKS.append(guard) + sys.addaudithook(guard) + + +def pytest_configure(config: pytest.Config) -> None: + """Hold writes under the real home to this run's temporary directory.""" + _install() + root = run_temp_root(config) + _RUNS.append( + _Run( + root=os.path.realpath(root), + homes=_forms(config.stash[REAL_HOME]), + kept=_forms(root, *_kept_roots()), + ) + ) + + +@pytest.hookimpl(wrapper=True) +def pytest_runtest_protocol() -> Generator[None, object, object]: + """Guard the writes of the test while its setup, call and teardown run.""" + run = _RUNS[-1] + run.testing = True + try: + return (yield) + finally: + run.testing = False + + +def pytest_unconfigure(config: pytest.Config) -> None: + """Give the run that started this one its temporary directory and real home back.""" + if _RUNS: + _RUNS.pop() + + +@pytest.fixture(autouse=True) +def home_writes_stay_in_the_run() -> Iterator[None]: + """Fail the test at teardown when it made a write under the real home that the guard + refused, also one in another thread or one that the code under test caught.""" + _REFUSED.clear() + yield + if _REFUSED: + refused = "; ".join(_REFUSED) + _REFUSED.clear() + pytest.fail(refused, pytrace=False) diff --git a/tests/support/spend_write_guard.py b/tests/support/spend_write_guard.py index cc239c1bf9..dcb2976a9f 100644 --- a/tests/support/spend_write_guard.py +++ b/tests/support/spend_write_guard.py @@ -21,13 +21,8 @@ from devops_cli.config.defaults import DEFAULT_AI_SPEND_DB_FILENAME from tests.support.bootstrap import run_temp_root +from tests.support.file_changes import changed_path -_FILE_CHANGE_EVENTS: dict[str, tuple[int, int | None]] = { - "open": (0, None), - "os.rename": (1, 3), - "os.remove": (0, 1), -} -_WRITE_FLAGS: int = os.O_WRONLY | os.O_RDWR | os.O_APPEND | os.O_CREAT | os.O_TRUNC _RUN_ROOTS: list[str] = [] _REFUSED: list[str] = [] _HOOKS: list[object] = [] @@ -58,17 +53,6 @@ def _extract_sqlite_path(db: Any) -> str | None: return db -def _changed_path(event: str, args: tuple[Any, ...], spot: tuple[int, int | None]) -> str | None: - """The path an audit event changes, or None for an open that only reads.""" - path_at, dir_fd_at = spot - if event == "open" and not args[2] & _WRITE_FLAGS: - return None - if dir_fd_at is not None and args[dir_fd_at] not in (None, -1): - return None - target = args[path_at] - return None if isinstance(target, int) else os.fsdecode(target) - - def _outside_the_run(path: str) -> bool: """Report whether `path` lies outside the temporary directory of the run in progress.""" if not _RUN_ROOTS: @@ -93,7 +77,6 @@ def _install() -> None: """Add the audit hook once per process.""" if _HOOKS: return - events = _FILE_CHANGE_EVENTS def guard(event: str, args: tuple[Any, ...]) -> None: if event == "sqlite3.connect": @@ -108,10 +91,7 @@ def guard(event: str, args: tuple[Any, ...]) -> None: _refuse(target) return - spot = events.get(event) - if spot is None: - return - path = _changed_path(event, args, spot) + path = changed_path(event, args) if ( path is not None and _is_spend_db_name(os.path.basename(path)) diff --git a/tests/support/tools.py b/tests/support/tools.py index 43d5db896c..1df2559e3c 100644 --- a/tests/support/tools.py +++ b/tests/support/tools.py @@ -2,7 +2,8 @@ A command links to the file in its tool's version directory under the user data root, which the test floor puts in the test's temporary directory. The installer's `--only-missing` then -finds each such tool at its pin and installs nothing. +finds each such tool at its pin and installs nothing. The helper writes only in the temporary +directory of a pytest run: outside pytest, the user data root is in the real home (#4739). """ from __future__ import annotations @@ -10,14 +11,19 @@ from pathlib import Path from devops_cli.tools_lock import installed_commands, load_tools_lock +from tests.support.home_write_guard import hold_to_the_run _EXECUTABLE = b"#!/bin/sh\necho mytool\n" def link_at_pin(name: str, target_dir: Path, content: bytes = _EXECUTABLE) -> None: - """Install the packaged lock's `name` as install-tools leaves it, without downloading it.""" + """Install the packaged lock's `name` as install-tools leaves it, without downloading it. + Each path is held to the run before the first write, so a refused path leaves no file.""" + commands = installed_commands(name, load_tools_lock().tools()[name]) + for path in (target_dir, *commands.values()): + hold_to_the_run(path) target_dir.mkdir(parents=True, exist_ok=True) - for command, installed in installed_commands(name, load_tools_lock().tools()[name]).items(): + for command, installed in commands.items(): installed.parent.mkdir(parents=True, exist_ok=True) installed.write_bytes(content) (target_dir / command).symlink_to(installed)