Sub topic 5
Covering edge cases with parametrized tests
This chapter assumes you can run pytest, read a decorator, and review a diff. It builds on the earlier chapters about giving the assistant context and generating first unit tests. The running subject is the apply_discount function from the Topic Spine.
Why edge cases need a deliberate request
An assistant that sees apply_discount(100, 10) in a docstring will happily write that one case and stop. Most real defects sit at the edges of the input space: zero, the largest allowed value, the first invalid value, and values that stress rounding. You get those cases only if you ask for them and then check that you got them.
Parametrization helps with this. The pytest.mark.parametrize decorator runs one test function once for each row of a table. Each row is reported as its own test. This has three effects:
- The assertion logic is written once, so there is little for a reviewer to read.
- Adding a case costs one line, so the assistant has no reason to skip marginal cases.
- A failing row is named in the report, so you see which input broke.
Deriving the edge-case table
Before you prompt, list the boundaries yourself. For apply_discount the contract says price must be non-negative and percent must be in the range 0 to 100 inclusive.
A useful rule is to test each boundary on both sides. At the upper limit that means 100 (valid), 100.01 (invalid), and one clearly invalid value such as 101. Do the same for price at 0 and just below 0. Then add categories that the boundaries do not cover:
- Zero price.
0is valid and the result should be0.0. - Rounding. Choose inputs whose exact result has more than two decimals.
- Type mix. Pass an
intprice and afloatprice. - Check order. If both arguments are invalid, the code raises for the price first. A test can pin that down, if you want it to be part of the contract.
Prompting for the table
Ask for the categories by name and tell the assistant how to derive the expected values. The expected-value rule is the part people forget. If the model calculates expected values by running the same arithmetic as the function, the test cannot fail.
Extend tests/test_pricing.py for apply_discount.
Use pytest.mark.parametrize with pytest.param(..., id="...") so every row
has a readable id. Use two tables: one for valid inputs, one for invalid
inputs with the expected error message.
Cover:
- percent at 0 and 100, and just outside them (-0.01, 100.01)
- price at 0 and just below 0 (-0.01)
- at least two inputs where the exact result has more than two decimals
- both arguments invalid at once
Expected values must be written as literals that you worked out by hand
from the docstring. Do not compute them with the function's own formula.
List any case where the docstring does not say what should happen.The last line matters. It asks the assistant to report gaps in the contract rather than guess. Anything it lists is a question for the code owner, not a test to write.
A complete parametrized test file
This version uses pytest.param ids, match on the error message, and the boundary values from the diagram.
import pytest
from pricing import apply_discount
@pytest.mark.parametrize(
"price, percent, expected",
[
pytest.param(100, 10, 90.0, id="typical"),
pytest.param(80, 25, 60.0, id="exact-quarter"),
pytest.param(19.99, 0, 19.99, id="zero-percent-unchanged"),
pytest.param(50, 100, 0.0, id="full-discount"),
pytest.param(0, 50, 0.0, id="zero-price"),
pytest.param(10, 33, 6.7, id="rounds-down-to-one-decimal"),
pytest.param(9.99, 15, 8.49, id="rounds-to-two-decimals"),
],
)
def test_apply_discount_valid(price, percent, expected):
assert apply_discount(price, percent) == expected
@pytest.mark.parametrize(
"price, percent, message",
[
pytest.param(-1, 10, "price must be non-negative", id="negative-price"),
pytest.param(-0.01, 10, "price must be non-negative", id="barely-negative-price"),
pytest.param(10, -5, "percent must be between 0 and 100", id="negative-percent"),
pytest.param(10, -0.01, "percent must be between 0 and 100", id="barely-negative-percent"),
pytest.param(10, 100.01, "percent must be between 0 and 100", id="barely-over-100"),
pytest.param(10, 101, "percent must be between 0 and 100", id="over-100"),
pytest.param(-1, 101, "price must be non-negative", id="both-invalid-price-first"),
],
)
def test_apply_discount_invalid(price, percent, message):
with pytest.raises(ValueError, match=message):
apply_discount(price, percent)Run it with pytest tests/test_pricing.py -v. Each id appears in the report, for example test_apply_discount_valid[full-discount]. To run a single row, use pytest -k "full-discount".
Notice what the second function does that the version in the Topic Spine does not. It checks the message with match, so a test for the percent error cannot pass because the price check fired instead. Without match, (10, -5) and (-5, 10) are indistinguishable.
Exact equality and floating-point values
Every expected value above is compared with ==. That works here because the function ends with round(..., 2), which returns the float nearest to a two-decimal value, and your literal is the same float. It would fail for a function that returns unrounded results. In that case, compare with pytest.approx:
import pytest
def test_unrounded_result_needs_approx():
assert 0.1 + 0.2 == pytest.approx(0.3)Ask the assistant to say why it chose == or approx for each table. If it cannot justify the choice from the code, treat the choice as a guess.
What to look for when reviewing the table
Generated parametrized tests tend to fail in a small number of ways. Check for these before you accept the output.
| Problem | How it looks | What to do |
|---|---|---|
| Expected value copied from the code | A row contains `100 * (1 - 10 / 100)` instead of `90.0` | Replace it with a hand-derived literal |
| Boundary on one side only | `100` is tested but `100.01` is not | Add the missing side |
| Cartesian explosion | Two stacked `parametrize` decorators produce every combination | Use one table of tuples unless you want all pairs |
| Duplicate rows | Two ids test the same partition | Delete one, or replace it with an untested category |
| Vague ids | `case1`, `case2` | Rename them to describe the property under test |
| Silent expectation | A row that expects no error where the docstring is silent | Raise it as a question |
The stacked-decorator case is easy to miss. Two decorators with 4 and 5 values produce 20 tests, and a failure message names only the combination. This is occasionally what you want, for example when you test a pure function across two independent flags. Most of the time it is accidental.
Finding what the contract does not say
A good edge-case table surfaces gaps. Consider apply_discount(float("nan"), 10). The price check price < 0 is false for NaN, so the function returns nan without raising. The docstring says nothing about this. The same call with percent=float("nan") raises, because 0 <= nan <= 100 is false.
Do not let the assistant lock in either behavior silently. A test such as assert math.isnan(apply_discount(float("nan"), 10)) would pass today and would turn an accident into a requirement. Decide what the behavior should be, change the code or the docstring, and then write the test. If you decide to leave it open, leave the case out and record the question in the pull request.
Refining the table with feedback
The first output rarely needs a full rewrite. Targeted follow-ups work better:
- Paste the failing row's id and the real output, and ask whether the expected value or the code is wrong. Do not accept "fix the test" without the reasoning.
- Ask for the table to be reduced to the rows that each represent a distinct partition, with a one-line reason per row.
- Ask for a list of categories the table does not cover, then pick from the list yourself.
Keep the decision about what the function should do with you. The assistant can enumerate inputs quickly, but it cannot know which behavior your callers depend on.
Summary of the workflow
- Write down the partitions and both sides of each boundary.
- Prompt with the categories, the id requirement, and the no-recomputation rule.
- Check each table for the problems in the review table above.
- Mutate the code briefly to confirm that boundary rows can fail.
- Resolve any gap the assistant reported before encoding it in a test.
Exercise
The assistant gives you this test for applydiscount. Name two problems and say how you would fix each. @pytest.mark.parametrize("price", [10, 20]) @pytest.mark.parametrize("percent", [0, 50, 100]) def testdiscount(price, percent): assert apply_discount(price, percent) == round(price * (1 - percent / 100), 2)
Show answer
First, the expected value re-implements the function's formula, so the test passes whenever the code and the test share the same mistake. Replace it with a table of hand-derived literals such as (10, 50, 5.0) and (20, 100, 0.0). Second, the stacked decorators generate six combinations with no ids and no invalid inputs, so no ValueError path or just-outside boundary (-0.01, 100.01) is tested. Use one table of pytest.param rows with ids for the valid cases, and a second table with pytest.raises and match for the error paths.