Skip to content

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.

20 min read0/8 questions

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".

The test pyramid
  1. End-to-end testsa real browser or client against the deployed app. Few, slow, brittle
  2. Integration testsseveral parts together: API + database. Some
  3. Unit testsone function or class in isolation. Many, fast (milliseconds)

Most of your tests should be unit tests: tiny, fast, precise. When one fails, you know exactly where to look.

1/3

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.

src/shop/pricing.py
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)
tests/test_pricing.py
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:

Python
def apply_discount(price, percent): if not 0 <= percent <= 100: raise ValueError("percent must be between 0 and 100") return round(price * (1 - percent / 100), 2) def test_ten_percent_off(): assert apply_discount(50.0, 10) == 45.0 def test_rounding(): assert apply_discount(10.0, 33) == 6.7, "expected 6.7" def test_bug_on_purpose(): assert apply_discount(100.0, 50) == 40.0, "half of 100 should be 50" # a five-line "test runner"for name, fn in list(globals().items()): if name.startswith("test_"): try: fn() print("PASS", name) except AssertionError as e: print("FAIL", name, "-", e)
Output
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 test

When 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 =========================
Quick check
Which function will pytest collect and run by default?
Need a nudge? A hint rules out a wrong answer.

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.

tests/test_cart.py
# 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() == 360

When 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.

Quick check
Which test name will help most when it fails in CI at 2am?
Need a nudge? A hint rules out a wrong answer.

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.

tests/test_prices.py
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.5

Three details catch people:

  • match= is a regular expression, searched with re.search anywhere in the message. Dots, brackets, + and parentheses are special. Use re.escape(...) for literal text.
  • Keep the with block to the one line that should raise. Any line after the raising one inside the block never runs, so an assert placed 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.value is the actual exception, so you can assert on its attributes (an HTTP error's status_code, a validation error's field name) after the block.

Here is what those two context managers check underneath, in plain Python:

Python
import reimport warnings def parse_price(text): if text.startswith("$"): warnings.warn("'$' prefix is deprecated, send a number", DeprecationWarning, stacklevel=2) text = text[1:] value = float(text) if value < 0: raise ValueError(f"price must be >= 0 (got {value})") return value # What pytest.raises(ValueError, match=...) checks: re.search on str(exc)try: parse_price("-5")except ValueError as exc: message = str(exc)print(message)print(bool(re.search("must be >= 0 (got -5.0)", message))) # ( ) is a regex groupprint(bool(re.search(re.escape("must be >= 0 (got -5.0)"), message))) # escaped: literal text # What pytest.warns(DeprecationWarning) checks: a matching warning was issuedwith warnings.catch_warnings(record=True) as caught: warnings.simplefilter("always") print(parse_price("$3.50"))print([(w.category.__name__, str(w.message)) for w in caught])
Output
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:

pyproject.toml
[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.

Quick check
A test reads: 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?
Need a nudge? A hint rules out a wrong answer.

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.

tests/conftest.py
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()
tests/test_cart.py
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() == 400

Each 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.

Put it in order4 steps

Order what happens when pytest runs test_query(db) with a yield fixture.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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 a pathlib.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 .out and .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.
tests/test_export_cli.py
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 the pairs0/4 matched

Match each test need to the built-in fixture that handles it.

Choose an item, then its match on the other side.

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.

tests/test_slugify.py
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) == expected

That 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.

tests/test_signup.py
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:

Python
from unittest.mock import Mock def checkout(cart_total, payments): if cart_total <= 0: return "nothing to pay" receipt = payments.charge(cart_total, currency="USD") return f"paid, receipt {receipt}" payments = Mock()payments.charge.return_value = "r-123" # what the fake returns print(checkout(500, payments))payments.charge.assert_called_once_with(500, currency="USD")print("charge was called with:", payments.charge.call_args) payments.reset_mock()print(checkout(0, payments), "| called:", payments.charge.called)
Output
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.

Quick check
You are unit testing a function that fetches a user from an HTTP API and formats their name. What should you mock?
Need a nudge? A hint rules out a wrong answer.

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:

Python
from unittest import mock class CartV1: def __init__(self): self.items = [] def add(self, name, price, qty=1): self.items.append((name, price, qty)) def _line_total(self, item): _, price, qty = item return price * qty def total(self): return sum(self._line_total(i) for i in self.items) class CartV2(CartV1): def total(self): # refactor: same behaviour, helper inlined return sum(price * qty for _, price, qty in self.items) def test_total_behaviour(cart_cls): cart = cart_cls() cart.add("pen", 150, qty=2) cart.add("pad", 400) assert cart.total() == 700 def test_total_implementation(cart_cls): cart = cart_cls() cart.add("pen", 150, qty=2) cart.add("pad", 400) with mock.patch.object(cart_cls, "_line_total", autospec=True, side_effect=CartV1._line_total) as spy: cart.total() assert spy.call_count == 2, "expected _line_total to be called twice" for cls in (CartV1, CartV2): for test in (test_total_behaviour, test_total_implementation): try: test(cls) print(f"PASS {test.__name__:28} {cls.__name__}") except AssertionError as e: print(f"FAIL {test.__name__:28} {cls.__name__} - {e}")
Output
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, None where 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.
Quick check
A refactor renames a private helper _calc_tax to _tax_for. Nothing a caller can observe changes, but 12 tests fail. What does that tell you?
Need a nudge? A hint rules out a wrong answer.

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-missing

Test-driven development (TDD) flips the order: write a failing test first, then the code. The loop is short, minutes at most:

Put it in order4 steps

Put the TDD cycle in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

The challenges below work the same way: our tests are already written, and your job is to make them pass.

ChallengeMedium

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 é into e plus an accent mark, and .encode("ascii", "ignore") drops the mark.
  • Every run of characters that are not a-z or 0-9 becomes 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"
Python
import reimport unicodedata def slugify(text: str) -> str: pass
ChallengeEasy

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 time

Our tests pass fake clocks, exactly like a test using a fixture or monkeypatch would.

Python
from collections.abc import Callablefrom datetime import datetime def greeting(now: Callable[[], datetime] = datetime.now) -> str: pass
Key terms
unit test
A fast test of one function or class in isolation, with external dependencies faked.
fixture
A @pytest.fixture function providing setup (and optional teardown via yield), injected by parameter name.
parametrize
@pytest.mark.parametrize runs 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.