My account

Testing with pytest

With pytest, a test is a plain function with a plain assert. Fixtures give each test what it needs and clean up after it. Parametrize runs one test with many inputs. Mocks and monkeypatch replace slow or dangerous parts, but only if you replace the name where it is used. Most of all, every test must be isolated, so the suite passes in any order, alone or together.

Not reviewedWritten with AI helpReading time: 16 minOnline shop examplepytest code

Author: bezzad

Contents

The problem: tests that pass alone and fail together

The test suite of our online shop had three strange problems:

  1. Every test passed when run alone. But when the whole suite ran, two cart tests failed. They shared one global cart, and an earlier test left items in it.
  2. One test really called the payment provider. It was slow, and sometimes it failed because of the network.
  3. A developer mocked the payment function, but the real one was still called. The mock was on the wrong name.

This lesson shows how pytest helps with all three.

A test is a function with an assert

Put tests in files whose names start with test, and write functions whose names start with test. Use the normal assert statement:

# shop/pricing.py
from decimal import Decimal

def apply_coupon(total: Decimal, coupon: str | None) -> Decimal:
    if coupon is None:
        return total
    if coupon == "SAVE10":
        return (total * Decimal("0.9")).quantize(Decimal("0.01"))
    raise ValueError(f"unknown coupon: {coupon}")
# tests/test_pricing.py
from decimal import Decimal
import pytest
from shop.pricing import apply_coupon

def test_save10_gives_ten_percent_off():
    total = apply_coupon(Decimal("100.00"), "SAVE10")
    assert total == Decimal("90.00")

def test_unknown_coupon_is_rejected():
    with pytest.raises(ValueError, match="unknown coupon"):
        apply_coupon(Decimal("10.00"), "FREE")
  1. pytest rewrites assert statements. When one fails, it shows both values, so you do not need special methods like assertEqual.
  2. The pytest.raises block checks that the code raises this error. The match option also checks the message, with a regular expression.
  3. Test behavior, not internals. Check what comes out, not which private method was called.

Parametrize: one test, many cases

Instead of copying a test five times, give it a table of cases:

@pytest.mark.parametrize(
    ("total", "coupon", "expected"),
    [
        (Decimal("100.00"), None, Decimal("100.00")),
        (Decimal("100.00"), "SAVE10", Decimal("90.00")),
        (Decimal("19.99"), "SAVE10", Decimal("17.99")),
    ],
    ids=["no-coupon", "round-number", "rounding"],
)
def test_apply_coupon(total, coupon, expected):
    assert apply_coupon(total, coupon) == expected
  1. Each row becomes its own test. If one row fails, the others still run, and the report says which row failed.
  2. The ids option gives each row a readable name in the report.
  3. Add a row for each edge case you find in a bug report. The table becomes a list of rules that the code must keep.

Fixtures: what a test needs

A fixture is a function marked with the pytest.fixture decorator. A test asks for it by writing its name as a parameter. pytest runs the fixture first and passes in the result.

# tests/conftest.py
import pytest
from shop.cart import Cart

@pytest.fixture
def cart() -> Cart:
    return Cart()                    # a NEW cart for every test

@pytest.fixture
def cart_with_shoes(cart: Cart) -> Cart:
    cart.add("shoes", quantity=1)    # fixtures can use other fixtures
    return cart
# tests/test_cart.py
def test_new_cart_is_empty(cart):
    assert len(cart) == 0

def test_adding_the_same_item_twice(cart_with_shoes):
    cart_with_shoes.add("shoes", quantity=1)
    assert len(cart_with_shoes) == 2
  1. A file named conftest.py shares its fixtures with all tests in its folder and below. You do not import it.
  2. By default, a fixture runs again for every test (function scope). So every test gets a fresh cart. This alone fixes the first problem from the start of the lesson.
  3. A fixture with yield can clean up. The code after yield runs after the test, even if the test fails.
from sqlalchemy.orm import Session

@pytest.fixture
def db_session(engine):
    connection = engine.connect()
    transaction = connection.begin()
    session = Session(bind=connection)
    yield session                    # the test runs here
    session.close()
    transaction.rollback()           # undo everything the test wrote
    connection.close()

Fixture scope

A fixture can live longer than one test, with the scope option: function (the default), class, module, package or session.

One test run, three testsscope=sessionengine: made once, shared by every testscope=functiontest_atest_btest_ca new session for each test, rolled back after itSetup: code before yieldCleanup: code after yieldAnything a test can change belongs in function scope.
A session fixture is made once for the whole run. A function fixture is made and cleaned up again for every test. Keep anything that tests change in function scope.
  1. Use a wide scope for things that are slow to make and that tests do not change, like a database engine or a test container.
  2. Use function scope for anything a test can change, like a session, a cart or a temporary folder.
  3. A wide-scope fixture with changing state is the most common reason for tests that pass alone and fail together.

Built-in fixtures you will use often

  1. The tmp_path fixture gives each test its own new temporary folder, as a pathlib Path. Use it instead of writing files into the project.
  2. The monkeypatch fixture changes attributes, dict items and environment variables, and puts them back after the test.
  3. The capsys fixture captures what the code prints.
  4. The caplog fixture captures log records.
def test_reads_api_key_from_env(monkeypatch):
    monkeypatch.setenv("PAYMENT_API_KEY", "test-key")
    assert load_settings().payment_api_key == "test-key"
    # after the test, the variable is gone again

Mocks: replace the name where it is used

To test checkout without a real payment, replace the payment function. But where you replace it matters.

# shop/checkout.py
from decimal import Decimal
# the name "charge" now lives in shop.checkout too
from shop.payments import charge

def checkout(card_token: str, total: Decimal) -> str:
    payment_id = charge(card_token, total)
    return f"order paid with {payment_id}"
  1. The import line copies the name. After it runs, the module shop.checkout has its own name charge, which points to the function.
  2. Patching shop.payments.charge changes the name in the payments module only. The checkout module still has the old name, so the real function is called.
  3. Patch shop.checkout.charge instead, the name that the code under test really looks up.
After patching the name in the payments moduleshop.paymentschargeshop.checkoutchargeThe mocknobody calls itThe real functionstill called by checkoutFix: patch the name in the module that looks it up.patch("shop.checkout.charge")
The import line makes a second name for the function in the checkout module. Patching the name in the payments module does not change it. Patch the name where it is looked up.
from decimal import Decimal
from unittest.mock import patch

def test_checkout_charges_the_card(monkeypatch):
    calls = []

    def fake_charge(card_token, amount):
        calls.append((card_token, amount))
        return "pay_123"

    monkeypatch.setattr("shop.checkout.charge", fake_charge)

    result = checkout("tok_visa", Decimal("50.00"))
    assert result == "order paid with pay_123"
    assert calls == [("tok_visa", Decimal("50.00"))]

def test_checkout_with_mock():
    with patch("shop.checkout.charge", return_value="pay_9") as fake:
        checkout("tok_visa", Decimal("1.00"))
    fake.assert_called_once_with("tok_visa", Decimal("1.00"))
  1. Mock only the edges of your system: payments, email, other services, the clock. Do not mock your own small functions, or the test only checks that the code calls what it calls.
  2. Use the autospec option of patch when you can. Then a wrong number of arguments fails the test, like it would fail with the real function.
  3. If mocking is hard, the design may be the problem. A function that gets its payment client as a parameter is easy to test with a fake.

Isolation: every test stands alone

A good suite passes in any order, alone or together, on any machine.

  1. No shared changing state. No global carts, no module-level lists that tests add to.
  2. Clean up everything. Use yield fixtures, monkeypatch and tmp_path. They clean up even when the test fails.
  3. No real network. Mock external services, or run them in a test container that the suite controls.
  4. Control time and randomness. Pass the clock or the random seed in, or replace them in the test.
  5. Check the order. Plugins like pytest-randomly run tests in a random order and find hidden dependencies between tests.

Testing a FastAPI endpoint

FastAPI has a TestClient, and the dependency_overrides dict lets you swap a dependency for the test:

from fastapi.testclient import TestClient
from shop.api import app, get_db

def test_get_missing_product_returns_404(db_session):
    app.dependency_overrides[get_db] = lambda: db_session
    try:
        response = TestClient(app).get("/products/999")
    finally:
        # do not leak into other tests
        app.dependency_overrides.clear()
    assert response.status_code == 404

For async def tests, pytest needs a plugin, for example pytest-asyncio or the plugin that comes with anyio.

Common mistakes

Mistake Result Better way
A global object that tests change Tests pass alone and fail together. A function-scope fixture.
A session-scope fixture with changing state Order-dependent failures. A wide scope only for things tests do not change.
Patching the name where it is defined The real function is still called. Patch the name where it is used.
Mocking your own small functions Tests that check nothing useful and break on every refactor. Mock only the edges.
Real network calls in unit tests Slow and flaky tests. Mocks, fakes, or a controlled test container.
Copying a test for each case Long files and missed cases. The parametrize mark.
Forgetting to clear dependency_overrides One test changes the app for the next tests. Clear it in finally, or in a fixture.

Summary in 6 lines

  1. A pytest test is a function with a plain assert. pytest shows the values when it fails.
  2. Parametrize runs one test with a table of cases. Each row is its own test.
  3. Fixtures give each test what it needs. A yield fixture also cleans up.
  4. The default fixture scope is one test. Use wider scopes only for things that tests do not change.
  5. Patch a name where it is used, not where it is defined. Mock only the edges of the system.
  6. Every test must pass alone, together, and in any order.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.