Sub topic 9
Verify the fix with a test
This chapter assumes you can run Python code and pytest from a terminal, use basic git commands (status, diff, stash, commit), and have already produced a candidate fix with an assistant. The earlier chapters covered reading the error, reproducing it, and judging the diagnosis. Here you decide whether the fix works.
A fix is a claim until you test it
An assistant's explanation of why a change works is text, and fluent text is not evidence. Code that looks right can fail in three ways:
- It fixes a different bug than the one you reported.
- It fixes your exact input but breaks a neighboring case.
- It hides the symptom, so the error disappears and the wrong behavior stays.
A test turns the claim "this is fixed" into something the machine can confirm or refute. The test you write for verification should also be one you can trust, which takes a few specific checks.
The verification loop
The loop has a fixed order. You write the test before you apply the fix, and you watch it fail first.
The first failing run matters most. If the test passes on the unfixed code, it does not detect the bug, and a passing result after the fix tells you nothing.
Worked example: the empty average
The reproduction from earlier chapters is a function that crashes on an empty list:
def average(values):
return sum(values) / len(values)
print(average([]))The failure is ZeroDivisionError: division by zero. Suppose the assistant proposes rejecting empty input explicitly. You decide this is the behavior you want, because callers should be told the input is invalid rather than see an arithmetic error from inside the function.
Before applying that change, write the test. Save the original function as stats.py and this file as test_stats.py:
import pytest
from stats import average
def test_average_of_numbers():
assert average([2, 4, 6]) == 4
def test_average_of_empty_list_raises():
with pytest.raises(ValueError):
average([])Remove the print(average([])) line from stats.py first. Otherwise, importing the module runs it and crashes at import time. This is a common trap when a reproduction script becomes a module.
Now run the tests against the unfixed code:
python -m pytest -qYou should see the normal-input test pass and the empty-list test fail:
.F [100%]
================================== FAILURES ===================================
____________________ test_average_of_empty_list_raises ______________________
def test_average_of_empty_list_raises():
with pytest.raises(ValueError):
> average([])
stats.py:2: ZeroDivisionError
1 failed, 1 passed in 0.03sThis is the result you want. The test fails because ZeroDivisionError is not a ValueError, which is the same reason the bug exists. The passing normal-input test also gives you a baseline for behavior that must not change.
Now apply the fix:
def average(values):
if not values:
raise ValueError("average() requires at least one value")
return sum(values) / len(values)Run the tests again:
python -m pytest -q.. [100%]
2 passed in 0.01sBoth tests pass. The failing-then-passing sequence is your evidence that this change, and not something else, caused the improvement.
What a verification test should cover
One test for the reported input is the minimum. A good set adds a few more, usually cheap to write.
| Case | Why it matters | Example |
|---|---|---|
| The reproduction | Proves the reported bug is gone | `average([])` raises `ValueError` |
| The normal path | Catches fixes that break working behavior | `average([2, 4, 6]) == 4` |
| Boundaries next to the bug | Catches off-by-one and partial fixes | `average([5]) == 5` |
| Input types the code accepts | Catches fixes that assume one type | floats, negative numbers |
| The error's contract | Pins down the message or type callers depend on | `match="at least one value"` |
For the average function, a more complete file looks like this:
import pytest
from stats import average
def test_average_of_numbers():
assert average([2, 4, 6]) == 4
def test_average_of_single_value():
assert average([5]) == 5
def test_average_of_floats():
assert average([1.5, 2.5]) == pytest.approx(2.0)
def test_average_of_negative_numbers():
assert average([-2, 2, -4]) == pytest.approx(-4 / 3)
def test_average_of_empty_list_raises():
with pytest.raises(ValueError, match="at least one value"):
average([])Two details are worth noting. pytest.approx avoids false failures from floating-point rounding. The match argument checks the message with a regular expression search, so a different ValueError raised for an unrelated reason would not satisfy the test.
Prove the test can fail against the old code
Sometimes you have already applied the fix before writing the test. You can still check the test by temporarily putting the old code back, without losing your work. With git, stash only the source file:
git stash push stats.py
python -m pytest -q
git stash popThe new empty-list test should fail while stats.py is stashed and pass again after git stash pop. If it passes while the fix is stashed, the test is not testing the fix.
Tests that pass for the wrong reason
Assistants write plausible tests quickly, and the same speed produces weak ones. Check generated tests for these problems:
- Too-broad exception checks.
pytest.raises(Exception)passes onZeroDivisionError, so it would pass on the unfixed code. Name the specific type you expect. - Mirroring the implementation. A test that recomputes
sum(values) / len(values)inside the assertion repeats the code under test. Use a hand-calculated expected value instead. - Over-mocking. If the test replaces the function that contains the bug with a mock, it verifies the mock. Mock only slow or external dependencies, such as network calls and clocks.
- Edited expectations. If the assistant changes an existing assertion so that the suite goes green, treat that as a red flag. Ask why the old expectation was wrong. Sometimes it was, but the change needs your explicit agreement.
- Skipped or deleted tests. Look for new
@pytest.mark.skip,xfail, or removed test functions in the diff. - No assertion. A test that calls the function and asserts nothing passes whenever nothing crashes.
Passing tests can still hide the bug
Consider a different "fix" for the same crash:
def average(values):
if not values:
return 0
return sum(values) / len(values)The crash is gone, and a test asserting average([]) == 0 would pass. But the average of nothing is undefined, and returning 0 lets bad data flow silently into later calculations. A test can only confirm the behavior you specified, so decide the intended behavior first. Here, your expected behavior from the debugging prompt was "a clear error telling the caller the input is empty." The test must encode that expectation, not whatever the new code happens to do.
Run more than the new test
After the new test passes, run the whole suite. A fix that changes a shared function can break callers elsewhere. For a larger project, run the new test first for a quick signal, then everything:
python -m pytest test_stats.py -q
python -m pytest -qIf the suite was already failing before your change, record that baseline first (python -m pytest -q on a clean checkout). Otherwise you cannot tell whether an unrelated failure is new.
Finally, inspect the change itself:
git diffThe diff should contain only what you intended: the fix and the new tests. Unrequested reformatting, renamed variables, and changed dependencies make the fix harder to review and are a common side effect of assistant edits.
Common errors when verifying
- Importing triggers the bug. Reproduction code left at module level runs on import. Move it under
if __name__ == "__main__":or delete it. - Testing the wrong copy. An installed package or a stale
.pycfile can shadow your edited source. Printstats.__file__in a quick check if results seem inconsistent. - Flaky confirmation. If the bug depended on timing, randomness, or ordering, one passing run proves little. Fix the random seed or run the test repeatedly, for example
python -m pytest --count=20with thepytest-repeatplugin installed. - Verifying only the happy path. The reported input passes, but a neighboring input still fails. Add the boundary cases from the table above.
Exercise
You apply an assistant's fix, then write a new test, and the test passes on the first run. Why is this not yet enough to conclude the bug is fixed, and what do you do next?
Show answer
The test may never have been able to fail. It might use too broad an assertion, mock away the buggy code, or not exercise the bug at all. Run it against the unfixed code, for example with git stash push <file>, and confirm it fails for the expected reason. Then restore the fix and confirm it passes.
Exercise
An assistant "fixes" a failing testaverageofemptylist_raises by changing the assertion to assert average([]) == 0 and making the function return 0 for empty input. List two problems with accepting this.
Show answer
First, the assistant rewrote the test to match new behavior, so the test no longer encodes your original expectation (a clear error for empty input). Second, returning 0 hides the invalid input, since the average of nothing is undefined, and downstream code will silently receive a wrong value. You should restore the original expectation or deliberately decide that the new behavior is correct.