Sub topic 7
Reviewing generated tests before you trust them
An assistant can produce a test file in seconds. A passing test file is not evidence that the code works. This chapter covers how to review generated tests so you keep the ones that protect you and discard the ones that only look busy.
This chapter assumes you can read and run pytest tests, use pytest.mark.parametrize and pytest.raises, and review a diff in Git. It builds on the traits of a good test and on the prompt and parametrization techniques from earlier chapters.
Why generated tests need their own review
A generated test is written by a system that has read your code. That creates a specific risk. The assistant can see what the function does, so it may write assertions that confirm what the code does instead of what it should do. If the code has a bug, a test derived from the code can encode the bug and pass.
Three failure patterns come up repeatedly:
- Tautological tests. The expected value is computed with the same logic as the code under test, so the test cannot fail.
- Weak tests. The test runs the code but asserts almost nothing, so many bugs pass through.
- Gaps. Each test is fine, but the set misses a boundary, an error path, or a branch.
Review means looking for all three. The workflow below goes from cheap checks to expensive ones.
The subject under test
The examples use the same function as the rest of the tutorial. Save it as pricing.py.
def apply_discount(price: float, percent: float) -> float:
"""Return price reduced by percent, rounded to two decimals.
Raises ValueError if price is negative or percent is outside 0-100.
"""
if price < 0:
raise ValueError("price must be non-negative")
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return round(price * (1 - percent / 100), 2)Suppose the assistant returns this file, saved as tests/test_pricing.py:
import pytest
from pricing import apply_discount
def test_discount_runs():
result = apply_discount(100, 10)
assert result is not None
def test_discount_matches_formula():
price, percent = 80, 25
expected = round(price * (1 - percent / 100), 2)
assert apply_discount(price, percent) == expected
def test_negative_price():
with pytest.raises(Exception):
apply_discount(-1, 10)
def test_percent_out_of_range():
apply_discount(10, 101)It looks reasonable and the first three tests pass. The fourth one fails, which is the only honest result in the file. Each test has a distinct problem.
Step 1: Read each test for independence
For every assertion, ask where the expected value came from. There are three acceptable sources: the docstring or specification, a value you can compute by hand, or a known reference such as a fixture file. An unacceptable source is a copy of the implementation.
test_discount_matches_formula repeats the implementation. If someone changed the formula to price * percent / 100, the test would still need updating in the same way, and a wrong formula copied into both places would pass. Replace it with values derived by hand: 80 reduced by 25 percent is 60.0.
A quick test is to cover the function body and ask whether you could write the expected value from the docstring alone. If you could not, the assistant probably leaned on the code.
Step 2: Look for weak assertions
A weak assertion lets many wrong behaviors pass. Look for these:
| Smell | Example | Why it is weak | Fix |
|---|---|---|---|
| No assertion | Calls the function, asserts nothing | Passes unless the code crashes | Assert on the result or the side effect |
| Existence check | `assert result is not None` | Any return value passes | Assert the exact value |
| Broad exception | `pytest.raises(Exception)` | A `TypeError` from a typo also passes | Use `ValueError` and `match=` |
| Type-only check | `assert isinstance(result, float)` | A wrong number of the right type passes | Assert the value |
| Loose tolerance | `assert result == pytest.approx(90, abs=10)` | Hides real errors | Use the tightest tolerance the spec allows |
| Overpatched mock | Every collaborator is mocked, including the logic under test | Tests the mock | Mock only the boundary |
Two points on exceptions. First, pytest.raises(ValueError, match="percent") checks both the type and the message, so a swapped error branch is detected. Second, the single-argument call in test_percent_out_of_range raises ValueError inside the test, so it fails. That is lucky. A test with no pytest.raises and no assertion for a path that does not raise would pass silently.
Step 3: Run the tests, and read the failures
A failing generated test has two possible causes. The test may be wrong, or the code may be wrong. Do not let the assistant "fix" the test by making it match the code without deciding which one is right.
When a test fails:
- Compare the failing expectation with the docstring or specification.
- If the specification supports the test, the code has a bug. Fix the code.
- If the specification contradicts the test, the test is wrong. Fix the test.
- If the specification is silent, you have found an undocumented behavior. Decide the behavior, write it into the docstring, then settle the test.
Step 4 is a common source of value from this exercise, because generated tests tend to probe the exact places a specification is vague.
Step 4: Measure coverage, and know what it means
Coverage reports which lines or branches ran during the tests. With the pytest-cov plugin installed:
pytest --cov=pricing --cov-branch --cov-report=term-missing tests/test_pricing.pyCoverage can prove a test is missing. It cannot prove a test is good. A test with no assertions can reach 100 percent coverage. Use coverage to find branches no test reaches, then check that the tests reaching them assert something meaningful.
Step 5: Mutate the code and see whether tests notice
A mutation check changes the code on purpose and runs the tests. If the tests still pass, they do not protect that behavior. This is the most direct test of whether assertions matter.
You can do it by hand for a few high-value edits. The commands below use GNU sed; on macOS use sed -i '' or edit the file manually.
cp pricing.py pricing.py.bak
sed -i 's/0 <= percent <= 100/0 <= percent < 100/' pricing.py
pytest -q tests/test_pricing.py
mv pricing.py.bak pricing.pyIf the test file contains a case with percent equal to 100 that expects 0.0, this mutation fails it. Good. Now try changing price < 0 to price <= 0. The original test file passes with that change, because no test uses a price of exactly 0. That surviving mutation shows a gap at a boundary.
Tools such as mutmut automate this by generating many mutations. They are slow on large code bases, so start by hand on the functions that matter most, such as money, permissions, and parsing.
A reviewed version
After review, the test file might look like this. Each expected value is derived from the docstring or computed by hand.
import pytest
from pricing import apply_discount
@pytest.mark.parametrize(
"price, percent, expected",
[
(100, 10, 90.0),
(80, 25, 60.0),
(19.99, 0, 19.99),
(50, 100, 0.0),
(0, 10, 0.0),
(19.99, 15, 16.99),
],
)
def test_returns_expected_price(price, percent, expected):
assert apply_discount(price, percent) == expected
@pytest.mark.parametrize("price", [-0.01, -1, -100])
def test_rejects_negative_price(price):
with pytest.raises(ValueError, match="price"):
apply_discount(price, 10)
@pytest.mark.parametrize("percent", [-0.01, -5, 100.01, 101])
def test_rejects_percent_out_of_range(percent):
with pytest.raises(ValueError, match="percent"):
apply_discount(10, percent)The changes map back to the review steps:
- The formula-copying test is gone, so no test repeats the implementation.
price == 0is covered, so the<=mutation is caught.- A rounding case,
(19.99, 15, 16.99), checks the two-decimal rule. The unrounded result is 16.9915. - Each error test uses
match=, so the two error branches cannot be swapped without a failure. - Values just outside the range (
-0.01,100.01) test the boundaries more tightly than101alone.
Other things worth checking
- Test names. A name like
test_discount_runssays nothing. A failing name should tell you what behavior broke. - Hidden dependencies. Tests that read the clock, the environment, or the network are flaky. Generated tests sometimes call real services. Replace them with mocks, as covered in the previous chapter.
- Order dependence. Run with
pytest -p no:randomlyand again with random ordering if you usepytest-randomly. Shared state between tests is a common generated-test flaw. - Floating-point comparisons. Exact
==is acceptable for values derived by hand that round cleanly. For computed floats usepytest.approx. - Production changes. Check the diff. An assistant asked for tests may also modify the function. Your prompt should forbid it, and your review should confirm it.
Common review errors
- Accepting the file because every test is green.
- Reading only the first few tests of a long parametrized table and trusting the rest.
- Trusting coverage numbers as a quality score.
- Checking that tests pass on the code but never that they fail on broken code.
- Keeping tests you do not understand. If you cannot say what bug a test would catch, delete it or rewrite it.
Exercise
A generated test reads expected = round(price * (1 - percent / 100), 2) and then asserts apply_discount(price, percent) == expected. The test passes. Name the problem and give two ways to fix it.
Show answer
The test is tautological: it recomputes the answer with the implementation's own formula, so it passes even if the formula is wrong. Fix it by replacing the computed expectation with hand-derived literals from the docstring (for example, 80 at 25 percent is 60.0), either in a parametrized table or as a single assertion. A second fix is to check against an independent reference, such as values from the specification or a stored fixture, and then confirm the test fails when you mutate the formula.
Exercise
You change price < 0 to price <= 0 in apply_discount and every test in the original generated file still passes. What does that tell you, and what test closes the gap?
Show answer
It shows that no test covers the boundary price of exactly 0, so that mutation survives. Add a case such as (0, 10, 0.0) to the expected-value table. It passes on the original code and fails on the mutated code, because the mutated code raises ValueError for a price of 0.