Sub topic 11
Add a Regression Test and Record the Root Cause
This chapter assumes you can run pytest, commit with git, and have a fix that already passes. The goal is to make sure the bug stays fixed and that you understand why it happened.
What a regression test protects
A regression is a bug that returns after it was fixed. It usually comes back when someone changes nearby code, or when an assistant "improves" a function and drops a check. A regression test is a test written from a real failure. It fails on the broken code and passes on the fixed code.
Your earlier reproduction is the best starting point. The failing call average([]) is already the test case.
Write the test from the reproduction
Start from the fixed function:
def average(values):
if not values:
raise ValueError("average() requires at least one value")
return sum(values) / len(values)Then write two tests. One covers the bug. The other covers normal input, so a future change cannot break the common case while passing the bug check.
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([])Check that the bug test can fail. Temporarily remove the if not values: check and run pytest. The empty-list test should fail, because ZeroDivisionError is not a ValueError. Restore the check and run again. A test you have never seen fail may not test anything.
Make the test specific
A good regression test names the exact behavior. Compare these two assertions:
pytest.raises(Exception)accepts almost any failure, including a typo in your own code.pytest.raises(ValueError, match="at least one value")accepts only the error you chose and its message.
def test_average_of_empty_list_message():
with pytest.raises(ValueError, match="at least one value"):
average([])Be careful with tests an assistant writes for you. It may produce a test that mirrors the implementation, or one that asserts whatever the code currently does, including wrong behavior. Read each assertion and ask whether it states what the code should do.
Record the root cause
The symptom was ZeroDivisionError. The root cause is that average assumed its input was never empty and nothing enforced that assumption. Writing this down helps you find the same mistake in other functions, such as a median or percentage helper that divides by a count.
Put the explanation where future readers will see it: the commit message, and the pull request description if you use one.
Reject empty input in average()
average([]) raised ZeroDivisionError because len(values) is 0.
Root cause: the function assumed non-empty input without checking it.
Fix: raise ValueError with a clear message for empty input.
Test: test_average_of_empty_list_raises fails before this change.
Follow-up: check other helpers that divide by len().Ask the assistant to draft this message if you like, but check it against what you observed. It should state the cause you verified, not a plausible guess.
Commit the test with the fix
Use version control to keep the pair together:
- Run the full test suite, not only the new tests.
- Stage the fix and the test.
- Commit with the root-cause message.
Keeping them in one commit means anyone who reverts the fix also reverts the test, and the history shows what the test was written for.
| Step | Question to answer |
|---|---|
| Reproduce | Does a test fail for the reported reason? |
| Fix | Does the same test now pass? |
| Guard | Do the other tests still pass? |
| Record | Does the commit explain the cause? |
Exercise
You add a regression test for a bug, and it passes on the first run, before you apply any fix. What does this tell you, and what should you do?
Show answer
The test does not detect the bug, so it gives no protection. Check that it exercises the failing input and asserts the correct behavior, then rewrite it until it fails on the broken code. Only after that, apply the fix and confirm the test passes.
Exercise
A function percentage(part, total) divides by total. Using the lesson on root causes, name one follow-up action after fixing average.
Show answer
Check whether percentage has the same unchecked assumption (total could be 0). If so, write a failing test for percentage(1, 0), then fix it the same way.