hermetic-python-testing
Write Python modules with hermetic unit-test seams. Covers sandboxed inputs AND live-side-effect output defaults (telegram/webhook/mail routes).
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 4
- Forks
- 1
01 前言 Front Matter
- name
- hermetic-python-testing
- author
- Steadfaste Fleet
- license
- MIT
- version
- 1.0.0
- category
- software-development
- metadata
- { "hermes": { "tags": [ "testing", "python", "isolation", "hermetic", "unit-test", "seams" ], "related_skills": [ "test-driven-development", "codebase-design", "survey-before-action" ] } }
- platforms
- [ "linux", "macos" ]
- description
- Write Python modules with hermetic unit-test seams. Covers sandboxed inputs AND live-side-effect output defaults (telegram/webhook/mail routes).
02 资源文件 2
- 参考文档references/order-dependent-failure-bisect.md3.0 KB
- 脚本templates/run-tests.sh3.2 KB
03 SKILL.md 正文
Hermetic Python Testing
Write Python modules so their unit tests never touch real state, real
credentials, or real network — and prove it. Born from telegram_notify S2
(2026-08-08): tests silently wrote to ~/.steadfaste-fleet/state/ and read the
real ~/.hermes/.env until the module was restructured.
When to Use
- Writing a new Python module that reads env vars, paths, or config files
- Adding L0 unit tests to a module that touches files, state, or network
- A test "passes" but you suspect it hit real resources (check the module's log/state files for unexpected entries)
- Refactoring a module to be testable without mocking the whole world
Core Rules
1. Resolve paths LAZILY, never at import time
# ❌ BAD — frozen at import; tests setting the env var after import hit REAL paths
STATE_FILE = Path(os.environ.get("MY_STATE_DIR", Path.home() / ".x")) / "state.json"
# ✅ GOOD — resolved per call; tests point it at tmp_path via monkeypatch.setenv
def _state_file() -> Path:
return Path(os.environ.get("MY_STATE_DIR", Path.home() / ".x")) / "state.json"
Import-time constants freeze the path for the whole process. Tests that set
env vars AFTER import (the standard monkeypatch.setenv pattern) silently
read/write the real location. Symptom to watch for: a module's real log file
or state JSON appears in ~/.steadfaste-fleet/state/ after a test run.
2. Expose seams for clock and send, then monkeypatch them
def _now() -> float: return time.time()
def _sleep(s: float) -> None: time.sleep(s)
def _send_once(token, chat_id, text): ... # the network boundary
Tests patch these module attributes:
with patch.object(tn, "_now", side_effect=fake_now), \
patch.object(tn, "_send_once", side_effect=fake_send):
...
This tests coalescing windows, retry budgets, and backoff with a fake clock and zero network.
3. Hermetic fixture setup — state dir AND env file, both in tmp
Every test that exercises the module gets its own tmp state dir and a fake env file:
def _setup(tmp_path, monkeypatch, chat="111222333", quiet="", mute=""):
state_dir = tmp_path / "state"; state_dir.mkdir(exist_ok=True)
env_file = tmp_path / "env"
env_file.write_text(f"TELEGRAM_BOT_TOKEN=123456:TESTTOKEN\nTELEGRAM_HOME_CHANNEL={chat}\n")
monkeypatch.setenv("MY_STATE_DIR", str(state_dir))
monkeypatch.setenv("MY_ENV_FILE", str(env_file))
return state_dir, env_file
4. Verify the hermeticity — never trust "tests passed"
After the suite is green, confirm no real resources were touched:
- The module's real state/log/lock files must NOT exist afterward
- No real credentials were read (check for side effects like real sends)
- Grep the test file for real identifiers (chat ids, tokens, hostnames,
/home/<user>/paths) — placeholder values only
5. Override live-side-effect defaults EXPLICITLY — sandboxed inputs are not hermeticity
A test that feeds tmp_path INPUTS can still act on the real world if the tool
under test has a default OUTPUT route. Proven 2026-09-30: the bridge-runner
test ran fleet-bus-bridge-run.py on a tmp echo.py without --deliver — the
runner's default is Telegram, so every test run sent cron:test-echo / hello from test to the user's real chat (repeated complaints: "I keep seeing
this"). Before invoking any tool/CLI in a test, grep its args/env for defaults
that route to a real channel (messenger, webhook, mail, metrics) and pass the
explicit safe target (--deliver local, FLEET_DEPLOY_HOME=tmp_path).
Assert the live default in a dedicated test — never exercise it by accident.
Prefer a SUITE-LEVEL kill-switch over per-call flags. Passing the safe
target into the test you happen to be writing does not protect the suite: the
next test someone adds calls the same function with the same dangerous default,
and the live channel fires again. Put an autouse SESSION fixture in
conftest.py that redirects the module's config away from production for the
whole process — point its env-file at a path that does not exist and clear the
destination chat/webhook variable. The fail-safe direction is "no credential →
skip", never "no credential → guess". Tests that genuinely exercise the send
path set their own values back via monkeypatch, so the guard costs them
nothing.
Mocking the write does NOT mock the notify. A post-commit side effect sits AFTER the call you patched: a unit test that mocks the DB layer and asserts the stored value still runs the notification that write triggers. Verified: a test proving a shell payload is stored as a literal — mocking only the query layer — also sent a real message on every run, which surfaced as recurring user noise ("I keep seeing this") that could never resolve because each run minted a fresh id. When you mock a dependency, read the function you are calling through to the END and list every external effect that follows the mocked call.
A guard needs a control proving the GUARD did the work. "notify returned False" also passes if the module is simply broken. Pair it: assert the send path refuses under the suite's environment, AND assert that with a valid env file the same probe DOES resolve its credential (a read-only call — no send). Without the second half, the first half proves nothing.
A tool you invoke may detect its SUBJECT on the inherited PATH. When the
code under test shells out and probes for a binary (command -v <tool>), passing
the ambient PATH through means the case asserting "tool not installed" can be
satisfied by the runner's own install: the audited host is no longer the only
source of truth, the assertion flips per machine, and the failure names nothing
useful ("expected exit 1, got 0"). Scrub the PATH for every case — drop each
directory that actually contains the binary — and put the detected route in the
failure DETAIL (tool_on_PATH=<which(...)>, home_tool=<exists>), so the next
red run says which route the tool took instead of only the exit code.
6. An imported module must not mutate os.environ at import
Loading a module is not a side-effect-free act. A module that parses an env
file into os.environ at MODULE scope poisons the whole pytest process for
every suite that runs after it. Verified 2026-10-01: a deploy script
exported the canonical env file at import; a metrics suite exec_moduled it,
so a var added to that file that day leaked into the process env and the
notify suite — which resolves its chat id from os.environ FIRST — used the
real value and failed only in the full run.
Two rules follow:
- The module: keep env-file parsing in a function called from
main()(_source_env_overrides()), never at module scope. Prove it:exec_modulethe file and assert no var appeared. - The test: if the code under test reads a process-env var BEFORE its
fixture file,
monkeypatch.delenvthat var in the fixture. A fixture that only points its own env file cannot defend against a leaked process value.
7. An imported module's LOGGER writes to real state
Loading a module runs its module-level logging setup. A module that attaches a file
handler at import (a RotatingFileHandler over a real log directory) means every
test that imports it APPENDS to that production log, and the entries are
indistinguishable from real ones — a fabricated cycle number or a (test) error line
lands in the audit trail a reviewer will later read as history. Same family as rule 6:
import is not a side-effect-free act.
- Silence by LEVEL, and leave the handler attached. Setting the logger above CRITICAL suppresses records. Clearing handlers is stronger but destroys the seam you need to prove the silencing works, and a module that re-attaches handlers later defeats the clear.
- Prove the "it did not write" assertion is not vacuous. An assertion that a real
file did not grow also passes when the code could never have written to it — e.g.
the module resolves its log path from a constant the test redirected. Check both
directions, and make the control write NOTHING (writing to prove a file is not
written to is self-defeating): first assert the logger carries a handler BOUND to
the real target (a
FileHandler'sbaseFilename), then detach it, restore the level with a counting handler attached, and assert records ARE emitted — so there was something to suppress — then re-attach and assert the silenced run contributes no FABRICATED line. If the control cannot emit, the test is measuring nothing. - Assert the "did not write" property by CONTENT, never by file SIZE. A byte-equality
check on a shared log is racy: any concurrent writer — a cron, a deploy, another
agent — appending a legitimate entry during the measurement window fails a test about
YOUR code, i.e. a false report of the very thing the test claims to measure. Read the
bytes appended in the window and assert none of them carries the test's own markers
(its fabricated ids, its session name, its
(test)strings); if something else wrote meanwhile, report that as non-test growth instead of failing on it. - Know what the module binds at IMPORT vs what you patch afterwards. A handler built at import keeps the real path even after the test patches the module's HOME; a path resolved per call follows the patch. Assert what is actually bound before trusting either result — a passing one-way size check is a claim about your probe, not about the artifact.
8. Once-only initialization must be keyed to the RESOURCE, not to the process
A module-level "already done" flag (_SCHEMA_DONE = False) makes the FIRST
resource a process touches the only one that ever gets set up. Any caller that
switches resources later — a test repointing the module constant at a tmp file,
a tool opening a second database — receives an un-set-up resource and fails on
the first query against it (no such table: <name>). The failure reads as
flakiness: those tests pass in isolation and fail in a full run, because some
other test has already opened the first resource.
- Key the guard to the thing that varies — the database FILE, the directory being prepared, the fixture identity — a SET of resources rather than a boolean.
- Read the key from the connection/handle under test, not from the module
constant. The caller may have repointed the constant after the connection was
opened, and the question the guard actually answers is "does THIS resource have
its setup" (
PRAGMA database_listgives the file a sqlite connection is attached to). - This is a SEAM, not just a test fix. The process-global flag is untestable by construction: no fixture can prove setup happened for the second resource while the code can only ever answer for the first. Fix the module, then pin it with a test that opens two resources in one process — and a premise test so the guard cannot pass vacuously if the DDL entry point moves.
- When the repo's own suite is red, test the claim that it is not your fault. Re-run the full suite with no lock and no in-flight change and compare the failure LIST, not the count: identical list = pre-existing, and "passes in isolation, fails in the full run" points at module state, not at you.
9. The caller's environment can change WHICH tests exist — not just what they read
Rule 6's family, one level up. An inherited PYTHONPATH or PYTHONHOME that points at a
foreign site-packages makes some test modules fail to IMPORT, and pytest then reports a
smaller suite as a clean run. Measured on one host, same command, only the environment
differing: 1818 collected with 4 collection errors contaminated vs 1846 with none
clean — four whole modules dropped, and the runner printed N passed either way. An agent
shell almost always exports PYTHONPATH, so the contaminated case is the DEFAULT case.
- Run the suite through a wrapper that CLEANSES the environment and resolves the
interpreter by CAPABILITY (never by
PATHor a barepython3):env -u PYTHONPATH -u PYTHONHOME "$PY" -m pytest …. Copyable shape:templates/run-tests.sh. - The wrapper must not REQUIRE a fleet install. A repo whose host has no resolver and no fleet
venv still needs to run its own suite: probe
python3/pythononPATHby CAPABILITY (still an import test, never a bare path), ANNOUNCE that you fell back and why, and still exit 3 when nothing can import pytest. A silent fallback is worse than none — it swaps which code decides the interpreter while the run looks identical, and it can make a stub test exercise the real thing and "pass". - Pin the wrapper's portability, not only its behaviour. A source scan asserting no bash-4-only or
BSD-hostile construct (the list lives in
shell-scripting), plus a run of the REAL wrapper in a constructed environment (temp repo, empty HOME, stubbed PATH) for the branches your host cannot reach. Same for the guard's numbers: assert "more than zero collected", never a count that is only true of one repo — a shared guard that encodes this repo's size fails a healthy smaller repo. - Guard collection, not just results. A test that runs the suite's collection in a
subprocess and FAILS on
N errors during collection— while also asserting a non-trivial collected count, so “0 collected” cannot read as clean — is what stops a dropped module from being reported behind a green total. A green run that tests less than it claims is worse than a red one. - A collection error is not a missing dependency.
ModuleNotFoundErrornaming a SUBMODULE of an installed package (pydantic_core._pydantic_core) is an ABI mismatch from a shadowedsite-packages, not something topip install: fix the environment, not the package list, and never record it as “dependency X is broken”. - Check the runner's own default before blaming a test. pytest with FLAGS but no PATH
collects the whole current directory — in a repo that means
.git, deploy trees and the venv, and it hangs. Always supply a path.
10. A module-level ENTRYPOINT makes a script un-importable — and the importer cannot defend itself
Rules 6 and 7 are about a module's side effects at import; this is that family one step further:
the module's whole JOB runs at module scope. count = purge() + sys.exit(0) at the bottom of a
script means importing it to exercise its shipped logic fires the work against the LIVE resource,
and the importer cannot prevent it — repointing the module's path constant after exec_module is
already too late. Observed: a probe importing a purge script removed 780 files from the live state
directory before it could repoint anything. The importer is then left reporting a side effect it
caused while measuring something else.
- Fix the MODULE, not the importer:
def main() -> int: ...plusif __name__ == "__main__": sys.exit(main()). Import becomes inert; only running the file has effects — and the function stays drivable with its path constant repointed. - Check BEFORE importing a file you do not own. Read the end of the file (or
ast-walk its module body) for a bare call, aprint, orsys.exitoutside a def or the__main__guard. If one is there, fix the guard first — do not import it "just to see". - Prove the guard in THREE directions, because "it did not purge" also passes when the function
is simply broken: (a) with the home directory patched into a temp tree, importing leaves the
stale fixture untouched AND the module's path constant really resolves into that temp tree —
without that second half, (a) asserts only that the probe aimed somewhere harmless; (b) calling
the function DOES remove the fixture; (c) running the file as a SUBPROCESS with
HOMEredirected removes it and reports — the real cron/systemd path, which an import test never exercises. - Pin the shape source-level too: walk the module body with
astand assert every top-level statement is an import, an assignment, a def, or the__main__guard, so a future edit cannot quietly reintroduce the side effect.
11. An end-to-end test drives the REAL path — and must not depend on the DEPLOYED tree
This user's standard for a non-trivial change is comprehensive unit tests PLUS one end-to-end run of the real system path (real argv in, real exit status out), which is the seam that catches what unit seams cannot. Two rules keep that test honest and durable:
- Redirect the deploy/install ROOT at a fixture; never let the test read the host's deployed
state. A command that resolves a collaborator from a deploy root (a CLI whose module is copied
under the deploy home, a doctor that drives it) passes locally and goes RED on every fresh
checkout, because the deployed copy is only current after a deploy — and the first failure a
reader meets is the suite, not the change, which is how a suite becomes something people ignore.
Point the root variable at
tmp_path(env/monkeypatch:FLEET_DEPLOY_HOME=<tmp>), so the test exercises the repo's own copy and measures the CHECK and the CLI it drives. Then verify the DEPLOYED wiring by RUNNING it in the cycle that changes it (a real invocation against the deployed path, recorded in the committed evidence) — deployment state is verified live, not asserted in a test. Note the consequence for assertions about the run: the exit code then reflects EVERY check the command performs (a pre-deploy tree fails unrelated deploy-sync checks), so assert the property you own (rcis a usage-clean code, the JSON parses) and say in a comment why an exact 0 would turn the test into a probe of the host. - Build the fixture from the collaborator's REAL output, not from your reading of it. When the
fixture stands in for another tool's machine-readable input (a
--jsoninventory, a manifest, a config the code parses), generate it by RUNNING that tool against a fixture directory with its own input path redirected — a hand-written fixture pins your guess at the shape, so it keeps passing after the real output changes and fails only when the guess was wrong. That is the difference from rule 5: the collaborator runs for real, on fixture inputs.
12. Real-git test fixtures must sandbox their OWN hooks — the host's global core.hooksPath runs inside them
A test that creates a real git repo in tmp_path inherits the host's GLOBAL
core.hooksPath. On a governed host that points it at the fleet hooks
(~/.steadfaste-fleet/hooks), the fleet pre-commit hook runs INSIDE the
throwaway repo and refuses the fixture's bare commits (no pathspec) with a
non-zero exit. When the fixture's commit helper swallows the return code (the
standard subprocess.run([...]).stdout pattern), the repo silently stays
EMPTY and every assertion that needs real commits fails with confusing,
unrelated symptoms: base...HEAD HEAD HEAD, git log: no commits yet, the
provenance block still empty.
- Set the throwaway repo's OWN repo-level
core.hooksPathright after init:git config core.hooksPath <repo>/.git/hooks. Repo-level is the sanctioned escape (the enforcer's own message says "a repo that should NOT have this check sets its own core.hooksPath"); per-invocation-c core.hooksPath=is a BLOCKED bypass. - Assert the fixture commit actually LANDED (
git rev-list --count HEADor the commit returncode) — a swallow-error commit helper hides the refusal and leaves only empty repos. A refused fixture fails the SEED, not the later assertions, so the red run names the real cause.
Verification
pytest tests/test_<module>_unit.py -q→ all pass- The suite collects the SAME number of tests under your wrapper as with
env -u PYTHONPATH -u PYTHONHOME(a lower count means modules failed to import) - The module's real state dir is clean after the run (no leftover files)
grep -nE "<real-chat-id>|<real-host>|/home/<user>/" tests/→ no hits- No network calls happened (fake send patched in; check no real HTTP in log)
Pitfalls
- NEVER mutate
sys.pathin test files to import the module under test. Asys.path.insert(0, <repo>/core)in one suite SHADOWS same-named modules/packages for every sibling suite running later in the same pytest process. Verified 2026-09-02: inserting<repo>/coremadeimport fleet_busresolve to thecore/fleet_bus/PACKAGE instead of thelib/fleet_bus.pyMODULE a sibling suite (test_bus_outbox) expected → ImportErrors in the full run, green in isolation. The suite that "passes alone but breaks others" is the culprit — run the pair together to confirm. Fix for pure-stdlib modules under test: load them by FILE PATH with a unique module name, zero path mutation:
Works whenever the module has no intra-package imports. If it does, use adef _load(name, path): spec = importlib.util.spec_from_file_location(name, os.path.normpath(path)) assert spec is not None and spec.loader is not None, f"cannot load {path}" mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(mod) return mod validate = _load("cortex_bus_validate_test", "core/fleet_bus/validate.py")conftest.pypythonpathentry (pytest-managed) instead of hand-rolled inserts. - Import-time path constants are the #1 hermeticity killer (see rule 1).
- Real identifiers in fixtures — a numeric chat id (e.g.
111222333) looks like an arbitrary integer and sails through the secret-leak detector; the scanner only flags/home/<user>/paths and emails. Use placeholders (111222333) and grep for the real id before committing. - State leakage across tests — every test needs its OWN tmp state dir; sharing one makes tests order-dependent.
- The module's own
if __name__ == "__main__"self-test should also go through the same seams, or it will hit real resources when run manually. - Queue mock returns for EVERY caller of a seam, not just the call site you are testing. Before writing the mock, grep the function under test's full call tree for uses of the seam — a sibling helper (e.g. a probe that queries the same LLM/API function) silently consumes the queued responses, and the code under test receives the wrong fixture or runs dry. The failure looks like a parsing bug in the function under test; the real bug is the mock budget. Count the seam's call sites first, then size the queue.
- Import repo packages at MODULE level in the test file, not inside test
functions. A
from pkg.sub import Xwritten inside a test function re-readssys.pathat call time; when a sibling suite (or a conftest fixture) restores/snapshotssys.pathbetween tests, the function-level import fails withModuleNotFoundErroreven though the suite passes in isolation. Symptom: green alone,No module named 'pkg.sub'only in the full run. Import the package at module top (after anysys.path.insert) so it is cached insys.modules— the cached module resolves from memory and is immune to path resets. This is the complement of the shadowing rule above: that rule is "your insert breaks siblings"; this is "siblings' restore breaks you." - Keep fixtures free of long digit runs. The repo PII guard
pattern-matches digit sequences as phone numbers and REFUSES the write — a
10-digit unix timestamp (
1700000000) and an all-zeros UUID both tripped it as "phone number". Use small ints for ids/timestamps (chat id7,ts=1), hex-letter UUIDs (aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee), andexample.comfor URLs in shared-surface test files. (The flip side of the numeric-chat-id rule above: that one is the detector missing a real id; this one is the detector flagging a fake one.) - A package module that imports cleanly can still crash when run as a
script. Relative imports (
from .transport import X) need a parent package, sopython3 daemon.py/ systemdExecStartfails with "attempted relative import with no known parent package" even thoughfrom pkg.daemon import mainworks. Verify the REAL invocation path, not just the import. Make one file work both ways with the run-as-script bootstrap:if __package__ in (None, ""): import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) __package__ = "<pkg_name>" - Do not replace a monkeypatchable module constant with a hardcoded path.
Repointing a reader from
SOME_HOME / ".env"to a literalPath.home() / "x" / ".env"silently broke the test that redirects it withmonkeypatch.setattr(mod, "SOME_HOME", tmp)— it read the real host path and failed. Keep a module-level constant (e.g.FLEET_ENV_FILE) and let tests patch THAT; a hardcoded path has no seam. - To find WHICH test pollutes
os.environ, hook pytest — and run with-s. A throwaway plugin (-p <name>, module onPYTHONPATH) that prints atpytest_runtest_setupwhen the leaked var is present, plus the previous test id, pinpoints the leaker in one full run. Without-spytest CAPTURES and DISCARDS a passing test's output, so the print never appears and you wrongly conclude "no leak". Check the var at SETUP, not teardown — fixtures undo their own patches during teardown, so a teardown probe misses real leaks. - A flaky test is not evidence the artifact is broken — probe the artifact OUT-OF-BAND before "fixing" it. Identical code that fails 2 runs in 3 is a RACE, and the race is often in the TEST. Before touching the module under test, drive it directly by hand (same request, outside pytest); if it answers correctly, the fault is the harness you wrote, not the code you were about to "fixing" it. Re-run the single test 3x first — deterministic vs flaky selects completely different fixes, and guessing wrong means rewriting working code.
- A git-gate test is an ambient-state test in disguise. An assertion that a hook
(pre-push, pre-commit) REFUSES a range only holds while the repo is ahead of its
upstream: it passes while work is in flight and fails the moment the tip is level,
which teaches readers to ignore it. Make the range a PRECONDITION — compute
merge-base <upstream> HEAD, and when it equals HEAD print an explicit SKIP with the reason — then assert the refusal only where a range exists. Asserting into the ambient condition instead is how a gate test turns red on a healthy tree. If the flake stops reproducing, STOP bisecting and bank what you proved. A failure that vanishes after N runs was a WINDOW, not an ordering: further bisect rounds buy nothing and cost the session. Record the MECHANISM you demonstrated with a control (a stub that reproduces it on demand), make the test hermetic against that mechanism, and leave the discriminator in the failure detail so a recurrence names its own route. "Mechanism proven, trigger unidentified, guarded and diagnosed" is a complete result — report it that way instead of widening the search. - Asserting on SOURCE TEXT? Strip comments and docstrings first — the file
legitimately names the thing you are asserting is absent. A guard written as
assert "addSystemPrompt" not in srcfailed against correct code, because the file's own comment explained why there is noaddSystemPrompt(). Grep the raw text and you flag your own documentation; strip comment lines (and preferably match the CALL,addSystemPrompt(, not the bare word) before asserting. Same family as any probe that is wrong rather than the code: a failing assertion is a claim about your probe first and the artifact second. - A guard that asserts a DETECTOR must assert the real one, not a plausible
one.
assert "sys.platform" in srcfailed against a store that correctly detects macOS viaos.uname().sysname == "Darwin". Read the implementation and assert what it actually does — or better, make the test BEHAVIOURAL: force the branch (set the flag) and assert the built command, instead of grepping for a string that merely resembles the mechanism. - Whitespace-normalise before asserting a PHRASE against source text. The
same family as the rule above: asserting a multi-word phrase failed because
the prose wrapped across a line break, so the substring never appeared
contiguously. Assert against
" ".join(text.split()), or drop the phrase assertion for a structural one. - Test the code you CHANGED — a neighbouring green suite is not evidence. Reporting "24 passed" from a test file that never imports either modified module verifies nothing about the change; it is reassurance shaped like proof, and it is the finding a reviewer will (correctly) raise. Before citing a test run as evidence, check the path: does any test in that file FAIL if you revert the change? If not, write one that does — a behavioural test on the changed code path, not a broader suite that happens to be nearby.
- A fallback/shim only defined when a dependency is ABSENT cannot be tested
from the machine that has the dependency. A guard asserting on the
conditional-shim class passed everywhere it was run and tested nothing: on a
host with the real package installed, the shim is never defined, so the
assertion inspected the real library instead. Drive the absent case for real
in a subprocess, by making the import fail:
A custom# a None entry in sys.modules makes `import pkg` raise ImportError script = "import sys; sys.modules['pkg'] = None; sys.modules['pkg.sub'] = None\n" script += "...load the module by path, assert the fallback engaged..." subprocess.run([sys.executable, "-c", script], ...)find_specthat RAISES ImportError is the wrong tool: the import machinery does not catch it, so it aborts instead of falling through to your guard. This case is worth a real test because it is the whole point of the fallback — and it is exactly where a pre-existing hard exit or an unreachable guard hides. - A test that reads AMBIENT state tests the machine, not the code. A refusal
case passed for as long as an unrelated stale lock file happened to exist in the
host's state dir, and went red the moment it was cleared — it had never once
exercised the branch it claimed to cover. Anything a test reads from a shared
location (locks, journals, session markers, live DB rows, and inherited
environment variables) is an accidental fixture: point it at a temp
HOME/ROOT, inject the value, ormonkeypatch.delenv(<VAR>, raising=False)in the shared runner when the test asserts the VAR-ABSENT branch. An agent shell commonly exports identity vars (AGENT_NAME) — a test that passes--agentexplicitly still silently depends on the caller NOT exporting one, so it goes green in a bare CI shell and red on a real host. Keep the real-resource assertion as ONE explicitly-labelled case. Clearing unrelated state is the cheapest way to discover tests that were passing by accident. The same trap fires when the subject reads a WELL-KNOWN HOST PATH, not an env var. Code that merges several registries (~/.pi/agent/mcp.json,~/.claude.json, the Hermesconfig.yaml) reads the LIVE files even when you substituted the fixture for one of them — the first two failing tests in a new suite both reported the host's real server name from the OTHER registry. A runner that submits fixtures to the subject must neutralise EVERY known path it reads (point them at a non-existent path in the runner's default, opt-in per test for the one under test), or the real files' content bleeds into every fixture. - A fake path standing in for a real resource silently selects the FALLBACK branch. Pointing the
code under test at
/tmp(or any path holding no repository, no config, no service) is not a neutral stand-in once the code gains an environment-derived branch: a probe like "is there a git repo here? a remote? a resolvable base?" answers NO at that path, so the test that meant to drive the NORMAL path drives the newly added fallback instead — green, and asserting about the wrong branch. It bites hardest immediately after adding such a branch, and it surfaces in several unrelated files at once (the same new predicate was reached by two different suites). Stub the predicate explicitly in every test that describes the normal case (m._is_fallback = lambda repo: False), give the fallback its OWN test asserting the fallback-specific behaviour, and name in the docstring which case the file is about — otherwise the next environment branch added reaches in again. - A test that repoints a SHARED module attribute (a module it does not own)
must restore it in
finally.setattr(doctor_checks, "HOME", tmp)looks like ordinary fixture setup and is not: the value outlives the test, survives into every later file in the process, and points at a temporary directory the harness then deletes. Every later test that reads that module silently produces nothing. The signature is worth memorising: the failures appear in a DIFFERENT file from the culprit, and the culprit's own tests are green — so the file you are staring at is the symptom, not the cause. Restore on the way out whether the body succeeded or raised, and add a regression test in the mutating file asserting the attribute is unchanged after the call. The same trap fires INSIDE one file, across sections. A test that installs a stub for section A and never puts the real function back leaves every later section asserting against the stub — and because a stub returns plausible values, the red run points at the code under test instead of at the test (aNonelock returned by the stub made three "must still fail closed" assertions look like the guard had been removed). Save the real attribute before patching and re-install it at the section boundary (real = m.fn…m.fn = real), or scope the stub to the section that needs it; when a whole block of assertions fails together in a fresh file, suspect the stub before the code. - POISON the collaborators the unit must NOT touch, rather than only restoring the ones it patches.
Restoring in
finallyprotects LATER tests; it does not protect THIS one from depending on an earlier test's teardown, or on a patch it never made. For every module attribute the function under test is not supposed to consult, install a stub that RAISES:
Two things come out of it: the test becomes deterministic under any ordering (a leaked or not-yet-restored patch fails LOUDLY and names the offending call instead of returning a plausible value that makes the assertions point at the code under test), and the unit's real dependency set is asserted rather than assumed. Restore EVERY attribute the test set indef _poison(*a, **k): raise AssertionError("must not call the store/range helpers")finally— the poisoned ones included, since a poison left behind breaks the next test exactly as a leak does. Prefer awith-scoped helper that saves and restores them together when a file has several such tests. - Finding WHICH test pollutes shared state is a pairing search, not a reading
exercise. See
references/order-dependent-failure-bisect.mdfor the recipe — run the victim alone, pair it with each candidate that touches the module, then bisect the failing group — and for what to do when the failure will not reproduce at all. - A test that references a DELIBERATELY-REMOVED symbol is stale, not a bug in the
feature. When a sibling suite fails on a constant that no longer exists in code
(e.g. a reviewer-model constant the operator reversed out of existence), the test
asserts the OLD contract — rewrite it to assert the CURRENT behavior (default →
canonical model; env override → cheaper), do NOT "repair" it by re-adding the
constant. Re-adding a constant a reversal deleted is how a reverted decision creeps
back in. Confirm via
git log -S '<symbol>' -- <file>that the removal was deliberate before concluding it is stale drain rather than a live regression. - A regression test whose SEED stage fails silently passes trivially — guard the seed
before the exercise step. A rename test that seeded the legacy entry by cloning a key
that a prior stage had already deleted died with KeyError, and the assertions that
followed passed against the UNSEDED fixture: the check was green without ever exercising
the rename. Any multi-stage test where later stages depend on an earlier stage's write
must assert the fixture landed (
grep -q '"key"' <fixture>/assert marker in fixture) between seed and exercise, so a dead seed fails the test instead of passing it for the wrong reason. A check that reads "PASS" while its setup raised is a false green, not a flake. - Derive a state-machine test's cases from the module's OWN table, not from your
memory of it. A test that hardcodes "advance X → completed" fails when the
machine does not allow that edge, and the red run blames the transition instead
of the assumption. Read the permitted set out of the module
(
for src, allowed in m.VALID_TRANSITIONS.items()) and drive a pair it actually allows, skipping with a printed reason when there is none — then assert BOTH directions (the permitted edge behaves, the forbidden one is refused) so the so the table, not the fixture, decides what is legal.- Before adding a helper to a test module, grep it for one that already exists — a hand-rolled
duplicate SHADOWS the original, and your new tests silently call the wrong signature. A second
_run()added to a suite whose first_runis(*args, env=None)made three new tests pass a dict positionally: they failed with argument-shaped errors that point at the assertions, not at the helper, so the red run reads like a bug in the code under test. Check first (grep -n "^def " tests/test_<module>.py), then use the existing seam. Read its semantics too: a helper that merges{**os.environ, **env}can ADD or override a variable but cannot REMOVE one, so a VAR-ABSENT branch is only reachable through it by passing an EMPTY value (which a[[ -n "$VAR" ]]guard treats as unset) — pass a sentinel and the branch you think you are testing is the VAR-SET one.
- Before adding a helper to a test module, grep it for one that already exists — a hand-rolled
duplicate SHADOWS the original, and your new tests silently call the wrong signature. A second
- 'The newest <file>' is the definition only when it DEFINES the construct. A guard that
reads
_migrations()[-1](or any 'latest config / schema / script') fails against a newer file that only USES the thing — a later migration that CALLS a function whose body an earlier one defines. Scan the set for the record that DEFINES the construct, newest-first, and match the exact definition (the function signature, not the file containing a mention), or the guard reads the wrong file and goes red on healthy code. - A 'skip if <lib> not importable' check can be defeated by importable-but-broken libraries
under contamination.
import reportlabsucceeds on a polluted heap while its real dependency (PIL's_imagingC extension) fails at build time, so a test that skips only on ImportError runs instead and fails mid-build. Widen the skip to import the ACTUAL dependency the exercised path needs and catch the broken-load exception — the point of the skip is 'the libs are usable here', not 'the top-level name resolves'. - A standalone test that loads its collaborator by path must check it AS A TEST, never at
import. Script-style suites that are each run directly (
python3 tests/test_<name>.py, no framework) make a module-scope precondition (if not hasattr(mod, "fn"): raise SystemExit(...)) fatal: the run dies before any test reports, the failure names no test, and a reader — including an automated reviewer of the diff — files it as a crash rather than as a guard, which is the opposite of what a precondition is for. Put the checks in a function the runner reaches FIRST (a name-sorted runner reachestest_00_preconditionsbefore any behaviour test) and ASSERT rather than raise: the collaborator exists, it carries the parameters this file calls it with (inspect.signature), and any module-level fact the test depends on is real — e.g. the logger it silences is the logger the module actually uses, otherwise the silencing is decorative and test output reaches production state. A genuine import failure stays an import error; a MISSING CAPABILITY becomes a named failing test.
04 同仓库更多 Skills
macbook-linux-maintenance
Legacy MacBook Linux fixes: GPU wedge, reboot hang, thermal.
governance-regression-triage
Triage a host's governance issues: what changed.
enforcement-immutability
Use when enforcement files lose their immutable flag.
steadfaste-fleet-repo-deploy
Use when committing to the steadfaste-fleet repo.
steadfaste-fleet-maintenance
Maintain an installed Steadfaste Fleet instance — update both the upstream Hermes Agent and the fleet repo layer, merge diverged histories, sync skills safely, and troubleshoot common issues. Covers the dual-update workflow (hermes update + fleet-update.sh), encrypted brain data backup, mycortex import, and recovery techniques.
fleet-preflight
DEPRECATED alias — merged into survey-before-action (2026-08-20). Load survey-before-action instead; its "Repo-Specific Pre-Flight" section covers git search, Hermes boundary, and deployment verification.