Lesson 48 of 52Real projects
Testing with pytest
Write fast, readable tests with pytest using asserts, fixtures, parametrize and mocks, and work in a TDD loop.
Tests are how you change code without fear. With a good test suite you can refactor, upgrade a library or fix a bug on a Friday afternoon and know within seconds whether you broke something. Every professional Python team uses pytest, take-home projects without tests get rejected, and "how would you test this?" is asked in nearly every interview.
Why tests, and what kind
An automated test is code that runs your code with known inputs and checks the outputs. It turns "I think it works" into "it works, and here is the proof, re-checked on every commit".
Most of your tests should be unit tests: tiny, fast, precise. When one fails, you know exactly where to look.
Test functions and assert
pytest keeps it simple. A test is a function whose name starts with test_, in a file named test_*.py. Inside, you use Python's plain assert statement. No special assertion methods to memorise.
def apply_discount(price: float, percent: float) -> float:
if not 0 <= percent <= 100:
raise ValueError("percent must be between 0 and 100")
return round(price * (1 - percent / 100), 2)import pytest
from shop.pricing import apply_discount
def test_ten_percent_off():
assert apply_discount(50.0, 10) == 45.0
def test_zero_percent_changes_nothing():
assert apply_discount(19.99, 0) == 19.99
def test_rejects_bad_percent():
with pytest.raises(ValueError, match="between 0 and 100"):
apply_discount(10.0, 150)pytest.raises is a context manager that passes only if the block raises that exception. A good test has three parts, often called Arrange, Act, Assert: set up the inputs, call the code, check the result.
The code windows here cannot run pytest itself, but assert is plain Python, so you can see the idea:
Press Run (⌘ Enter) to see what happens.Running pytest
uv add --dev pytestuv run pytest # find and run every testuv run pytest tests/test_pricing.py::test_rejects_bad_percent # just oneuv run pytest -k discount # tests whose name matches "discount"uv run pytest -x # stop at the first failureuv run pytest -v # one line per testWhen an assert fails, pytest rewrites it to show you both sides:
def test_bug_on_purpose():
> assert apply_discount(100.0, 50) == 40.0
E assert 50.0 == 40.0
E + where 50.0 = apply_discount(100.0, 50)
tests/test_pricing.py:14: AssertionError
========================= 1 failed, 2 passed in 0.03s =========================Arrange, Act, Assert, and names that explain failures
Six months from now, someone (probably you) will see a red test in CI and need to understand it in under a minute. Two habits make that possible.
The first is Arrange-Act-Assert: every test has three blocks, separated by a blank line. Arrange builds the inputs. Act calls the one thing under test, usually a single line. Assert checks the outcome. When a test does not fit this shape, it is usually testing two behaviours at once and should be split.
# Hard to read: setup, calls and checks are interleaved
def test_cart():
c = Cart()
c.add("pen", 150)
assert c.total() == 150
c.add("pad", 400)
c.apply_coupon("TEN")
assert c.total() == 495
c.remove("pen")
assert c.total() == 360
# One behaviour per test, three clear blocks
def test_coupon_takes_ten_percent_off_the_total():
cart = Cart()
cart.add("pen", 150)
cart.add("pad", 400)
cart.apply_coupon("TEN")
assert cart.total() == 495
def test_removing_an_item_keeps_the_coupon():
cart = Cart()
cart.add("pen", 150)
cart.add("pad", 400)
cart.apply_coupon("TEN")
cart.remove("pen")
assert cart.total() == 360When the first version fails on its third assert, you learn that "something about carts" broke, and the asserts after it never ran, so you do not know whether removal also broke. When the second version fails, the test name already tells you which behaviour regressed. "One behaviour per test" does not mean "one assert per test": checking the status code and the body of one response is still one behaviour.
The second habit is names that read like a specification. Good names describe the condition and the expected outcome: test_rejects_percent_above_100, test_empty_cart_total_is_zero, test_expired_token_returns_401. Bad names describe the code: test_apply_discount_2, test_edge_case, test_bug_fix. Run pytest -v on a well-named suite and the output reads as a list of what the system promises. Some teams use a fixed pattern such as test_<unit>_<condition>_<result>. Any consistent pattern beats none.
Testing exceptions and warnings
Error paths are where bugs hide, because the happy path gets tested by hand every day and the error path only runs when something goes wrong. Test both.
import re
import pytest
from shop.prices import parse_price
def test_negative_price_is_rejected():
with pytest.raises(ValueError, match=r"must be >= 0") as excinfo:
parse_price("-5")
assert "-5.0" in str(excinfo.value) # the exception object itself
def test_message_with_regex_characters():
with pytest.raises(ValueError, match=re.escape("must be >= 0 (got -5.0)")):
parse_price("-5")
def test_dollar_prefix_still_works_but_warns():
with pytest.warns(DeprecationWarning, match="prefix is deprecated"):
assert parse_price("$3.50") == 3.5Three details catch people:
match=is a regular expression, searched withre.searchanywhere in the message. Dots, brackets,+and parentheses are special. Usere.escape(...)for literal text.- Keep the
withblock to the one line that should raise. Any line after the raising one inside the block never runs, so anassertplaced there passes silently by never executing. And if an earlier line raises the same exception type by accident, the test passes for the wrong reason. excinfo.valueis the actual exception, so you can assert on its attributes (an HTTP error'sstatus_code, a validation error's field name) after the block.
Here is what those two context managers check underneath, in plain Python:
Press Run (⌘ Enter) to see what happens.Warnings deserve one more setting. Your dependencies emit DeprecationWarning months before they remove something. pytest shows them in a summary at the end of the run, where everyone learns to ignore them. Many teams turn them into failures so they get fixed while the fix is small:
[tool.pytest.ini_options]
filterwarnings = [
"error", # every warning fails the test
"ignore::DeprecationWarning:some_old_library.*", # except this known one, for now
]You can try the same thing once from the command line with pytest -W error::DeprecationWarning. Errors and Exceptions covers the warnings module from the library author's side.
with pytest.raises(ValueError): then two lines inside the block, parse_price("-5") and assert audit_log == ["rejected -5"]. The audit log is actually empty. What happens?Fixtures: reusable setup
Many tests need the same setup: a sample cart, a temporary folder, a test database. A fixture is a function decorated with @pytest.fixture. A test asks for it simply by naming it as a parameter, and pytest calls the fixture and passes in the result. This is dependency injection.
import pytest
from shop.cart import Cart
@pytest.fixture
def cart():
c = Cart()
c.add("pen", 150)
c.add("pad", 400)
return c
@pytest.fixture
def db():
conn = connect_to_test_database()
yield conn # the test runs here
conn.rollback() # teardown runs after, even if the test failed
conn.close()def test_total(cart): # pytest injects the fixture
assert cart.total() == 550
def test_remove(cart): # a FRESH cart for every test
cart.remove("pen")
assert cart.total() == 400Each test gets a fresh fixture value, so tests cannot leak state into each other. Put shared fixtures in conftest.py; pytest finds them automatically. Fixtures with yield do teardown after the test, just like @contextmanager. pytest also has built-in fixtures, such as tmp_path (a temporary Path per test) and monkeypatch.
Order what happens when pytest runs test_query(db) with a yield fixture.
- Tap the steps below in the right order.
Three built-in fixtures you will use weekly
pytest ships fixtures for the outside world. You ask for them by name like your own. These three cover most everyday needs:
tmp_path: a fresh, empty directory as apathlib.Path, unique to each test. Write files there instead of into the repo, and tests cannot trip over each other's leftovers.capsys: captures what the code printed.capsys.readouterr()returns an object with.outand.err, and resets the capture.monkeypatch: sets attributes, dict items and environment variables, or changes the working directory, and undoes all of it when the test ends, pass or fail.
from shop import export_cli
def test_export_writes_file_and_reports_count(tmp_path, capsys, monkeypatch):
monkeypatch.setenv("SHOP_CURRENCY", "EUR")
out_file = tmp_path / "orders.csv"
exit_code = export_cli.main(["--out", str(out_file)])
assert exit_code == 0
assert out_file.read_text(encoding="utf-8").startswith("id,total,currency\n")
captured = capsys.readouterr()
assert captured.out == f"exported 3 orders to {out_file}\n"
assert captured.err == ""Notice how the test reads: one fixture per kind of outside world, then the same Arrange-Act-Assert shape. Design follows from this. A main(argv) that takes its arguments as a list and returns an exit code is trivially testable; one that reads sys.argv and calls sys.exit deep inside is not. Scripting and Automation shows that shape in full.
For the rest of the built-in fixtures (caplog for log records, request for parametrized fixtures, fixture scopes and conftest.py layering), see pytest in Depth in the Python Backend course. For faking time, randomness, HTTP calls and subprocesses, Testing Code That Touches the Outside World picks up where this section stops.
Match each test need to the built-in fixture that handles it.
parametrize: one test, many cases
Instead of copy-pasting a test for each input, list the cases and let pytest generate one test per row. Each row passes or fails on its own in the report.
import pytest
from shop.text import slugify
@pytest.mark.parametrize(
("raw", "expected"),
[
("Hello World", "hello-world"),
(" trim me ", "trim-me"),
("Café & Bar", "cafe-bar"),
("", ""),
],
)
def test_slugify(raw, expected):
assert slugify(raw) == expectedThat produces four tests, named like test_slugify[Hello World-hello-world]. Edge cases (empty input, whitespace, unicode) become one more line each, so you actually write them.
Mocking: replacing the outside world
Unit tests must not send real emails, charge real cards or depend on the current time. Mocking means swapping a real dependency for a fake during a test. pytest's monkeypatch fixture replaces an attribute or environment variable and restores it afterwards. unittest.mock (standard library) gives you Mock objects that record how they were called.
from shop import signup
def test_sends_welcome_email(monkeypatch):
sent = []
monkeypatch.setattr(signup, "send_email", lambda to, body: sent.append(to))
monkeypatch.setenv("APP_ENV", "test")
signup.register("ada@example.com")
assert sent == ["ada@example.com"]unittest.mock runs anywhere, so try it:
Press Run (⌘ Enter) to see what happens.The cleanest code to test takes its dependencies as parameters (like payments above) instead of importing and calling them directly. Then a test just passes a fake in; no patching needed.
What to test: behaviour, not implementation
The most expensive test suite is not the one with too few tests. It is the one where every refactor breaks forty tests that were checking how the code works instead of what it does. Teams with suites like that stop refactoring, and the code rots.
A test checks behaviour when it goes through the public interface (call the function, call the endpoint) and asserts on the observable result: the return value, the saved row, the response, the email that was "sent" to a fake. It checks implementation when it asserts on private helpers, internal call counts, or the exact sequence of internal steps. Watch both kinds of test meet a harmless refactor:
Press Run (⌘ Enter) to see what happens.The behaviour test passed before and after. The implementation test failed on code that is exactly as correct as before. That is a false alarm, and every false alarm teaches the team to distrust red builds. A test should fail when the behaviour breaks and stay green when it does not.
So where do the tests go? Look back at the pyramid at the top of this lesson. Its point is cost: unit tests are cheap enough to cover every rule and edge case, a smaller set of integration tests proves the pieces fit, and a few end-to-end tests guard the journeys that make money. Some teams draw a different shape (more integration tests, fewer units) for apps that are mostly glue between a framework and a database. The shape matters less than the principle: test each behaviour at the cheapest level that can actually catch its bugs.
For each unit, a reliable checklist of cases:
- Typical input: the case everyone thinks of.
- Boundaries: zero, one, the maximum, exactly at a limit (
percent=100), just past it (100.01). - Empty and missing: empty string, empty list,
Nonewhere it is allowed. - Invalid input: wrong type, negative quantity, malformed date. Assert the error.
- Real-world mess: Unicode names, leading spaces, very long strings.
- Every bug you fix: write the failing test first, then the fix. That test is the proof the bug cannot quietly return.
_calc_tax to _tax_for. Nothing a caller can observe changes, but 12 tests fail. What does that tell you?Organisation, coverage and the TDD loop
Mirror your source tree: src/shop/services/pricing.py is tested in tests/services/test_pricing.py. Name tests after the behaviour they check (test_rejects_negative_quantity), so a failing name tells you what broke.
Coverage measures which lines your tests executed. It is a useful flashlight for untested code, but 100% coverage does not mean correct code: a line can run without its result ever being checked.
uv add --dev pytest-covuv run pytest --cov=shop --cov-report=term-missingTest-driven development (TDD) flips the order: write a failing test first, then the code. The loop is short, minutes at most:
Put the TDD cycle in order.
- Tap the steps below in the right order.
The challenges below work the same way: our tests are already written, and your job is to make them pass.
Make the slugify tests pass
The tests are already written (like a parametrize table). Write slugify(text) to make them pass. A slug is the URL-friendly form of a title.
- Lowercase everything.
- Turn accented letters into plain ASCII (
é→e). Hint:unicodedata.normalize("NFKD", text)splitséintoeplus an accent mark, and.encode("ascii", "ignore")drops the mark. - Every run of characters that are not
a-zor0-9becomes a single-. - No
-at the start or end.
slugify("Hello, World!") # "hello-world"
slugify(" Café & Bar ") # "cafe-bar"
slugify("Déjà vu 2026") # "deja-vu-2026"Inject the clock
Code that calls datetime.now() directly is hard to test: the result changes every time you run it. The fix is dependency injection: take the clock as a parameter, defaulting to the real one, so tests can pass a fake.
Write greeting(now=datetime.now), where now is a function returning a datetime:
- hour 5 to 11 →
"Good morning" - hour 12 to 17 →
"Good afternoon" - hour 18 to 21 →
"Good evening" - otherwise (22 to 4) →
"Good night"
greeting(lambda: datetime(2026, 1, 1, 9, 30)) # "Good morning"
greeting() # depends on the real timeOur tests pass fake clocks, exactly like a test using a fixture or monkeypatch would.
- unit test
- A fast test of one function or class in isolation, with external dependencies faked.
- fixture
- A
@pytest.fixturefunction providing setup (and optional teardown viayield), injected by parameter name. - parametrize
@pytest.mark.parametrizeruns one test function over many input rows.- mock
- A stand-in object that replaces a real dependency and records how it was called.
- monkeypatch
- A pytest fixture that temporarily replaces attributes or environment variables and restores them after the test.
- TDD
- Test-driven development: red (failing test), green (make it pass), refactor, repeat.
- Arrange-Act-Assert
- Structuring a test as setup, one action, then checks, each as its own block.
- pytest.raises
- A context manager that passes only if its block raises the given exception;
match=is a regex searched in the message. - behaviour test
- A test that uses the public interface and checks observable results, so it survives refactors.