Article summary

TL;DR

  • Fixtures prepare test resources and clean them up. Reusing the definition can still give every case fresh data.
  • Parametrization runs the same behavior with different inputs and reports each case separately. Clear case names make failures easier to rerun.
  • Use a factory when one scenario needs several objects. Use indirect parameters when a case needs the fixture to prepare different starting data.
  • Measure setup costs before sharing resources across tests. Faster setup is useful only when the tests remain independent.

Code for this article

Open the repository to follow along.

artem-istranin/istranin-dev-code-examples
View on GitHub (opens in a new tab)

01 / START HERE

Keep the behavior clear as your test suite grows.

You have 3 tests for reserving stock. Each opens a database, adds 5 books, reserves a quantity, and checks the balance. The tests work, but changing the setup means editing the same code in 3 places. Adding more cases makes that repetition grow.

Pytest fixtures and parametrization solve different parts of this problem. A fixture prepares something a test needs and can clean it up afterward. Parametrization runs the same test with different inputs, reporting each case separately. Together, they let us reuse setup while keeping the behavior under test visible.

We’ll follow an inventory example from repeated setup to a suite that checks reservations in memory and in a temporary database file. You’ll see how to name cases, rerun a failure, and give each case fresh stock. Then we’ll use factories and indirect parameters where the setup needs more flexibility.

This guide assumes you can write a test with assert. If that is still unfamiliar, start with your first pytest test.

Run the working example

With uv installed, clone the companion repository and enter this example:

git clone https://github.com/artem-istranin/istranin-dev-code-examples.git
cd istranin-dev-code-examples/pytest-fixtures-parametrization
uv sync --locked
uv run pytest -q

The project uses Python 3.13 and locks pytest 9.1.1. uv sync --locked installs the recorded dependencies; -q keeps pytest’s output brief. The complete suite reports 32 passed.

We’ll inspect code that is already in this checkout, so you don’t need to copy snippets into new files. Keep commands in this directory. The application lives in inventory.py: add() creates a product, reserve() reduces its stock, and remaining() reads the balance. SQLite comes with Python, so there’s no database server to configure.

The rule is simple: a valid reservation reduces stock; a rejected reservation leaves it unchanged. The example tests that rule against 2 SQLite storage configurations. It doesn’t establish compatibility with another database or test production concurrency.

02 / REUSE SETUP

Move repeated setup into a fixture.

Open refactoring/before.py. Each of its 3 tests contains the same preparation and cleanup. Here is the first:

def test_reserve_one():
    with closing(sqlite3.connect(':memory:', autocommit=True)) as conn:
        inventory = Inventory(conn)
        inventory.add('book', 5)
        inventory.reserve('book', 1)
        assert inventory.remaining('book') == 4

The file imports sqlite3, closing from contextlib, and Inventory from the application. ':memory:' creates a database in memory. closing(...) closes its connection when the block ends, including after an assertion fails.

The other tests reserve 4 or 5 books. Their setup is identical; only the quantity and expected balance change. Let’s handle the repeated setup first.

In refactoring/after.py, the shared preparation becomes this fixture:

@pytest.fixture
def stocked_inventory():
    with closing(sqlite3.connect(':memory:', autocommit=True)) as conn:
        inventory = Inventory(conn)
        inventory.add('book', 5)
        yield inventory

@pytest.fixture registers the function as a fixture. A test requests it by using stocked_inventory as an argument. Pytest runs the fixture and supplies the inventory object; the test doesn’t call the fixture itself.

yield separates preparation from cleanup. The fixture pauses there while the test uses the inventory. Afterward, it resumes and leaves the closing(...) block, which closes the connection. This happens even when the test fails.

By default, a fixture has function scope: pytest creates it again for each test item. A test item is one execution with its own result, including each parametrized case. Reusing the fixture definition therefore gives each case a new database and 5 books.

Put the varying inputs beside the assertion

The same file imports pytest and defines one test with 3 rows:

@pytest.mark.parametrize(
    ('quantity', 'expected'),
    [
        pytest.param(1, 4, id='reserve-one'),
        pytest.param(4, 1, id='leave-one'),
        pytest.param(5, 0, id='exhaust-stock'),
    ],
)
def test_reserve(stocked_inventory, quantity, expected):
    stocked_inventory.reserve('book', quantity)
    assert stocked_inventory.remaining('book') == expected

Each row supplies quantity and expected. The first reserves 1 book and expects 4 left. The last reserves all 5 and expects 0. pytest.param lets us attach a readable ID to each row, so a failure can identify exhaust-stock instead of an unexplained number.

Each test receives a fresh inventory of 5 books and a parameter row: reserving 1, 4, or 5 leaves 4, 1, or 0, matching the expected value.

Run both versions:

uv run pytest refactoring/before.py refactoring/after.py -q

You get 6 passed: 3 original tests and 3 cases from the refactored version. These comparison files sit outside the default suite and run only when requested.

We kept the same checks while reducing the places that need editing. A setup change belongs in the fixture; another quantity belongs in the table. Keep different behaviors separate, though. A reservation that succeeds and one that raises an exception usually read better as separate tests than as rows requiring an if inside the assertion code.

Practice fixtures and parametrization through a complete project in the pytest course.

View course

03 / SHARE FIXTURES

Run the same cases with 2 storage configurations.

The comparison used one fixture in one file. The finished suite has several test files, so its shared fixtures live in tests/conftest.py. Pytest discovers that file automatically; test files don’t import its fixtures.

The setup now has 3 parts: open a connection, create the inventory, and add the starting stock. These definitions already exist in tests/conftest.py:

@pytest.fixture(params=['memory', 'file'])
def connection(request, tmp_path):
    path = ':memory:' if request.param == 'memory' else tmp_path / 'stock.sqlite3'
    with closing(sqlite3.connect(path, autocommit=True)) as conn:
        yield conn


@pytest.fixture
def inventory(connection):
    return Inventory(connection)


@pytest.fixture
def stocked_inventory(inventory):
    inventory.add('book', 5)
    return inventory

Fixtures request other fixtures through their arguments, just as tests do. To prepare stocked_inventory, pytest first prepares inventory, which first needs connection. That dependency determines setup order.

The connection’s params list asks pytest to use both storage configurations. During setup, request.param contains the selected string. Pytest’s built-in tmp_path fixture supplies a temporary directory unique to each test invocation for the file case.

All 3 fixtures keep the default function scope. Every case gets a fresh database. autocommit=True makes each SQL statement take effect immediately; isolation here comes from separate databases, not transaction rollback. Python’s SQLite context-manager documentation explains why we use closing: a connection’s own context manager handles transactions but doesn’t close the connection.

See how the cases combine

tests/test_reservations.py contains the same 3-row test_reserve. It now runs each quantity against both storage configurations: 2 configurations x 3 rows = 6 test items.

Ask pytest to list those items without running them:

uv run pytest tests/test_reservations.py::test_reserve --collect-only -q

The names include both choices:

tests/test_reservations.py::test_reserve[memory-reserve-one]
tests/test_reservations.py::test_reserve[memory-leave-one]
tests/test_reservations.py::test_reserve[memory-exhaust-stock]
tests/test_reservations.py::test_reserve[file-reserve-one]
tests/test_reservations.py::test_reserve[file-leave-one]
tests/test_reservations.py::test_reserve[file-exhaust-stock]

This multiplication is useful because every combination matters here. If only certain input combinations are valid, list those combinations as rows instead of generating many cases you immediately skip.

Place shared fixtures in the nearest conftest.py above their consumers. Inventory fixtures used only by integration tests can live in tests/integration/conftest.py. Putting a fixture in the root file makes it available more widely; it doesn’t change how long its objects live. The pytest fixture reference covers lookup and overrides.

04 / READ A FAILURE

Use the case name to rerun a failure.

Let’s make the reporting benefit visible. In tests/test_reservations.py, temporarily change the final row of test_reserve from pytest.param(5, 0, ...) to pytest.param(5, 1, ...). Keep its ID, exhaust-stock, unchanged.

Run that test:

uv run pytest tests/test_reservations.py::test_reserve -q

You get 2 failed, 4 passed. Both failures identify exhaust-stock, one for memory and one for file storage. The assertion shows 0 == 1: reserving all 5 books left 0, but our edited expectation asked for 1.

Copy one complete case name to rerun it:

uv run pytest 'tests/test_reservations.py::test_reserve[file-exhaust-stock]' -q

Only that case runs and fails. The quotes keep the shell from interpreting the brackets. Restore the expected value to 0, then rerun the same command. You get 1 passed.

We changed the expectation deliberately, so the correction belongs in the test. In a real failure, compare the expected result with the requirement before deciding whether the application or test is wrong.

Check what rejection leaves behind

The same file keeps excessive reservations in a separate test:

@pytest.mark.parametrize('quantity', [6, 10], ids=['one-too-many', 'double-stock'])
def test_overdraw_preserves_stock(stocked_inventory, quantity):
    with pytest.raises(ValueError, match='stock unavailable'):
        stocked_inventory.reserve('book', quantity)
    assert stocked_inventory.remaining('book') == 5

The exception alone doesn’t establish that a rejected reservation was harmless. The final assertion also checks that stock stayed at 5. Each quantity runs with its own starting state under both storage configurations. Run the complete file after restoring the earlier row:

uv run pytest tests/test_reservations.py -q

Its successful, excessive, and nonpositive reservation cases produce 14 passed.

05 / FLEXIBLE SETUP

Choose between more cases and more objects.

Sometimes one test needs several products. A parameter table would run the test several times, but it wouldn’t create 2 products that coexist in the same scenario.

For that, tests/conftest.py provides a factory fixture: a fixture that returns a function the test can call.

@pytest.fixture
def make_product(inventory):
    def create(*, sku, available=5):
        inventory.add(sku, available)
        return sku

    return create

Here sku is the product identifier. The * makes the factory’s arguments keyword-only, keeping the call sites explicit. In tests/test_products.py, a test uses it twice:

def test_reserving_one_product_leaves_another_unchanged(inventory, make_product):
    book = make_product(sku='book', available=5)
    pen = make_product(sku='pen', available=20)

    inventory.reserve(book, 2)

    assert inventory.remaining(book) == 3
    assert inventory.remaining(pen) == 20

The factory and test request the same inventory fixture. Within this item, pytest supplies the same inventory instance to both. The test can therefore see the products the factory created.

Reserving books must leave the pens unchanged. Both assertions describe that one scenario. Calling the factory twice doesn’t create more test items; the 2 storage configurations give us 2 executions, each containing both products.

Use a factory when meaningful choices belong inside the test. If a helper needs no fixture-managed resource, an ordinary Python function is enough.

Let a row configure fixture setup (Advanced)

Indirect parametrization handles a different need: a row supplies a value that a fixture turns into prepared state. In tests/conftest.py:

@pytest.fixture
def prepared_inventory(request, inventory):
    inventory.add('book', request.param)
    return inventory

And in tests/test_prepared.py:

@pytest.mark.parametrize(
    ('prepared_inventory', 'quantity', 'expected'),
    [(5, 2, 3), (10, 4, 6)],
    indirect=['prepared_inventory'],
    ids=['small-order', 'larger-order'],
)
def test_reserve_from_prepared_stock(prepared_inventory, quantity, expected):
    prepared_inventory.reserve('book', quantity)
    assert prepared_inventory.remaining('book') == expected

In the first row, 5 reaches the fixture as request.param. The fixture creates 5 books and returns the inventory. The test receives that object, plus quantity=2 and expected=3 directly from the row. Only the named prepared_inventory argument takes the indirect route.

Run the file:

uv run pytest tests/test_prepared.py -q

You get 4 passed: 2 rows under 2 storage configurations. Use this when rows describe setup. Keep ordinary inputs direct when they need no preparation. The official indirect-parametrization example shows the same mechanism in isolation.

Can an indirectly parametrized pytest fixture depend on other parameters?

Yes. An indirectly parametrized fixture can request other parameters by name. Here, reserved_before determines whether setup includes an earlier reservation.

For this optional variation, replace prepared_inventory in tests/conftest.py with:

@pytest.fixture
def prepared_inventory(request, inventory, reserved_before):
    opening_stock = request.param
    inventory.add('book', opening_stock)

    if reserved_before > 0:
        inventory.reserve('book', reserved_before)

    return inventory

Then replace the existing test and its decorator in tests/test_prepared.py with:

@pytest.mark.parametrize(
    ('prepared_inventory', 'reserved_before', 'quantity', 'expected'),
    [(5, 0, 1, 4), (5, 2, 1, 2)],
    indirect=['prepared_inventory'],
    ids=['no-earlier-reservation', 'after-earlier-reservation'],
)
def test_reserve_from_prepared_stock(prepared_inventory, quantity, expected):
    prepared_inventory.reserve('book', quantity)
    assert prepared_inventory.remaining('book') == expected

Both cases start with 5 books and test a new reservation of 1 book. In the first, reserved_before=0 skips the extra setup, so 4 remain. In the second, the fixture reserves 2 books before the test runs, leaving 2 after the new reservation.

request.param supplies the opening stock. The fixture receives reserved_before separately by name, even though it is a direct parameter. The test doesn’t need that argument because only the fixture uses it.

Keep these fixtures at function scope. Rerun uv run pytest tests/test_prepared.py -q: you get 4 passed across the 2 storage configurations. The full suite still has 32 passing cases.

06 / SCOPE AND CLEANUP

Keep mutable state fresh before sharing expensive resources.

Fixture scope controls reuse. The available scopes are function, class, module, package, and session. A broader scope keeps a fixture available to more tests before cleanup, which can save setup work when sharing is safe.

Our inventory changes during every reservation. Sharing its stock across tests would let one case affect the next. Function scope keeps the starting balance predictable.

Reuse the setup definition. Give each test its own mutable state unless you have verified that sharing is safe.

Changing only connection to session scope also conflicts with its function-scoped tmp_path dependency. Pytest raises ScopeMismatch: a longer-lived fixture cannot depend on a shorter-lived one. Switching to a longer-lived path would address that mismatch, but would not isolate the shared database.

For a larger application, you might share an expensive database server while giving each test separate data. That requires a verified isolation strategy, such as a separate database or transactions that really contain every write. The lifetime of the server and the lifetime of test records are separate decisions.

Keep cleanup beside the resource acquisition. Our connection fixture enters closing(...) before yielding. If inventory preparation or the test fails, the connection can still be closed. For a fixture that acquires several resources, an exception before yield prevents teardown code placed only after that yield from running. Use context managers or separate fixtures so each successful acquisition has cleanup. Pytest’s teardown guide explains this boundary.

07 / MEASURE BEFORE TUNING

Find the expensive work before widening fixture scope.

Run the complete suite with timing details:

uv run pytest --durations=20 --durations-min=0 -q

The report lists slow setup, test calls, and teardown phases. It can identify where to investigate, though it doesn’t measure every fixture independently.

The full example package includes an optional scope experiment:

uv run pytest benchmarks -q --catalog-scope=function
uv run pytest benchmarks -q --catalog-scope=session

Both runs pass 10 cases. The first reports catalog setups=10; the second reports catalog setups=1. This fixture returns an immutable tuple and deliberately waits 0.1 seconds during setup. The experiment demonstrates saved setup work when reuse is safe; its timings don’t predict a production suite’s speedup.

The installed pytest-xdist plugin also lets you run the main suite with 2 worker processes:

uv run pytest tests -n 2 -q

It still runs 32 items. Workers divide the cases between them. A session-scoped fixture is local to each worker, however, so it isn’t automatically created just once across the entire run. See the xdist guidance on session fixtures.

Configuration-driven cases are another optional extension. The companion’s tests/test_dynamic.py uses pytest_generate_tests to turn an opening-stock option into cases. Keep small, fixed tables beside the test; use a pytest collection hook when configuration genuinely determines the inputs. The companion README includes commands and validation rules for that experiment.

08 / COMMON QUESTIONS

Common questions about pytest fixtures and parametrization.

The example gives each reservation fresh stock, reports meaningful case names, and reuses setup across files. These are practical pytest fixtures and parametrization best practices: a developer can add a case without duplicating the database setup or hiding the expected result.

Use this distinction when extending your own suite:

What do you need? Use
The same behavior with different inputs A parametrized test
A resource configuration used by several tests A parametrized fixture
Several objects inside one scenario A factory fixture
A row that controls resource preparation Indirect parametrization

How do pytest fixtures and parametrization work together?

Fixtures prepare the resources a test needs; parametrization supplies separate cases for the test to run. A parametrized fixture adds resource configurations to those cases. In this inventory example, 2 storage configurations combine with 3 reservation quantities to produce 6 independently reported test items, each with fresh stock.

Which pytest fixture scope should I use?

Start with the default function scope for mutable test data so each test item receives fresh state. Consider class, module, package, or session scope for resources that are safe to share. Measure the setup cost first and verify that one test cannot leave changes that affect another.

Can pytest fixtures take arguments from a test?

A test requests a fixture by name rather than calling it directly. Use a factory fixture for values chosen inside the test, or indirect parametrization for values that configure fixture setup. Fixtures can also request other fixtures through their own arguments.

Why did parametrization replace my fixture?

Direct parametrization supplies the named argument itself. If a row assigns inventory=5, the test receives that integer instead of the fixture’s inventory object. Use a distinct name for ordinary data, or indirect parametrization with a fixture designed to interpret the value.

Should shared pytest fixtures use autouse?

Use autouse=True for a policy that should apply to every affected test, such as blocking unexpected network requests. Request scenario resources explicitly so the test signature shows what it needs. Sharing a fixture definition does not require autouse.

Does pytest copy mutable parameter values?

Pytest passes parameter values as supplied; it does not copy lists or dictionaries. Reusing a mutable value can let one invocation change what another receives. Prefer simple descriptions, such as quantities and product names, then construct fresh objects during setup.

Improve one test file

Choose a file where setup repeats. Preserve its behavior checks, extract the shared preparation, and group equivalent cases with readable names. Run the affected tests alone and together. Check the case count before adding another configuration, and measure setup before changing its lifetime.

For the inventory example, finish with uv run pytest -q and confirm all 32 cases pass. When you’re ready to run the same checks on pull requests, continue with the GitHub Actions pytest guide.

Continue with fixtures, mocking, and CI practice in the complete pytest course.

View course