yieldfixture.rst

Overview

This documentation file covers the concept and usage of "yield_fixture" functions in the pytest testing framework. It explains the purpose and functionality of yield fixtures, which allow users to define setup and teardown behavior in test fixtures using Python's `yield` statement.

The key focus is on the historical context and current best practice regarding yield fixtures in pytest:

This file is part of the pytest documentation and helps users understand how to write fixtures with setup and teardown phases using the `yield` statement.

Detailed Explanations

Concept: Yield Fixtures in pytest

A *fixture* in pytest provides a fixed baseline upon which tests can reliably and repeatedly execute. Fixtures often involve setup steps (e.g., creating test data or opening resources) and teardown steps (e.g., closing connections or cleaning up files).

A *yield fixture* is a fixture function that uses Python's `yield` statement instead of `return`:

Historical Usage

Before pytest 3.0:

import pytest

@pytest.yield_fixture
def resource():
    # Setup code
    setup_resource = acquire_resource()
    yield setup_resource
    # Teardown code
    release_resource(setup_resource)

Current Recommended Usage (pytest 3.0+)

Now, the `yield` statement is fully supported inside `@pytest.fixture`, so the same fixture is written as:

import pytest

@pytest.fixture
def resource():
    # Setup code
    setup_resource = acquire_resource()
    yield setup_resource
    # Teardown code
    release_resource(setup_resource)

Parameters and Return Values

Usage Examples

Below is an example of a modern yield fixture:

import pytest

@pytest.fixture
def db_connection():
    # Setup: open db connection
    connection = open_database()
    yield connection
    # Teardown: close db connection
    connection.close()

def test_query(db_connection):
    result = db_connection.query("SELECT * FROM users")
    assert result is not None

Important Implementation Details

Interaction with Other Parts of the System

Mermaid Diagram

The following class diagram illustrates the high-level structure of yield fixture usage, focusing on the fixture function lifecycle phases:

flowchart TD
    A[Fixture Function] --> B[Setup Code (before yield)]
    B --> C[Yielded Value to Test]
    C --> D[Test Function Executes]
    D --> E[Teardown Code (after yield)]
    E --> F[Fixture Cleanup Complete]

This flowchart shows the linear lifecycle:

  1. Setup code runs first.

  2. Fixture yields a value to the test.

  3. Test runs using the fixture value.

  4. After test completion, teardown code runs.

  5. Fixture finishes cleanup.

Summary


*End of yieldfixture.rst*