Testing with pytest
Course contents (15 lessons)
- Iteration the Python way
- List, dict and set comprehensions
- Iterators and generators
- Functions as building blocks
- Closures and decorators
- Context managers and the with statement
- Object-oriented Python in depth
- Classes and dataclasses
- Properties and special (dunder) methods
- Inheritance versus composition
- Quality: types, packaging and tests
- Type hints and mypy
- Packaging a project with pyproject.toml
- Testing with pytest
- Async code and web APIs
- async and await with asyncio
- Working with HTTP APIs and JSON
- Performance, concurrency and a final project
- Performance and profiling
- Concurrency: threads versus processes
- Final project: a price tracker command-line tool
Why tests
A test is a small program that checks your code and fails loudly when the result is wrong. Without tests, every change is a gamble. You fix one thing and break another and find out from a customer. With tests, you find out in two seconds.
Python has unittest built in, but most people use pytest. Tests are plain functions with plain assert statements, and the failure messages are very readable. Install it with pip install pytest.
The code under test
# src/invoicer/calc.py
def with_tax(amount: float, rate: float = 0.17) -> float:
if amount < 0:
raise ValueError("amount cannot be negative")
return round(amount * (1 + rate), 2)
def apply_discount(amount: float, percent: float) -> float:
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return round(amount * (1 - percent / 100), 2)
Your first tests
# tests/test_calc.py
import json
import pytest
from invoicer.calc import apply_discount, with_tax
def test_with_tax_default_rate():
assert with_tax(1000) == 1170.0
def test_with_tax_zero_rate():
assert with_tax(250, rate=0) == 250.0
@pytest.mark.parametrize(
"amount, percent, expected",
[
(1000, 0, 1000.0),
(1000, 10, 900.0),
(1000, 100, 0.0),
(80, 25, 60.0),
],
)
def test_apply_discount(amount, percent, expected):
assert apply_discount(amount, percent) == expected
def test_negative_amount_is_rejected():
with pytest.raises(ValueError, match="negative"):
with_tax(-1)
@pytest.fixture
def invoice_file(tmp_path):
path = tmp_path / "invoice.json"
path.write_text(json.dumps({"amount": 1000, "percent": 20}), encoding="utf-8")
return path
def test_discount_from_file(invoice_file):
data = json.loads(invoice_file.read_text(encoding="utf-8"))
assert apply_discount(data["amount"], data["percent"]) == 800.0
Run the tests from the project folder:
pytest
pytest -v
pytest tests/test_calc.py::test_apply_discount
How pytest finds and runs things
Pytest looks for files named test_*.py and for functions whose names start with test. If an assert fails, pytest shows the values on both sides, so you rarely need a debugger to see what went wrong. If your module is not found, install the package with pip install -e . as in the packaging lesson.
parametrize runs one test function several times with different data. Each row shows up as its own test, so you can see exactly which case failed. pytest.raises checks that code raises the expected exception. The match argument is a regular expression checked against the message. If no exception happens, the test fails.
Fixtures
A fixture is a function that prepares something a test needs, such as a file, a database connection or sample data. A test asks for it by adding the fixture's name as a parameter. Pytest ships with useful ones: tmp_path gives a fresh temporary folder for each test, so tests never touch your real files. Fixtures can also clean up after themselves with yield:
@pytest.fixture
def db():
conn = open_test_database()
yield conn # the test runs here
conn.close() # cleanup
Put fixtures that several files need in a file called conftest.py. Pytest loads it automatically.
Replacing parts of the system
When code reads an environment variable or the clock, tests become unpredictable. The monkeypatch fixture replaces things for one test only and puts them back afterwards.
import os
def tax_rate() -> float:
return float(os.environ.get("TAX_RATE", "0.17"))
def test_tax_rate_from_environment(monkeypatch):
monkeypatch.setenv("TAX_RATE", "0.05")
assert tax_rate() == 0.05
For replacing objects with fakes, use unittest.mock from the standard library, for example mock.patch. Be careful with mocks, though. A test that mocks everything proves only that your mocks work.
What to test
- Normal cases, boundary values (0, 100, empty list) and error cases.
- Bugs you have fixed. Write a test that fails on the old code, then fix it.
- Behaviour, not implementation. If a test breaks every time you rename an internal variable, it tests the wrong thing.
Common mistakes
- Comparing floats with ==. Use
pytest.approx:assert result == pytest.approx(0.3). - Tests that depend on each other. Each test should work alone and in any order.
- Testing against real services. Network calls make tests slow and flaky. Isolate them.
- Naming a file without test_ prefix, so pytest silently finds nothing.
- Putting several unrelated asserts in one test, so the first failure hides the others.
Try it yourself
Add a function split_bill(total, people) that returns what each person pays and raises ValueError if people is less than 1. Write at least five tests with parametrize, including the error case. Then run pytest --cov after installing pytest-cov and see which lines your tests do not cover.
# tests/test_calc.py
import json
import pytest
from invoicer.calc import apply_discount, with_tax
def test_with_tax_default_rate():
assert with_tax(1000) == 1170.0
def test_with_tax_zero_rate():
assert with_tax(250, rate=0) == 250.0
@pytest.mark.parametrize(
"amount, percent, expected",
[
(1000, 0, 1000.0),
(1000, 10, 900.0),
(1000, 100, 0.0),
(80, 25, 60.0),
],
)
def test_apply_discount(amount, percent, expected):
assert apply_discount(amount, percent) == expected
def test_negative_amount_is_rejected():
with pytest.raises(ValueError, match="negative"):
with_tax(-1)
@pytest.fixture
def invoice_file(tmp_path):
path = tmp_path / "invoice.json"
path.write_text(json.dumps({"amount": 1000, "percent": 20}), encoding="utf-8")
return path
def test_discount_from_file(invoice_file):
data = json.loads(invoice_file.read_text(encoding="utf-8"))
assert apply_discount(data["amount"], data["percent"]) == 800.0
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account