Product case study · December 1, 2026
Ask Claude Code why a file-writing test fails on its second run
Reproduce a pytest test that leaves report files behind. Give Claude Code a scoped repair, then verify repeat runs and preservation of an existing file.

Give each file-writing test its own directory before changing an application that correctly appends data.
Your report test passes. You run the same command again, and now the file contains two lines instead of one. Deleting the report makes the failure disappear until the next run.
The report writer may be doing exactly what it should. A test that writes into its working directory can inherit yesterday’s output. Ask Claude Code to isolate the test’s files while preserving the application’s append behavior.
This lab targets state that survives between test processes on disk. For an environment variable that leaks between tests in one process, use the separate pytest environment-leak exercise.
Verification scope: the baseline and reference repair below were run locally with Python 3.14.4 and pytest 9.2.0. The Claude Code prompt is an authored exercise, not a recorded agent run. Official documentation was checked December 1, 2026. You need Bash on Linux, macOS or WSL, Python with venv, and an installed, authenticated Claude Code for the agent step.
Reproduce the second-run failure
Create a fresh practice directory. Keep this terminal open for the remaining commands:
file_lab=$(mktemp -d /tmp/claude-file-test.XXXXXX)
cd "$file_lab"
python3 -m venv .venv
.venv/bin/python -m pip install pytest
Save this as report.py:
from pathlib import Path
def append_report(line):
with Path("report.txt").open("a", encoding="utf-8") as report:
report.write(line + "\n")
The contract is intentional: append one line to report.txt in the current working directory. Existing lines must survive. This tutorial does not redesign that interface.
Save this deliberately flawed test as test_report.py:
from pathlib import Path
from report import append_report
def test_one_line():
append_report("alpha")
assert Path("report.txt").read_text(encoding="utf-8") == "alpha\n"
Run it twice as two separate commands. The second command is supposed to fail:
.venv/bin/python -m pytest -q test_report.py
.venv/bin/python -m pytest -q test_report.py
Locally, the first command returned exit code 0, with one pass. The second returned 1, with one failure: the actual text was "alpha\nalpha\n". A fresh Python process did not remove the file left by the first process.
If your first run already fails, inspect report.txt and confirm that you created a fresh lab directory. Do not delete a report in your real project to make this demonstration pass.
Give Claude a repair boundary
Start claude from the lab directory and paste:
Read report.py and test_report.py. The test passes on the first
run in an empty directory and fails on the second run because
report.txt contains two alpha lines. Explain where the state lives.
Repair only test_report.py. Keep report.py unchanged: append_report
must append to report.txt in the current working directory and
preserve existing lines. Keep test_one_line and its assertion.
Use pytest tmp_path plus monkeypatch.chdir to give each test its
own working directory. Add test_append_keeps_existing_line,
which seeds existing\n, appends beta, and checks existing\nbeta\n.
Do not delete or truncate report.txt in the project directory.
Do not skip tests or relax assertions. Run the suite twice and
then run the two tests in reverse order. Report commands, exit
codes, observed results and the exact file changed.
Anthropic’s common workflows recommend supplying debugging context and verifying fixes with tests. The edit boundary here is our exercise design. Review the resulting diff before accepting it.
A patch that changes the application’s file mode from "a" to "w" would hide the symptom by breaking the append contract. A patch that deletes the project report before every test could destroy useful data. Neither is the repair this lab asks for.
Compare with the reference repair
A complete reference test_report.py is:
from pathlib import Path
from report import append_report
def test_one_line(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
append_report("alpha")
assert Path("report.txt").read_text(encoding="utf-8") == "alpha\n"
def test_append_keeps_existing_line(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
Path("report.txt").write_text("existing\n", encoding="utf-8")
append_report("beta")
assert Path("report.txt").read_text(encoding="utf-8") == "existing\nbeta\n"
Pytest’s tmp_path fixture supplies a directory unique to each test function, represented by a pathlib.Path. Requesting the fixture alone does not move relative writes into it. The test must pass that path to the application, or, for this current-directory interface, change directory before calling it.
monkeypatch.chdir changes the working directory; pytest undoes the monkeypatch changes after the test or requesting fixture finishes. Both the application call and the assertion therefore address the same isolated file.
Temporary files may remain available for inspection after a run under pytest’s retention policy. Isolation does not mean immediate deletion, and it is not a security sandbox.
Prove the project file survives
In this disposable lab only, replace the deliberately generated report with a fictional owner-note sentinel:
printf 'owner note\n' > report.txt
.venv/bin/python -m pytest -q test_report.py
.venv/bin/python -m pytest -q test_report.py
.venv/bin/python -m pytest -q \
test_report.py::test_append_keeps_existing_line \
test_report.py::test_one_line
.venv/bin/python - <<'PY'
from pathlib import Path
actual = Path("report.txt").read_text(encoding="utf-8")
assert actual == "owner note\n", repr(actual)
print("project report unchanged")
PY
The local reference produced two passes on each of the three pytest commands, all with exit code 0. A separate check confirmed the sentinel was unchanged, and report.py remained byte-for-byte identical to the baseline.
These checks cover different mistakes:
| Check | What it catches |
|---|---|
| Same test command twice | Reuse of output left by a previous process |
| Append test with an existing line | A repair that silently truncates reports |
| Reverse test order | Dependence on the other test’s setup |
| Owner-note sentinel | Tests that still write into the project directory |
If the real project still fails
If tmp_path is present but the project report changes, check whether the test actually changes directory before calling the writer. Also look for an absolute output path or a path computed during module import. Changing directory later cannot redirect an already stored absolute path.
For an application that accepts an output path, pass tmp_path / "report.txt" directly. That avoids changing process-wide working-directory state. This lab uses chdir because the existing function explicitly writes relative to the working directory; it is not a recommendation for concurrent threads sharing that process.
Keep the failing second-run result alongside the repaired runs. The useful handoff is specific: the application kept its append contract, each test received separate files, and the project report survived. A single green run cannot establish all three.
Sources
Checked December 1, 2026. Test results are from the authored local fixture, not a Claude Code performance claim.
- pytest: temporary directories and files — per-test paths and temporary-directory retention.
- pytest: monkeypatch — working-directory changes and automatic undo.
- Anthropic: common workflows — debugging context and test-based verification.
Put this to work
Why tmp_path alone does not redirect relative file writes.
Try
Pair a per-test temporary directory with monkeypatch.chdir in a disposable Python lab.
Prove it worked
Run two tests twice and in reverse order, then check that an owner-note sentinel survives.
Keep in view
- Reproduce a test that passes once and fails when repeated.
- Scope a Claude Code repair to test setup, preserving append behavior.
- Verify repeat runs, reversed order and an untouched existing file.