Part 11 / Topic 5 of 12
pytest features
pytest.raises: test that an error happens
Like checking that the ATM really refuses a wrong PIN.
import pytest
from shop import apply_discount
def test_apply_discount_rejects_bad_percent():
with pytest.raises(ValueError, match="discount must be 0-100"):
apply_discount(1000, 120)
The test passes only if a ValueError is raised inside the with block. match= checks the error message (it is a regex, Part 8).
@pytest.mark.parametrize: one test, many inputs
Like one exam question asked with different numbers. A decorator (Part 10) on top of the test gives it a list of inputs; pytest runs it once per row.
import pytest
from shop import apply_discount
@pytest.mark.parametrize(
("percent", "expected"),
[(0, 1000), (10, 900), (50, 500), (100, 0)],
)
def test_apply_discount(percent, expected):
assert apply_discount(1000, percent) == expected
This counts as 4 tests. If one row fails, the report shows which: test_apply_discount[50-500].
Fixtures: reusable test data
A fixture is a function marked with @pytest.fixture that prepares data for tests. A test asks for it simply by using its name as a parameter. Each test gets a fresh copy, so one test cannot spoil another.
Like a lab assistant who sets up clean equipment before every experiment.
import pytest
from shop import cart_total
@pytest.fixture
def cart():
return [
{"name": "Notebook", "price": 60, "qty": 5},
{"name": "Pen", "price": 20, "qty": 10},
]
def test_cart_total(cart): # pytest calls cart() and passes the result
assert cart_total(cart) == 500
tmp_path: a fresh temporary folder
tmp_path is a fixture built into pytest. It gives each test its own new, empty folder (a Path, Part 8), so tests never touch your real files.
from shop import load_cart, save_cart
def test_save_then_load(tmp_path):
path = tmp_path / "cart.json"
cart = [{"name": "Pen", "price": 20, "qty": 2}]
save_cart(path, cart)
assert load_cart(path) == cart
pytest.approx: compare floats safely
Floats are stored in binary, so tiny rounding errors appear (Part 2). == then fails even though the answer is "right".
import pytest
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
print(0.1 + 0.2 == pytest.approx(0.3)) # True
print(99.99 * 1.18) # 117.98819999999999
print(99.99 * 1.18 == pytest.approx(117.9882)) # True
Add abs=0.01 to allow a fixed difference, e.g. pytest.approx(10_379.18, abs=0.01) for money.
All of these are used in tests/test_shop.py.
๐ Going deeper: a fixture can
yieldinstead ofreturn; the code afteryieldruns after the test (clean-up). Put fixtures inconftest.pyto share them across many test files.
Done here? The practice set for Part 11 โ 7 exercises with solutions โ is on the part page.