Sub topic 4
Generating your first unit tests
This chapter assumes you can write and run pytest tests, use Git, and have used an AI chat or coding assistant. You will write a prompt, read the tests it produces, and run them against a small function.
The function under test
The running subject is apply_discount. Its docstring defines the contract: a price and a percent go in, a rounded price comes out, and two inputs raise ValueError.
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 at the project root.
Build the prompt from four parts
A vague request such as "write tests for this" gives you generic output. A useful prompt names four things:
- Framework and layout. Say that the project uses pytest and where the file lives.
- Import line. Give the exact import so the assistant does not guess a module path.
- Coverage expectations. List the cases you want: normal values, boundaries, and every error path.
- Constraints. Forbid the habits you do not want, such as changing the code or copying its logic into the assertions.
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>The constraint about deriving expected values matters most. If the assistant computes the expected value with the same formula as the function, the test passes even when the formula is wrong. That kind of test is a tautology.
What the assistant might return
A response to this prompt could look like the following.
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)Save this as tests/test_pricing.py and run pytest. Each expected value was worked out by hand: 10% off 100 is 90, and 25% off 80 is 60. The cases 19.99, 0 and 50, 100 cover the lower and upper boundaries of percent. The second test covers a negative price, a negative percent, and a percent above 100.
Passing is not the same as correct
A green run tells you the tests agree with the code today. It does not tell you they agree with the contract. Before you commit, check three things:
- Each expected value comes from the docstring, not from running the function and pasting its output.
- Each error path has its own case. Here there are two
raisestatements, so the invalid-input cases must trigger both a bad price and a bad percent. - Each test would fail if you broke the code. Change
1 - percent / 100to1 + percent / 100, rerun, and confirm that tests fail. Then undo the change.
One gap remains in the sample output. The error test accepts any ValueError, so it cannot tell the two error messages apart. You can tighten it with pytest.raises(ValueError, match="percent"). Later chapters cover this kind of review in depth.
Exercise
You paste apply_discount into an assistant and ask only "write tests". It returns a test that computes the expected value with price * (1 - percent / 100) and asserts equality. Why is this a weak test, and what prompt constraint prevents it?
Show answer
The expected value is calculated with the same formula as the function, so the test passes even if that formula is wrong. Add a constraint such as "Assert on expected values you derive from the docstring, not by re-implementing the function", and ask for hand-worked values such as 10% off 100 equals 90.0.
Exercise
Name two checks you can run, beyond seeing a green pytest result, to confirm that generated tests are worth committing.
Show answer
Any two of: confirm each expected value traces to the docstring rather than to pasted output; confirm every raise statement has a test case; temporarily break the function (for example, flip the sign in the formula) and confirm that the tests fail.