DEV Community

Hasib Ahmed
Hasib Ahmed

Posted on Originally published at pythontojob.com

pytest fixtures: shared setup, fresh state and guaranteed cleanup

If your pytest files start with the same four lines of setup in every test, you are paying for it twice: once in reading, and again every time the setup changes. Fixtures fix both. This post walks through the core of them with one small shopping cart, including the part people skip: cleanup with yield.

The problem

Here is a small cart, shop.py:

DISCOUNTS = {}


def register_discount(code, percent):
    DISCOUNTS[code] = percent


def remove_discount(code):
    del DISCOUNTS[code]


class Cart:
    def __init__(self):
        self.lines = []

    def add(self, name, price, quantity=1):
        if quantity < 1:
            raise ValueError(f"quantity must be at least 1: {quantity}")
        self.lines.append((name, price, quantity))

    def total(self, code=None):
        amount = sum(price * quantity for _, price, quantity in self.lines)
        if code is not None:
            amount = amount * (100 - DISCOUNTS[code]) / 100
        return round(amount, 2)
Enter fullscreen mode Exit fullscreen mode

Without fixtures, every test builds its own cart: Cart(), then two add() calls, then the one line the test is actually about. The setup is the same each time, so the line that differs is buried. And when Cart() needs an argument, you edit it in every test.

A first fixture

Move the setup into a function and put @pytest.fixture above it. A test asks for it by naming it as a parameter:

import pytest

from shop import Cart


def cart_with(*lines):
    cart = Cart()
    for name, price, quantity in lines:
        cart.add(name, price, quantity)
    return cart


@pytest.fixture
def cart():
    return cart_with(("pen", 15.0, 3), ("bag", 850.0, 1))


def test_total(cart):
    assert cart.total() == 895.0
Enter fullscreen mode Exit fullscreen mode

Nothing calls cart(). Before running a test, pytest looks at its parameter names, finds a fixture with each name, runs it, and passes the result in. The test says what it needs, not how to build it.

Each test gets a fresh value. If one test adds a notebook to the cart, the next test doesn't see it. That is the default ("function scope"), and it's what makes fixtures safe: a test's result can't depend on which tests ran before it.

yield: setup, then cleanup

Some setup changes something outside the test. In our shop, registering a discount code writes to a module-level dictionary, so it must be undone. Use yield instead of return:

@pytest.fixture
def summer_code():
    register_discount("SUMMER", 10)
    yield "SUMMER"
    remove_discount("SUMMER")
Enter fullscreen mode Exit fullscreen mode

Everything before yield is setup. The yielded value is what the test receives. When the test ends, pytest resumes the fixture and runs what's below the yield.

Why not just clean up at the end of the test body? Because a failing assert raises, and raising ends the test on the spot. The cleanup line never runs, the mess stays behind, and the next test, which was perfectly correct, fails on what it inherited. In a big suite that second failure is the one that eats your afternoon. Cleanup after a yield runs whether the test passed or failed.

The rule: cleanup goes after the yield of a fixture, not at the end of a test body.

Fixture or plain helper?

A test can call a helper and pass it arguments. A test can't call a fixture; it can only name it. So:

  • Use a fixture when many tests need the same starting state, especially if it needs cleanup.
  • Use a helper function (like cart_with above) when each test needs a slightly different object.

They combine well, as the fixture cart above calls the helper.

The full test file

import pytest

from shop import Cart, register_discount, remove_discount


def cart_with(*lines):
    # A plain helper: it takes arguments, so each test can ask for its own cart.
    cart = Cart()
    for name, price, quantity in lines:
        cart.add(name, price, quantity)
    return cart


@pytest.fixture
def cart():
    # The cart most tests share. Built fresh for every test that asks.
    return cart_with(("pen", 15.0, 3), ("bag", 850.0, 1))


@pytest.fixture
def summer_code():
    # Changes global state, so it must undo that change afterwards.
    register_discount("SUMMER", 10)
    yield "SUMMER"
    remove_discount("SUMMER")


def test_total(cart):
    assert cart.total() == 895.0


def test_summer_discount(cart, summer_code):
    assert cart.total(summer_code) == 805.5


def test_code_is_gone_afterwards(cart):
    with pytest.raises(KeyError):
        cart.total("SUMMER")


def test_small_cart(summer_code):
    cart = cart_with(("pen", 15.0, 2))
    assert cart.total(summer_code) == 27.0


def test_zero_quantity_is_refused():
    with pytest.raises(ValueError):
        Cart().add("pen", 15.0, 0)
Enter fullscreen mode Exit fullscreen mode
$ pytest -q
.....                                                                    [100%]
5 passed in 0.01s
Enter fullscreen mode Exit fullscreen mode

Three things to notice:

  1. Each test asks only for what it uses. test_small_cart wants a different cart, so it calls the helper and never requests cart. test_zero_quantity_is_refused needs no fixture at all, since nobody else shares its starting state.
  2. test_code_is_gone_afterwards is a test of the fixture's cleanup. It runs after test_summer_discount and checks that SUMMER no longer exists. Change summer_code to a plain return "SUMMER" and this test fails with DID NOT RAISE, because the code leaked from one test into the next. Without that check the leak would be silent.
  3. Run pytest --setup-show to see exactly when each fixture is set up and torn down. Teardown happens in the reverse order of setup.

When it breaks

  • fixture 'crat' not found: a parameter name matched no fixture. Check for a typo, or a missing @pytest.fixture. Note it shows as ERROR, not FAILED: the test never started.
  • Fixture "cart" called directly: you wrote cart() in a test body. Name it as a parameter instead, or use a helper function if you need arguments.
  • ERROR at setup of test_x: the exception was raised inside the fixture. Look there first.
  • A test passes alone but fails with the others: something is leaking between tests. Look for global state changed without a yield cleanup.

Fixtures are the foundation for the rest of pytest (tmp_path, monkeypatch and capsys are all fixtures), so it pays to get comfortable with them early.


Originally published on PythonToJob — a free Python course. This post was written with AI assistance and reviewed.

Top comments (0)