|
1 | 1 | """Shared test fixtures for the AgentWire test suite.""" |
2 | 2 |
|
3 | 3 | import os |
| 4 | +import sys |
4 | 5 | from pathlib import Path |
5 | 6 |
|
6 | 7 | import pytest |
7 | 8 | import yaml |
8 | 9 |
|
| 10 | +from tests import home_guard |
| 11 | + |
9 | 12 | FIXTURES_DIR = Path(__file__).parent / "fixtures" |
10 | 13 |
|
| 14 | +#: The owner's real config directory. Nothing in the suite may write here. |
| 15 | +#: Re-exported from the single owner so both halves agree on what "real" is. |
| 16 | +REAL_AGENTWIRE_HOME = home_guard.REAL_AGENTWIRE_HOME |
| 17 | + |
| 18 | +home_guard.install() |
| 19 | + |
| 20 | + |
| 21 | +def _agentwire_modules(): |
| 22 | + """Loaded agentwire modules, snapshotted (import can mutate sys.modules).""" |
| 23 | + return [m for name, m in list(sys.modules.items()) |
| 24 | + if name == "agentwire" or name.startswith("agentwire.") |
| 25 | + if m is not None] |
| 26 | + |
| 27 | + |
| 28 | +def _import_every_agentwire_module(): |
| 29 | + """Import the whole package once, BEFORE any test redirects ``$HOME``. |
| 30 | +
|
| 31 | + Load-bearing, and subtle. The redirect below works by rebinding |
| 32 | + module-level constants that were computed at import time — but it can only |
| 33 | + rebind modules that are *already imported*. Much of this codebase imports |
| 34 | + lazily inside functions (``from agentwire.__main__ import |
| 35 | + build_agent_command`` inside a test helper), so without this the first |
| 36 | + test to trigger such an import does it while ``$HOME`` already points at |
| 37 | + that test's tmp directory. The module then computes |
| 38 | + ``CONFIG_DIR = Path.home() / ".agentwire"`` against the *fake* home and |
| 39 | + freezes it there — permanently, for the rest of the session, because |
| 40 | + monkeypatch never patched it and so has nothing to restore. |
| 41 | +
|
| 42 | + The symptom is a constant stuck at some early test's tmp path, which is |
| 43 | + exactly the kind of cross-test bleed this fixture exists to prevent. Doing |
| 44 | + the imports up front means every constant is computed against the real |
| 45 | + home, so the per-test walk both rebinds and restores it. |
| 46 | +
|
| 47 | + Best-effort: a submodule that cannot import (optional dependency, platform |
| 48 | + guard) is skipped rather than failing collection. |
| 49 | + """ |
| 50 | + import importlib |
| 51 | + import pkgutil |
| 52 | + |
| 53 | + import agentwire |
| 54 | + |
| 55 | + # Importing the package touches the real config dir: `agentwire_dir()` |
| 56 | + # both resolves AND mkdirs, and some modules call it at import. That is the |
| 57 | + # package's own import-time behaviour, not a test polluting the store, and |
| 58 | + # attributing it to whichever test happened to be first would be a lie. It |
| 59 | + # is sanctioned rather than silenced, so it still shows up in |
| 60 | + # SANCTIONED_WRITES if anyone wants to look. |
| 61 | + with home_guard.sanctioned_real_home_write(): |
| 62 | + for info in pkgutil.walk_packages(agentwire.__path__, prefix="agentwire."): |
| 63 | + try: |
| 64 | + importlib.import_module(info.name) |
| 65 | + except Exception: |
| 66 | + continue |
| 67 | + |
| 68 | + |
| 69 | +_import_every_agentwire_module() |
| 70 | + |
| 71 | + |
| 72 | +@pytest.fixture(autouse=True) |
| 73 | +def _isolate_agentwire_home(request, tmp_path_factory, monkeypatch): |
| 74 | + """No test may read or write the real ``~/.agentwire`` — ever (#893). |
| 75 | +
|
| 76 | + Found the hard way: ``~/.agentwire/sessions/resumed/metadata.json`` was a |
| 77 | + live record in the owner's config directory, written by this suite and |
| 78 | + grown to 80 fabricated conversation ids — one appended per full-suite run, |
| 79 | + because ``conversation_ids`` is a chain by design (#871). Beyond tests |
| 80 | + mutating real user state being a defect on its own, it corrupted a |
| 81 | + measurement: sizing #871's orphaned-history doctor check against the real |
| 82 | + store surfaced 28 recorded ids with no transcript, *all* from that one |
| 83 | + record, with zero genuine orphans behind them. |
| 84 | +
|
| 85 | + Two levers, because there are two ways a path gets computed: |
| 86 | +
|
| 87 | + 1. **``$HOME``** — ``Path.home()`` resolves through ``expanduser``, which |
| 88 | + reads the variable, so redirecting it catches everything computed at |
| 89 | + *call* time, including modules imported later by a lazy import. |
| 90 | + 2. **A walk over loaded modules** — roughly forty constants across ~25 |
| 91 | + modules are computed at *import* time |
| 92 | + (``COHORT_ROOT = Path.home() / ".agentwire" / "cohorts"`` and friends) |
| 93 | + and are already frozen before any fixture runs. Rebinding them by |
| 94 | + walking beats enumerating them: a hand-written list would rot the first |
| 95 | + time someone adds a constant, which is exactly how this class of bug |
| 96 | + recurs. ``test_home_isolation.py`` asserts the walk missed nothing. |
| 97 | +
|
| 98 | + Per-test rather than per-session, so no test can observe another's writes. |
| 99 | + Tests that need their own location re-patch the same attributes via |
| 100 | + ``monkeypatch``, which overrides this. |
| 101 | + """ |
| 102 | + # Escape hatch for the rare test that must see the REAL deployment paths |
| 103 | + # to assert on them — e.g. "role prompts are not in a directory macOS |
| 104 | + # garbage-collects", which this fixture would otherwise make vacuous by |
| 105 | + # relocating them into exactly such a directory. Read-only by intent, and |
| 106 | + # not a hole: the session-scoped backstop below still fails the run if an |
| 107 | + # opted-out test writes anything. |
| 108 | + if request.node.get_closest_marker("real_agentwire_home"): |
| 109 | + return REAL_AGENTWIRE_HOME |
| 110 | + |
| 111 | + fake_home = tmp_path_factory.mktemp("home") |
| 112 | + fake_config = fake_home / ".agentwire" |
| 113 | + fake_config.mkdir(parents=True, exist_ok=True) |
| 114 | + |
| 115 | + monkeypatch.setenv("HOME", str(fake_home)) |
| 116 | + monkeypatch.setenv("AGENTWIRE_HOME", str(fake_config)) |
| 117 | + |
| 118 | + for module in _agentwire_modules(): |
| 119 | + for attr, value in list(vars(module).items()): |
| 120 | + if not isinstance(value, Path): |
| 121 | + continue |
| 122 | + if value == REAL_AGENTWIRE_HOME: |
| 123 | + monkeypatch.setattr(module, attr, fake_config, raising=False) |
| 124 | + elif REAL_AGENTWIRE_HOME in value.parents: |
| 125 | + relocated = fake_config / value.relative_to(REAL_AGENTWIRE_HOME) |
| 126 | + monkeypatch.setattr(module, attr, relocated, raising=False) |
| 127 | + |
| 128 | + # ``agentwire_dir()`` both resolves AND mkdirs, and callers bound it with |
| 129 | + # ``from .utils.paths import agentwire_dir`` — a per-module copy that |
| 130 | + # patching the definition site would not reach. |
| 131 | + def _fake_agentwire_dir() -> Path: |
| 132 | + fake_config.mkdir(parents=True, exist_ok=True) |
| 133 | + return fake_config |
| 134 | + |
| 135 | + for module in _agentwire_modules(): |
| 136 | + if callable(vars(module).get("agentwire_dir")): |
| 137 | + monkeypatch.setattr(module, "agentwire_dir", _fake_agentwire_dir, raising=False) |
| 138 | + |
| 139 | + return fake_config |
| 140 | + |
| 141 | + |
| 142 | +@pytest.fixture(scope="session", autouse=True) |
| 143 | +def _real_agentwire_home_untouched(): |
| 144 | + """Backstop: fail the run loudly if anything escaped the redirect (#893). |
| 145 | +
|
| 146 | + The redirect above is prevention; this is detection. Implementation lives |
| 147 | + in :mod:`tests.home_guard` so there is exactly one recorder — see the note |
| 148 | + there about pytest loading this file under two module names. |
| 149 | + """ |
| 150 | + yield |
| 151 | + failure = home_guard.report() |
| 152 | + if failure: |
| 153 | + pytest.fail(failure, pytrace=False) |
| 154 | + |
11 | 155 |
|
12 | 156 | @pytest.fixture(autouse=True) |
13 | 157 | def _no_real_outbound_email(request, monkeypatch): |
|
0 commit comments