Sub topic 2
Covering Edge Cases with Parametrized Tests
Assume you know basic Python, pytest, Git, and code review. Treat an AI assistant’s tests as drafts. The assistant can suggest cases, but you must decide what the function should guarantee.
Covering Edge Cases with Parametrized Tests
Parametrization runs the same test with several input rows. It keeps related cases together and makes boundary coverage visible.
For apply_discount, test ordinary values, both valid boundaries, and each documented error path:
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)Derive expected values from the documented contract. Do not calculate the expected result by calling the same implementation or copying its formula into the test.
Isolating External Dependencies with Mocks
A mock is a test object that replaces a dependency. Use one when a test should not make a network request, write to a real service, or depend on changing external data.
from unittest.mock import Mock
def get_username(client, user_id):
response = client.get(f"/users/{user_id}")
return response.json()["name"]
def test_get_username_reads_name_from_response():
client = Mock()
client.get.return_value.json.return_value = {"name": "Ada"}
assert get_username(client, 7) == "Ada"
client.get.assert_called_once_with("/users/7")The test checks both the returned value and the request sent to the client.
Reviewing Generated Tests Before You Trust Them
Check that generated tests:
- assert behavior, rather than merely executing code;
- include documented boundaries and every error path;
- use expected values independent of the implementation;
- verify important calls made to dependencies;
- fail when you deliberately break the production code.
Passing tests measure only the cases they contain. They do not prove that undocumented behavior is correct.
Generating Docstrings from Code
Ask the assistant to describe arguments, return values, exceptions, and runnable examples. Then run the examples with python -m doctest. Update the docstring when the implementation changes.
Exercise
What is missing if generated tests cover 10 and 25 percent discounts but omit 0 percent, 100 percent, and invalid percentages?
Show answer
Boundary and error-path coverage is missing. Add parametrized cases for 0, 100, values below 0, and values above 100.