0
0
PytestHow-ToBeginner ยท 3 min read

How to Use Yield Fixture in pytest for Setup and Teardown

In pytest, use yield inside a fixture to separate setup and teardown code. The code before yield runs before the test, and the code after yield runs after the test finishes, allowing clean resource management.
๐Ÿ“

Syntax

A pytest fixture using yield has two parts: setup code before yield and teardown code after it. The value yielded is passed to the test function as the fixture result.

  • Setup: Code before yield prepares resources.
  • Yield: Sends the resource to the test.
  • Teardown: Code after yield cleans up resources.
python
import pytest

@pytest.fixture
def resource():
    # Setup code
    print("Setup resource")
    yield "my_resource"
    # Teardown code
    print("Teardown resource")
๐Ÿ’ป

Example

This example shows a fixture that sets up a resource, yields it to the test, and then cleans up after the test finishes. The print statements show the order of execution.

python
import pytest

@pytest.fixture
def resource():
    print("Setup resource")
    yield "my_resource"
    print("Teardown resource")


def test_example(resource):
    print(f"Using {resource} in test")
    assert resource == "my_resource"
Output
Setup resource Using my_resource in test Teardown resource
โš ๏ธ

Common Pitfalls

Common mistakes when using yield fixtures include:

  • Not placing cleanup code after yield, so teardown never runs.
  • Yielding None unintentionally, causing test failures.
  • Using return instead of yield, which skips teardown.

Always remember that yield splits setup and teardown.

python
import pytest

# Wrong: using return skips teardown
@pytest.fixture
def wrong_fixture():
    print("Setup")
    return "resource"
    print("Teardown")  # This never runs

# Right: using yield runs teardown
@pytest.fixture
def right_fixture():
    print("Setup")
    yield "resource"
    print("Teardown")
๐Ÿ“Š

Quick Reference

Remember these tips when using yield fixtures:

  • Setup code runs before yield.
  • The value yielded is passed to the test.
  • Teardown code runs after the test finishes.
  • Do not use return if you need teardown.
  • Use yield fixtures for managing resources cleanly.
โœ…

Key Takeaways

Use yield in pytest fixtures to separate setup and teardown cleanly.
Code before yield runs before the test; code after runs after the test.
Always yield the resource to the test function; do not use return if teardown is needed.
Teardown code after yield ensures resources are properly cleaned up.
Yield fixtures help manage test resources simply and clearly.