Sub topic 2
What makes a test worth keeping
This chapter assumes you can write and run pytest tests, read a short Python function, and review a pull request in Git. It also assumes you have already asked an AI assistant for code at least once. Later chapters cover prompting and generating tests. This one defines the standard you will use to judge what the assistant gives you.
Why the standard comes first
An assistant can produce twenty tests in seconds. Most of them will pass on the first run. A passing run tells you the tests agree with the code. It does not tell you the tests would notice if the code were wrong.
A test is worth keeping if it fails when the behavior it protects breaks, and stays quiet otherwise. Every test you merge also costs something. It must be read, run on every commit, and updated when the code changes. A test that never catches a bug still carries all of those costs.
The traits of a worthwhile test
| Trait | Question to ask | What a violation looks like |
|---|---|---|
| Checks behavior | Would this fail if the function returned a wrong result? | No assertion, or `assert result is not None` |
| Independent expected value | Where did the expected value come from? | The test repeats the formula from the function |
| Specific | Does a failure point at one cause? | One test with ten unrelated assertions |
| Deterministic | Does it give the same result on every run? | Depends on the clock, random numbers, or network |
| Isolated | Can it run alone and in any order? | Relies on state left by another test |
| Fast | Does it finish in milliseconds? | Real HTTP calls, sleeps, real databases |
| Stable under refactoring | Does it survive a rewrite that keeps behavior? | Asserts on private calls or internal structure |
| Readable | Does the name state the rule being checked? | `test_1`, `test_function_works` |
Two of these deserve more attention because assistants break them most often.
An independent expected value
An assistant sees the function body before it writes the test. The easy way to get an expected value is to copy the logic from the body. The test then agrees with the code by construction. If the code has a bug, the copy has the same bug, and the test passes.
Derive expected values from the specification: the docstring, a ticket, a business rule, or arithmetic you can do by hand. A discount of 10% on 100 is 90. You do not need the function to know that.
Stability under refactoring
A test should describe what the code promises, not how it keeps the promise. If you rename a private helper and a test fails, that test was coupled to the implementation. Over-mocking causes this most often. A test that mocks every collaborator and then asserts the exact sequence of internal calls restates the implementation. The test that checks the returned value and the one outward-facing call that matters is more durable. Chapter "Isolating external dependencies with mocks" covers where mocks help.
A worked comparison
The running subject is the discount function from the plan. The file below holds the function, three weak tests, and three tests worth keeping. Save it as test_pricing_demo.py.
import pytest
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)
# --- Weak tests: all pass, none protect much ---
def test_runs_without_error():
apply_discount(100, 10)
def test_returns_something():
assert apply_discount(100, 10) is not None
def test_matches_formula():
price, percent = 80, 25
expected = round(price * (1 - percent / 100), 2)
assert apply_discount(price, percent) == expected
# --- Tests worth keeping ---
def test_ten_percent_off_one_hundred_is_ninety():
assert apply_discount(100, 10) == 90.0
@pytest.mark.parametrize(
"price, percent, expected",
[
(19.99, 0, 19.99),
(50, 100, 0.0),
],
)
def test_boundary_percentages_are_accepted(price, percent, expected):
assert apply_discount(price, percent) == expected
def test_negative_price_is_rejected_with_clear_message():
with pytest.raises(ValueError, match="non-negative"):
apply_discount(-1, 10)Run it with:
pytest -q test_pricing_demo.pyAll six tests pass. They are not equally useful.
test_runs_without_errorhas no assertion. It fails only if the function raises, so it would pass if the function always returned0.test_returns_somethingasserts that a value exists. Almost any return value satisfies it.test_matches_formulais a tautology. It rebuilds the function's expression in the test. If someone changed the formula toprice * (percent / 100), the real function and the expected value would need to be changed together to keep this test green, and nothing would tell you that the rule was wrong.test_ten_percent_off_one_hundred_is_ninetyuses a value you can verify in your head, and the name states the rule.- The boundary test checks
0and100, the two values where an off-by-one comparison would be wrong. - The error test uses
match, so it fails if the function raisesValueErrorfor the wrong reason, such as a typo in a different branch.
Checking a test by breaking the code
You can measure whether a test is worth keeping with a quick experiment. Introduce a small bug on purpose, run the tests, and see whether any fail. If none fail, the bug survived and your tests have a gap. This is the idea behind mutation testing, and you can do it by hand in a minute.
Try each change below, one at a time, in apply_discount:
- Change
0 <= percent <= 100to0 <= percent < 100. The(50, 100, 0.0)case fails. - Change
0 <= percentto0 < percent. The(19.99, 0, 19.99)case fails. - Change
price < 0toprice <= 0. No test in the file fails, because none uses a price of0. - Change
1 - percent / 100topercent / 100.test_ten_percent_off_one_hundred_is_ninetyfails.test_matches_formulaalso still fails here only because the function changed and the copied formula did not. Change both together and it passes again.
The third change is a surviving mutant. A price of 0 is a boundary the docstring allows, since only negative prices are rejected. Add (0, 50, 0.0) to the boundary table and the mutant is caught.
Weak tests tend to leave many mutants alive. When you review generated tests, picking two or three mutations to try is faster than reading every line closely.
Where the assistant tends to go wrong
These patterns show up often in generated tests. Look for them first.
- Copied logic. The expected value is computed with the same expression as the code under test.
- Happy path only. Three or four typical inputs and nothing at the boundaries or error paths.
- Assertions that cannot fail. Checks such as
assert result is not None,assert isinstance(result, float), orassert True. - Snapshots of current behavior. If the assistant ran the code to learn the output and pasted it in, a bug in the code is now recorded as correct. Check outputs against the docstring, not against a run.
- Unnecessary mocks. Pure functions such as
apply_discountneed no mock. Mocking collaborators that are cheap and deterministic makes tests brittle for no gain. - Exact-call assertions on internals. Tests that pin the number and order of calls to private helpers.
- Hidden shared state. Module-level variables or fixtures mutated by one test and read by another.
None of these are errors the interpreter reports. Your review is the only check.
A decision path for each test
Deleting is a legitimate outcome. A smaller suite of tests that all do something is better than a larger one padded with tests that cannot fail.
Applying the standard in your prompt
You can encode these traits as constraints so the assistant starts closer to the target. The plan's test-generation prompt includes lines such as "Assert on expected values you derive from the docstring, not by re-implementing the function" and "Do not change the function under test". These target the two worst failure modes directly: copied logic, and a quiet edit to the code to make a test pass.
A prompt does not replace review. The assistant can follow the instruction and still produce a weak test, so apply the checks above to the result.
A review checklist
Use this list on any batch of generated tests:
- Read each test name. Can you state the rule from the name alone?
- Find the expected value. Could you have written it from the docstring without running the code?
- Find the assertion. Would a plausible wrong result make it fail?
- List the inputs. Are the boundaries and every error path present?
- Count the mocks. Is each one standing in for something slow, nondeterministic, or external?
- Mutate the code in two or three places. Do the tests notice?
- Run the tests in random order or alone. Do they still pass?
Exercise
A generated test for apply_discount computes expected = price * (1 - percent / 100) inside the test and asserts apply_discount(price, percent) == expected for twenty random inputs. The test passes. Name the trait it violates, and describe one concrete bug it would fail to detect.
Show answer
It violates the independent expected value trait, because the test repeats the function's formula. It would fail to detect a wrong formula that was copied into both places, for example if the discount were meant to be applied as price * (percent / 100) and both the code and the test used price * (1 - percent / 100) incorrectly relative to the business rule. It also would not notice that the rounding to two decimals is missing from the expected value. The fix is to use hand-derived pairs such as (100, 10, 90.0) and (80, 25, 60.0).
Exercise
You change price < 0 to price <= 0 in apply_discount and the tests in test_pricing_demo.py all still pass. What does that tell you, and what single parametrized row would fix it?
Show answer
It means a mutant survived: the tests never check a price of exactly 0, which the docstring says is valid. Adding the row (0, 50, 0.0) to the boundary table makes the mutated function raise ValueError where the test expects 0.0, so the test fails and catches the change.