Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท Fixtures

Fixture Factories, Autouse and Parameters

Build factory fixtures that create many objects on demand, apply setup to every test with autouse, add fixtures with usefixtures, and use getfixturevalue and params.

A basic fixture hands every test exactly one prepared object. Real tests are more varied: one test needs a user, another needs three users with different roles, a third needs a user with an expired subscription. This lesson shows the patterns that give you that flexibility while keeping tests short: factory fixtures, autouse fixtures, the usefixtures mark and dynamic lookup.

Factory fixtures

When a test needs several objects, or an object with custom values, make the fixture return a function that builds objects on demand. Tests call it as many times as they like, with whatever arguments they need:

Python A factory fixture

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 factory is created once per test, so the counter restarts for every test. The test now describes the interesting part itself (role="admin") instead of hiding it inside the fixture.

Factories that clean up

If the objects made by the factory need cleanup, keep track of them in the fixture and clean everything after the yield:

Python Factory with cleanup

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.

This is the standard recipe for "any number of resources, all cleaned up".

autouse: setup without asking

Sometimes every test in a group needs the same setup and you do not want to list the fixture everywhere: reset a global, freeze the clock, block network access, clear a cache. Mark the fixture autouse=True and pytest applies it automatically to every test within its scope (the file, or the folder for a conftest):

Python autouse fixture

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 mentions clean_registry, yet the --setup-show output shows it running before each one.

Use autouse sparingly. It makes tests depend on something that is not visible in their signature, which surprises readers. Good uses are safety nets (no real network or database calls, a reset of global state). Bad uses are building data a test depends on: that belongs in an explicit fixture.

usefixtures: request a fixture without a parameter

When you need a fixture's side effect but not its value, the usefixtures mark is clearer than adding an unused parameter. It works on a function, a class or a whole module:

Python @pytest.mark.usefixtures

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.

To apply a fixture to every test in a file, set pytestmark = pytest.mark.usefixtures("name") at module level. In a pytest.ini, usefixtures = name applies it to the whole run.

Fixtures with parameters

A fixture can run its tests once per parameter value, using params. Inside, request.param holds the current value. The lesson on parametrized fixtures covers the details; here is a taste:

Python params on a fixture

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.

One test function produced two test items, each with its own id (test_backend_name[sqlite] and [memory]).

getfixturevalue: choose a fixture at run time

When the fixture to use depends on data, request it by name inside the test with request.getfixturevalue:

Python getfixturevalue

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.

This is useful in parametrized tests that switch between fixtures. Use it only when static parameters cannot do the job, because pytest cannot show the dependency in --setup-show until the test runs.

Fixture ordering with autouse

Autouse fixtures are instantiated first within their scope, before explicitly requested ones. If an explicit fixture relies on the effect of an autouse one (for example, an env var), that works. When order matters between explicit fixtures, make one depend on the other so that the dependency is visible.

Choosing the right tool

flowchart TD
    A["I need something for my test"] --> B{"One object,<br/>fixed values?"}
    B -->|yes| C["plain fixture"]
    B -->|no| D{"Several objects or custom values?"}
    D -->|yes| E["factory fixture"]
    D -->|no| F{"Only a side effect,<br/>for many tests?"}
    F -->|"explicit"| G["usefixtures mark"]
    F -->|"always, everywhere"| H["autouse fixture"]

Start with the simplest tool and move down only when a test needs more.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a factory fixture return?

    A factory fixture returns a callable so each test can build as many customised objects as it needs.
  2. 2. What does autouse=True do?

    An autouse fixture is set up automatically for every test it covers.
  3. 3. When is @pytest.mark.usefixtures preferable to a function parameter?

    usefixtures requests a fixture without introducing an unused parameter and works on classes and modules.
  4. 4. How do you get a fixture whose name is only known inside the test?

    getfixturevalue looks up and instantiates a fixture by name at run time.

Summary

  • Factory fixtures return functions, letting each test create exactly the objects it needs; track created objects to clean them up after the yield.
  • autouse=True applies a fixture automatically; keep it for safety nets, not for data.
  • usefixtures requests a fixture for its side effect, on a function, class or module.
  • params runs tests once per value, and request.getfixturevalue picks fixtures dynamically.
  • Pick the simplest tool that expresses what the test needs.

Next: Parametrized Tests