I used monkeypatch to hide a missing parameter
I wrote a small function and a test for it. The test passed, the review passed, and the code was still wrong. The test passed because it changed the state of the whole process to make the function behave. This post covers what I did, why it was a mistake, and what I’m doing differently now.
What I wrote
The function finds test scripts under a few directories and skips data directories:
def discover(trees: Sequence[str], data: Sequence[str] = ()) -> list[Path]:
return sorted(
test
for tree in trees
for test in Path(tree).rglob("*.test.sh")
if not any(test.is_relative_to(held) for held in data)
)
Path(tree) is a relative path, so rglob searches from whatever the process’s current directory happens to be. The function has no way to take a root directory, so to test it I changed the directory:
@pytest.fixture
def trees(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
# ...create some files under tmp_path...
return tmp_path
def test_every_test_under_a_tree_is_found_in_order(trees):
assert discover(["scripts"]) == [...]
The test went green. It shouldn’t have been possible to write it this way without someone noticing.
Why it’s wrong
monkeypatch let me skip a design problem. The function depends on the current working directory, but nothing in its signature says so. discover(["scripts"]) returns different results depending on where it’s run from. Run it from a subdirectory or a different worktree and it finds different files, or none at all.
The fix is a single parameter:
def discover(root: Path, trees: Sequence[str], data: Sequence[str] = ()) -> list[Path]:
return sorted(
test
for tree in trees
for test in (root / tree).rglob("*.test.sh")
if not any(test.is_relative_to(root / held) for held in data)
)
The production caller already knows the repository root and passes it in. The test passes tmp_path. Nothing changes the state of the process.
It wasn’t just this one test
When I checked the rest of the suite, I found about thirty uses of monkeypatch, and almost all of them were the same mistake:
chdirto control a function that reads the working directory. That function should take arootorcwdargument.setenv/delenvto control a function that readsos.environdirectly. That function should take anenvironment: Mapping[str, str]argument.setenv("PATH", ...)to make a subprocess pick up a stub tool first. The code should accept an injected runner, or pass apathto the runner.
Our testing standard already says that any dependency a function reaches outside its inputs, including the filesystem and the environment, should be a parameter so a test can pass in a fake. Some of our code follows that rule, and those functions are easy to test. The code I patched didn’t follow it. I patched the process instead of adding the parameter, and the passing tests made the rule look satisfied when it wasn’t.
What it cost
- Hidden inputs. The function’s behavior depended on process state that callers couldn’t see.
- Tests that only pass in isolation.
monkeypatchundoes its changes after each test, so the suite stays green. But anything that runs in a thread, or a fixture that reads the value before the patch is applied, sees the real process state. - A misleading signal. A test that patches the process looks just like a test of a well-designed function. The assertion is the same in both cases. The difference only shows up in the fixture list.
A related smell: the module under test is a script that does its work on import. To get at its functions, the test loaded it by file path with spec_from_file_location and exec_module. That’s a sign the script needs a thin entry point and a separate importable module.
What I’ll do from now on
- I’ll treat
monkeypatchin a test signature as a sign that the function is missing a parameter. The exception is when the thing being patched belongs to code we don’t own, like a third-party module’s attribute or an environment variable a library reads internally. That’s what the fixture is for. Using it to control our own functions means I skipped writing a parameter. - The working directory and the environment are dependencies like any other. Functions take them as arguments. One thin entry point reads
Path.cwd()andos.environonce and passes them down. Tests pass plain values. - A passing test that patches the process isn’t evidence of good design. When I review, I’ll read the fixture list as well as the assertions.
A checklist for reviewers
monkeypatchin a test or fixture signature for our own code. Ask which input is coming in through the process, and why it isn’t an argument.monkeypatch.chdir(...)before calling a function that takes no path.monkeypatch.setenv(...)for a variable the function reads fromos.environdirectly.Path("relative")built with no root argument, oros.environ[...]read anywhere other than the entry point.- A test that loads a script with
spec_from_file_locationandexec_moduleto reach its functions.
We had already written down the rule I broke. What we hadn’t named was the most obvious sign that someone was breaking it, so I’m naming it here: when you see monkeypatch, ask which parameter is missing.