fixtures.rst

Overview

The [fixtures.rst](/projects/286/67203) file is a comprehensive reference document for **pytest fixtures**, a core feature of the pytest testing framework. It explains the purpose, behavior, and usage of fixtures, which are reusable components that help set up and tear down test environments in a modular and maintainable way.

This document covers:

This file serves as both a user guide and a conceptual reference for understanding and effectively leveraging fixtures in pytest-based test suites.


Detailed Explanations

Built-in Fixtures

These fixtures are provided by pytest out-of-the-box and cover common test setup needs, such as capturing output, managing temporary directories, controlling logging, and accessing test configuration.

Fixture Name

Description

capfd

Capture output to file descriptors 1 and 2 as text.

capfdbinary

Capture output to file descriptors 1 and 2 as bytes.

`caplog`

Control and access logging output.

`capsys`

Capture output to [sys.stdout](/projects/286/67223) and [sys.stderr](/projects/286/67223) as text.

capsysbinary

Capture output to [sys.stdout](/projects/286/67223) and [sys.stderr](/projects/286/67223) as bytes.

capteesys

Like `capsys` but passes text through according to [--capture=](/projects/286/67356) option.

cache

Store and retrieve values across pytest runs.

doctest_namespace

Inject a dict into the doctest namespace.

monkeypatch

Temporarily modify classes, functions, dictionaries, environment variables (`os.environ`), etc.

pytestconfig

Access pytest configuration and plugin hooks.

record_property

Add extra properties to a test record.

record_testsuite_property

Add extra properties to a test suite record.

recwarn

Record warnings emitted by tests.

`request`

Provides information about the executing test function.

testdir

Provides a temporary test directory for testing pytest plugins.

`tmp_path`

Provides a [pathlib.Path](/projects/286/67376) object to a unique temporary directory per test function.

tmp_path_factory

Creates session-scoped temporary directories as [pathlib.Path](/projects/286/67376) objects.

tmpdir

Provides a [py.path.local](/projects/286/67409) temporary directory (deprecated in favor of `tmp_path`).

tmpdir_factory

Creates session-scoped temporary directories as [py.path.local](/projects/286/67409) objects (deprecated).

Usage example of a built-in fixture:

def test_write_and_read(tmp_path):
    file = tmp_path / "example.txt"
    file.write_text("hello pytest")
    assert file.read_text() == "hello pytest"

Fixture Availability and Scope

Fixtures are available to tests based on the scope they are defined in:

Fixtures can request other fixtures regardless of scope, provided the requesting test has visibility of all involved fixtures. This is known as *dependency injection*.

Example illustrating fixture visibility from the test's perspective shows that tests can use fixtures defined in outer scopes transparently.


Sharing Fixtures with conftest.py

The special file `conftest.py` allows defining fixtures that are automatically discovered and shared across multiple test files within a directory (and its subdirectories unless overridden).

Key points:

Example directory structure with `conftest.py` and tests illustrates fixture inheritance and overriding behavior.


Fixtures from Third-party Plugins

Fixtures can also be provided by third-party pytest plugins. These fixtures:

An example shows how fixtures from plugins `plugin_a` and `plugin_b` integrate with user-defined fixtures during resolution.


Fixture Instantiation Order

Pytest determines the order of fixture setup based on three factors:

  1. Scope: Fixtures with broader scope (e.g., session) are instantiated before narrower scope (e.g., function).

  2. Dependencies: If fixture A depends on fixture B, B is set up first.

  3. Autouse: Fixtures marked autouse=True run before explicitly requested fixtures within their scope.

Higher-scoped fixtures execute first

Example:

Dependency order

Fixture dependencies form a directed acyclic graph (DAG). Pytest topologically sorts fixtures so dependencies execute first.

If dependencies are ambiguous or incomplete, pytest may choose any valid order consistent with constraints.

Autouse fixtures execute first

Example graphs visualize how autouse fixtures reorder execution.


Important Notes


Implementation Details


Interactions with Other Parts of the System


Visual Diagram: Fixture Resolution and Execution Structure

flowchart TD
    A[Test Request]
    B[Fixture Resolution Start]
    C{Fixture Scope?}
    D[Session Scoped Fixture]
    E[Package Scoped Fixture]
    F[Module Scoped Fixture]
    G[Class Scoped Fixture]
    H[Function Scoped Fixture]
    I{Dependencies?}
    J[Resolve Dependencies]
    K[Autouse Fixtures?]
    L[Execute Autouse Fixtures First]
    M[Execute Requested Fixtures]
    N[Test Runs]

    A --> B
    B --> C
    C -->|Session| D
    C -->|Package| E
    C -->|Module| F
    C -->|Class| G
    C -->|Function| H
    D --> I
    E --> I
    F --> I
    G --> I
    H --> I
    I -->|Yes| J
    I -->|No| K
    J --> K
    K -->|Yes| L
    K -->|No| M
    L --> M
    M --> N

**Explanation:**


Usage Examples Snippets

**Requesting fixtures in a test:**

def test_example(tmp_path, capsys):
    file = tmp_path / "data.txt"
    file.write_text("pytest fixtures")
    out, err = capsys.readouterr()
    assert file.read_text() == "pytest fixtures"

**Defining a fixture in `conftest.py`:**

import pytest

@pytest.fixture(scope="module")
def db_connection():
    conn = create_db_connection()
    yield conn
    conn.close()

**Using autouse fixture:**

@pytest.fixture(autouse=True)
def enable_feature_flag():
    # Setup code before each test
    yield
    # Teardown code after each test

Summary

The [fixtures.rst](/projects/286/67203) file is an essential, detailed guide to pytest fixtures, explaining their built-in forms, lifecycle, scope, availability rules, and execution order. It covers how fixtures can be shared across tests and directories, integrated from plugins, and controlled via autouse and dependencies.

Understanding this document enables pytest users to write robust, maintainable tests with complex setup/teardown needs, and to diagnose fixture-related behavior effectively.


**End of documentation for [fixtures.rst](/projects/286/67203).**