Sub topic 11
Add a Regression Test and Record the Root Cause
This chapter covers what to do after a fix passes. You will turn the one-off check into a permanent regression test and write down why the bug happened. It assumes you can run pytest, use git, and have already followed the workflow in earlier chapters: read the error, reproduce it, prompt the assistant, apply one change, and verify.
Why a passing fix is not the end
A fix that works today can break again. Someone refactors average, a new caller passes an empty list, or a merge restores an old version. A regression is a bug that returns after it was fixed. A regression test is an automated test that fails if the bug comes back.
The reproduction you built earlier is already most of the test. The assistant can help write the rest, but you decide what the test must guarantee.
The second job is learning. If you only paste the fix and move on, you repeat the same class of mistake later. Recording the root cause turns one bug into knowledge the team keeps.
Start from the reproduction
Recall the failing function from the earlier chapters:
def average(values):
return sum(values) / len(values)
print(average([]))The fix rejects empty input with an explicit error:
def average(values):
if not values:
raise ValueError("average() requires at least one value")
return sum(values) / len(values)The reproduction was average([]). A regression test keeps that exact input, but states the expected behavior as an assertion instead of something you read from a terminal.
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([])The file has two tests, and each has a different job.
test_average_of_empty_list_raisesis the regression test. It fails on the old code, because the old code raisesZeroDivisionError, which is not aValueError.test_average_of_numbersguards the normal path. It stops a future "fix" from breaking correct behavior, for example by makingaverageraise on every input.
Prove the test can fail
A test you have never seen fail proves little. It may pass for the wrong reason, such as a typo in the import or an assertion that is always true. Check it against the broken code before trusting it.
- Stash or revert the fix, so
averageis the original version. - Run the new test and confirm it fails for the expected reason.
- Restore the fix and confirm it passes.
With git, the steps look like this.
git stash push stats.py
pytest test_stats.py -q
git stash pop
pytest test_stats.py -qOn the original code, the first run should report a failure in test_average_of_empty_list_raises. The failure message should name ZeroDivisionError. If the test passes on the broken code, it does not test the bug, and you must fix the test before going further.
The same check works when the assistant writes the test. Assistants often produce tests that pass immediately, because they were written against the already-fixed code and never exercised the failure.
The workflow in one view
What a good regression test looks like
A regression test earns its place when it is specific, small, and tied to the original failure.
Pin the behavior, not the implementation
The test should describe what callers can rely on. It should not describe how the function works inside. Asserting that average([]) raises ValueError is a behavior. Asserting that a particular if statement exists is not.
Check the error precisely
pytest.raises(ValueError) accepts any ValueError. If a later change raises a ValueError for an unrelated reason, the test still passes. Add match to check the message:
import pytest
from stats import average
def test_average_of_empty_list_explains_the_problem():
with pytest.raises(ValueError, match="at least one value"):
average([])The trade-off is brittleness. A test tied to exact wording breaks when someone improves the message. Match on a stable fragment, not the whole sentence.
Cover the neighbors of the bug
The original bug was about empty input. Other inputs share the same root cause, which is that the function assumed a non-empty sequence. Parametrized tests cover them cheaply:
import pytest
from stats import average
@pytest.mark.parametrize("empty", [[], (), set()])
def test_average_rejects_empty_collections(empty):
with pytest.raises(ValueError, match="at least one value"):
average(empty)This runs three cases from one test function. Add only the cases that follow from the root cause. Stacking dozens of unrelated cases makes the suite slow and hides which case matters.
Name the test after the bug
A name like test_average_of_empty_list_raises tells the next reader what broke. If your team tracks issues, add the issue number in a comment so the history is easy to find.
Using the assistant to write the test
The assistant is good at the typing part and weaker at deciding what matters. Give it the facts and the constraints.
Here is stats.py after the fix, and the original traceback.
Write a pytest regression test for the bug: average([]) used to raise
ZeroDivisionError and now must raise ValueError.
Requirements:
- One test for the empty-list case, using pytest.raises with a match.
- One test that a normal list still returns the right average.
- Do not change stats.py.
- Tell me how to confirm the test fails on the original code.The last line matters. It makes the assistant describe the verification step, and you then run it yourself.
Review what comes back for these common problems:
- The test calls a mock or a helper instead of the real function, so it can never fail.
- The assertion is too loose, such as
assert result is not None. - The test edits
stats.pyor changes the expected value to match the new output. - The test imports something that does not exist in your project.
Record the root cause
A root cause is the underlying reason a bug exists, as opposed to the symptom you saw. The symptom here is ZeroDivisionError: division by zero. The root cause is that average assumed its input is never empty and nothing enforced that assumption.
The distinction matters for two reasons. A fix aimed at the symptom, such as returning 0 for an empty list, hides the problem. And naming the cause lets you search for the same mistake elsewhere, for example in median or weighted_average.
Where to write it down
Use the places your team already reads:
- The commit message is the minimum. It travels with the code and shows up in
git logandgit blame. - The pull request description can carry more detail and links.
- The issue tracker is the right place if the bug was reported by someone else.
- A code comment is useful only when the reason would surprise a future reader.
A commit message that carries the cause
Reject empty input in average()
average([]) raised ZeroDivisionError because len(values) is 0.
Root cause: the function assumed a non-empty sequence and nothing
checked that assumption, so callers got an unrelated arithmetic error.
Fix: raise ValueError with a clear message for empty input.
Test: test_average_of_empty_list_raises fails on the old code
(ZeroDivisionError) and passes now.Four things appear in the message: the symptom, the root cause, the fix, and the evidence. A reader six months later can judge whether a change is safe without rerunning the investigation.
You can ask the assistant to draft this from the diff and the traceback. Check the draft for claims you did not verify. Assistants sometimes state a cause with more confidence than the evidence supports, or describe a test as passing when no one ran it.
Look for the same mistake elsewhere
Once the cause is named, search for it. If the cause was "assumed non-empty input", this search finds likely siblings:
grep -rn "/ len(" --include="*.py" .Treat the results as leads. Each match needs a human decision. Some functions may handle empty input correctly already, and some may need their own regression test. Fix them in separate commits, so each change stays small and reviewable.
Edge cases and gotchas
- Flaky tests. A regression test that sometimes fails is worse than none. Avoid depending on time, random values, network access, or test order. If the original bug depended on one of these, control it. For example, fix the random seed or inject a fake clock.
- Bugs that need heavy setup. If reproducing the bug needs a database or a service, write the smallest test that captures the faulty logic. Move the logic into a plain function if necessary, then test that function directly.
- Bugs you cannot test. Some failures involve hardware, timing, or production-only data. Record the root cause and the manual check you performed, and say plainly that no automated test exists.
- Tests that encode the wrong behavior. If the real requirement is that
average([])returns0.0, the test above locks in the wrong contract. Settle the intended behavior before writing the test. - Test location. Put the test next to existing tests for the same module and follow the project's naming pattern, so the test runner finds it.
A short checklist
| Step | Question to answer | Evidence |
|---|---|---|
| Write | Does the test use the original reproduction input? | The input appears in the test |
| Fail | Does it fail on the broken code for the expected reason? | Failure output names the original error |
| Pass | Does it pass on the fixed code? | Green test run |
| Guard | Does a normal-input test still pass? | Green test run |
| Record | Does the commit state symptom, cause, fix, and test? | Commit message |
| Search | Does the same cause exist elsewhere? | Search results reviewed |
Exercise
You asked an assistant to write a regression test for the average([]) fix. You run the new test against the original, unfixed code and it passes. What does that tell you, and what should you do?
Show answer
It means the test does not exercise the bug, so it is not a regression test. Typical causes are that the test calls a different function or mock, that the assertion is too loose, or that the test was written to match the fixed code. Do not commit it. Rewrite the test so it uses the original input average([]) and asserts ValueError. Then run it on the original code again and confirm it fails with ZeroDivisionError before restoring the fix.
Exercise
Write a commit message body for a fix where average([]) now raises ValueError. Include the symptom, the root cause, and the evidence. Then say why "return 0 for an empty list" would be a worse fix.
Show answer
Example: "average([]) raised ZeroDivisionError because len(values) is 0. Root cause: the function assumed non-empty input and nothing enforced it. Fix: raise ValueError with a clear message. Test: testaverageofemptylist_raises fails on the old code and passes now." Returning 0 hides the bug. The caller cannot tell an empty input from a real average of zero, so wrong results flow downstream without any error.
Exercise
The root cause of a bug was "the function assumed non-empty input". Name one way to find other places with the same problem, and one reason to fix them in separate commits.
Show answer
Search the codebase for the pattern, for example grep -rn "/ len(" --include="*.py" ., or review other functions that compute statistics over a sequence. Review each match by hand. Separate commits keep each change small, make review easier, and let you revert one change without losing the others.