Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Fixtures

Fixtures Basics

Learn what pytest fixtures are and how @pytest.fixture provides test data by name, how fixtures use other fixtures, and why they beat copy-pasted setup code.

Most tests need something to work with before they can start: a shopping cart with items in it, a user record, a temporary file, a database connection. If you create these things at the top of every test, the tests fill up with repeated setup code and the interesting part, the assertion, gets lost.

A fixture is pytest's answer. It is a function that prepares something and gives it to any test that asks for it by name. The test lists the fixture as a parameter, pytest runs the fixture first, and passes the returned value in. This idea is called dependency injection, and it is the feature that makes pytest suites easy to grow.

Your first fixture

Decorate a function with @pytest.fixture. Then use its name as a parameter in a test:

Python A fixture that returns a value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Neither test builds a cart. They declare they need one, by naming the parameter cart, and pytest matches that name to the fixture. The name matching is exact: a typo gives fixture 'carts' not found.

flowchart LR
    T["test_total(cart)"] -->|"needs 'cart'"| F["fixture cart()"]
    F -->|"returns Cart object"| T

pytest looks up the fixture by parameter name, calls it, and passes the result to the test.

Each test gets its own copy

By default a fixture is run again for every test that uses it, so tests cannot affect each other. If the first test empties the cart, the second still receives a full one:

Python Fresh fixture for each test

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

You can see "building numbers" printed once per test in the captured output. That isolation is why the second test passes even though the first one cleared the list. In the next lesson you will learn to widen this when building something is expensive.

Fixtures can use other fixtures

A fixture may itself ask for fixtures. pytest builds the chain in the right order, so you can assemble complex objects from small, named parts:

Python Fixtures depending on fixtures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The --setup-show option prints each fixture as it is set up and torn down. It is the best tool for understanding fixture order, and you will use it in the following lessons. Notice that test_admin_keeps_user_fields asks for both admin and user; because they come from the same test, they share the same user instance within that test.

flowchart LR
    U["user"] --> A["admin"] --> G["greeting"] --> T["test_greeting"]

Fixture dependencies form a graph. pytest sets up the leaves first.

Fixtures versus helper functions

You could write make_cart() as a normal function and call it in each test. When is a fixture better?

Plain helper function Fixture
called explicitly in every test requested by parameter name
no automatic cleanup can run cleanup code after the test (see yield fixtures)
cannot be shared across files without imports shared through conftest.py
runs every time can be cached with a scope
no parametrization can be parametrized

For a trivial value a helper is fine. Use a fixture when you need cleanup, sharing, caching or parametrization, or just to keep the test's parameter list a clear statement of what it needs.

Naming and style

  • Name a fixture after what it provides (cart, logged_in_user, tmp_db), as a noun.
  • Keep fixtures small and focused; compose big ones from small ones.
  • Document with a docstring if the purpose is not obvious; pytest --fixtures lists every available fixture with its docstring.
  • A fixture can have its test-visible name set explicitly, @pytest.fixture(name="cart"). This avoids shadowing when the fixture function and a parameter would otherwise share a name in the same file.
Terminal
pytest --fixtures            # built-in fixtures and your own
pytest --fixtures -v         # also shows where each one is defined

The output lists pytest's own fixtures (capsys, tmp_path, monkeypatch and more) and, in a separate section, the ones defined in your project, with their docstrings.

Fixtures return anything

A fixture can return numbers, strings, objects, functions, classes, generators, dictionaries, mock objects, database connections... Anything. A test can use several fixtures at once, and a fixture can return a helper function instead of data:

Python
@pytest.fixture
def make_user():
    def _make(name="Ada"):
        return {"name": name}
    return _make

This factory pattern gets its own lesson later in this chapter.

Common mistakes

  1. Calling a fixture directly. cart() in a test raises an error; request it as a parameter instead.
  2. Forgetting the parameter. Defining a fixture and never listing it does nothing.
  3. Mutating shared objects. With wider scopes the same object is reused; keep scope-function fixtures for anything tests change.
  4. Giant fixtures. A fixture that builds the world hides what a test actually depends on. Prefer several small fixtures.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a test receive a fixture?

    pytest matches parameter names to fixture names, runs the fixture and passes in its result.
  2. 2. By default, how often does a fixture run?

    The default scope is function, so each test gets a fresh fixture value.
  3. 3. Which option shows when fixtures are set up and torn down?

    --setup-show prints each fixture's setup and teardown with its scope.
  4. 4. A fixture named admin lists user as a parameter. What happens?

    Fixtures can request other fixtures; pytest resolves the dependency graph.

Summary

  • A fixture is a function marked with @pytest.fixture; tests ask for it by parameter name.
  • Each test gets its own fixture value by default, which keeps tests independent.
  • Fixtures can depend on other fixtures, forming a graph pytest resolves for you.
  • --setup-show and --fixtures help you understand what is available and in what order it runs.
  • Choose fixtures over plain helpers when you need cleanup, sharing, caching or parametrization.

Next: Fixture Scopes