Stop 10 · Testing & Code QualityTopics · 2/8

Fixtures & Parametrized Tests

Part of the Python Roadmap

In short

Copy-pasting the same setup into ten tests, or writing ten nearly identical tests for ten inputs, makes test files long and fragile. Fixtures share setup, and parametrize turns one test into many.

Fixtures provide reusable setup, such as sample data or a temporary file, to any test that asks for them. @pytest.mark.parametrize runs one test with many inputs, so you cover more cases with less code.

The jaadu stands at a long kitchen counter lined with ready bowls of chopped vegetables, filling a neat row of identical steel tiffin boxes one after another.

Think of it like this

The tiffin centre's prep station

A tiffin centre in Mumbai doesn't chop onions separately for every order. The prep station keeps chopped onions, boiled rice and dal ready, and each cook just takes what their dish needs. Fixtures are that prep station. Parametrize is cooking the same recipe for ten addresses at once.

Watch it happen

How a fixture reaches a test

test function
pytest
fixture

def test_total(cart):

1/4The test asks for an argument named cart. That's the whole request.

The big ideas

What you need to know

@pytest.fixture

A function that builds test data. Any test that names it as a parameter receives its return value.

yield for cleanup

Code before yield is setup, code after it runs when the test finishes, even if it failed.

Built-in fixtures

tmp_path gives a fresh temporary folder, and capsys captures printed output. No setup needed.

@pytest.mark.parametrize

List input and expected pairs once. pytest runs a separate test for each row and reports each one.

See it in code

Walk through the code

python
1import pytest2 3 4@pytest.fixture5def cart() -> dict[str, int]:6    return {"Parle-G": 2, "Maggi": 3}7 8 9def test_cart_has_two_products(cart: dict[str, int]) -> None:10    assert len(cart) == 211 12 13def test_adding_updates_quantity(cart: dict[str, int]) -> None:14    cart["Maggi"] += 115    assert cart["Maggi"] == 416 17 18@pytest.mark.parametrize(19    ("pincode", "valid"),20    [("411001", True), ("011001", False), ("4110", False), ("41100A", False)],21)22def test_pincode(pincode: str, valid: bool) -> None:23    assert (len(pincode) == 6 and pincode.isdigit() and pincode[0] != "0") == valid24 25 26def test_writes_receipt(tmp_path) -> None:27    receipt = tmp_path / "receipt.txt"28    receipt.write_text("Total: 245", encoding="utf-8")29    assert receipt.read_text(encoding="utf-8") == "Total: 245"

1/4A fixture returns fresh sample data every time a test asks for it.

Run with pytest -v to see each parametrized case listed separately, like test_pincode[011001-False].

Save yourself the pain

Common mistakes

Oops

Calling a fixture directly inside a test, like data = cart().

Do this instead

Name it as a parameter: def test_x(cart). pytest raises an error if you call a fixture function directly.

Oops

Sharing one mutable list at module level across tests.

Do this instead

Build it in a fixture so each test gets a fresh copy and tests can run in any order.

Oops

Writing a for loop over inputs inside one test.

Do this instead

Use parametrize. A loop stops at the first failure and hides which other inputs also fail.

Your mission

Refactor a repetitive test file

~30 min

Quick check

A fixture is used by three tests. How many times does it run by default?

Go deeper

  1. 1Create a fixture that returns a sample shopping cart.
  2. 2Parametrize a test with five input and expected-output pairs.
  3. 3Use the built-in tmp_path fixture to test file-writing code.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge