Sub topic 4
Generating your first unit tests
This chapter walks through one complete cycle: pick a function, write a prompt, get tests from the assistant, and check that they are worth keeping. It assumes you can read and write Python, have run pytest before, know the basics of Git and code review, and have used an AI chat or coding assistant. It builds on the earlier chapters on what makes a test worth keeping and on giving the assistant context.
The subject under test
All examples use one small function with a documented contract and two error paths.
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)Save it as pricing.py in the project root. The tests will go in tests/test_pricing.py.
The workflow at a glance
Generating tests is a loop with a human at both ends. You decide what should be tested before you prompt. You decide whether the result is acceptable after you run it.
Step 1: Derive the cases yourself first
Before you open the assistant, read the docstring and write down what must be true. This list is your reference for judging the output later. If you skip it, you will end up judging the tests by whatever the assistant happened to produce.
For apply_discount the contract gives these cases:
| Case | Input (price, percent) | Expected |
|---|---|---|
| Typical value | 100, 10 | 90.0 |
| Another typical value | 80, 25 | 60.0 |
| Lower percent boundary | 19.99, 0 | 19.99 |
| Upper percent boundary | 50, 100 | 0.0 |
| Negative price | -1, 10 | ValueError |
| Percent below range | 10, -5 | ValueError |
| Percent above range | 10, 101 | ValueError |
Work out each expected value by hand from the docstring. 10% off 100 is 90. 25% off 80 is 60. Do not run the function to get the answers. A test whose expected value came from the code under test can only confirm that the code agrees with itself.
Also note one case the table leaves out on purpose: price == 0 is valid, because only negative prices are rejected. Keep it in mind for the review step.
Step 2: Write a prompt that carries the context
The assistant cannot see your project layout, your test framework, or your standards unless you tell it. A good first-test prompt supplies four things: the framework and file layout, the import line, the coverage you expect, and the constraints that block weak output.
Write pytest tests for the function below.
Context:
- Project uses pytest; tests live in tests/test_pricing.py.
- Import the function with: from pricing import apply_discount
- Use pytest.mark.parametrize for input/output tables.
Requirements:
- Cover normal values, the boundaries 0 and 100 for percent, and every ValueError path.
- Assert on expected values you derive from the docstring, not by re-implementing the function.
- Do not change the function under test.
<code of apply_discount here>Each line prevents a specific failure:
- The import line stops the assistant from guessing a module name such as
from utils import .... - The parametrize instruction produces a compact table of cases instead of a dozen near-identical functions.
- "Boundaries 0 and 100" and "every ValueError path" turn "good coverage" into something checkable.
- "Not by re-implementing the function" blocks tautological tests. Without it, an assistant may write
assert apply_discount(p, d) == round(p * (1 - d / 100), 2). That test passes against the current code and against any bug in it. - "Do not change the function" keeps a failing test from being "fixed" by editing the code.
Paste the real function source in place of the placeholder. If the function calls helpers or uses types defined elsewhere, include those too. The assistant will invent plausible definitions for anything it cannot see.
Step 3: Read what comes back
A typical result for this prompt looks like this.
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),
],
)
def test_apply_discount_returns_expected_price(price, percent, expected):
assert apply_discount(price, percent) == expected
@pytest.mark.parametrize("price, percent", [(-1, 10), (10, -5), (10, 101)])
def test_apply_discount_rejects_invalid_input(price, percent):
with pytest.raises(ValueError):
apply_discount(price, percent)Compare it with your table. All seven cases appear, the expected values match your hand-derived numbers, and nothing imports from a made-up module. The tests are split into a "returns" test and a "rejects" test, so a failure message tells you which kind of behavior broke.
The exact == comparison on floats is acceptable here because the function rounds to two decimals, and the literals in the table are already two-decimal values. If a function returned unrounded floats, you would compare with pytest.approx instead.
Step 4: Run the tests
From the project root:
python -m pytest -qUse python -m pytest rather than bare pytest. With a tests/ folder that has no __init__.py, bare pytest puts tests/ on the import path, not the project root, and from pricing import apply_discount can fail with ModuleNotFoundError. Running through python -m adds the current directory to the path. Alternatively, set pythonpath = ["."] under [tool.pytest.ini_options] in pyproject.toml.
A passing run looks like this:
....... [100%]
7 passed in 0.02sSeven results come from two test functions because each parametrized row counts as its own test.
When a generated test fails, decide which side is wrong before you change anything. Re-read the docstring. If the test contradicts the documented contract, the code has a bug. If the test asserts something the contract never promised, the test is wrong. Give the assistant the failure output and the contract, and ask it to correct the test. Do not tell it only "make the tests pass", because it may weaken the assertion to do so.
Step 5: Check that the tests can fail
Passing tests prove little until you know they would fail on broken code. Do a quick manual mutation check: introduce a small bug on purpose, run the tests, then undo it.
Change the range check in pricing.py from <= to <:
if not 0 <= percent < 100:Run python -m pytest -q. The row (50, 100, 0.0) should now fail with a ValueError, because 100 is suddenly rejected. That failure shows the upper-boundary case is doing its job. Revert the change.
Now try a mutation the suite might miss. Change price < 0 to price <= 0, so a free item is wrongly rejected. Run the tests again. All seven still pass, because no case uses a price of 0. This is the gap you noted in Step 1. Ask the assistant to add a case, or add the row yourself:
(0, 50, 0.0),Put it in the first parametrize table. Re-run the mutation and confirm the new row now fails. This is the kind of omission an assistant makes even when the prompt asks for boundaries. It tends to cover the boundaries the docstring names and skip those it implies.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ModuleNotFoundError: pricing` | Project root is not on the import path | Run `python -m pytest` or set `pythonpath` in pytest config |
| Tests pass but expected values look copied from the code | Assistant re-implemented the function | Add the "derive from the docstring" constraint and replace computed values with literals |
| Only happy-path tests | Prompt did not name error paths | List each `raises` condition in the prompt |
| Assistant edits `pricing.py` to make tests pass | No "do not change" constraint | Add it, and review the diff for non-test files |
| Float comparison fails by a tiny amount | Function returns unrounded floats | Use `pytest.approx` |
| `ValueError` test passes for the wrong reason | Test does not check which error fired | Add `match="price must be non-negative"` to `pytest.raises` |
The last row is worth acting on. In the generated tests, (-1, 10) and (10, 101) both raise ValueError, but the test cannot tell whether the right branch raised it. Adding match= pins the message and makes each error path distinguishable.
What the assistant does not guarantee
The assistant produces tests that look plausible for the code and prompt it saw. It does not run them unless it is wired to a terminal, and even then it does not know your intent beyond what you wrote. It can omit a boundary, assert a wrong expected value with full confidence, or test behavior the contract never promised. Your table from Step 1, the run from Step 4, and the mutation check from Step 5 are what turn a draft into something you can keep.
Exercise
A teammate asks an assistant for tests of apply_discount. It returns a test that computes the expected value with round(price * (1 - percent / 100), 2) and compares that to the function's result. The test passes. Why is it weak, and how would you fix it with a prompt change and a code change?
Show answer
The expected value comes from the same formula as the code, so any bug in the formula is copied into the test and the test still passes. Fix the prompt by adding "assert on expected values you derive from the docstring, not by re-implementing the function". Fix the test by replacing the computed value with literals worked out by hand, such as (100, 10, 90.0) and (80, 25, 60.0). Then confirm with a mutation check, for example changing the 100 divisor to 10, that the tests fail.
Exercise
The generated suite passes. You change if price < 0 to if price <= 0 in apply_discount and it still passes. What case is missing, and what row would you add to the first parametrize table?
Show answer
The suite never tests a price of 0, which the docstring treats as valid because only negative prices raise. Add the row (0, 50, 0.0) to the returns-expected-price table. With the mutated code it raises ValueError and the test fails, which shows the case now guards that boundary.