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
yieldprepares resources. - Yield: Sends the resource to the test.
- Teardown: Code after
yieldcleans 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
Noneunintentionally, causing test failures. - Using
returninstead ofyield, 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
returnif you need teardown. - Use
yieldfixtures 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.