About Fixtures
A fixture in pytest is a function decorated with @pytest.fixture. It can do one or more of the following:
- provide data to tests,
- set up environment state or resources before a test runs,
- clean up after the test completes.
To use a fixture, simply include its name as a parameter in your test function (pytest matches the parameter name to the fixture and injects its return value):
import pytest
@pytest.fixture
def sample_data():
return {"id": 1, "username": "test_user"}
def test_data_validation(sample_data):
# The fixture return value is injected into 'sample_data'
assert sample_data["id"] == 1Setup and Teardown
Fixtures are commonly used to manage setup and teardown logic, i.e., preparing resources before a test runs and cleaning them up afterward. Pytest provides a simple pattern for this using the yield keyword.
To handle teardown (cleanup code), use the yield keyword instead of return. Code before the yield is the setup; code after the yield is the teardown.
When a fixture uses yield instead of return, pytest treats the code before the yield as setup and the code after it as teardown (cleanup code). The value yielded is what gets injected into the test.
@pytest.fixture
def db_connection():
print("\n--- Connecting to DB ---") # Setup
conn = "DatabaseConnection"
yield conn
print("\n--- Closing DB ---") # Teardown
def test_query(db_connection):
assert db_connection == "DatabaseConnection"Sometimes a fixture is needed only for its side effects (for example, initializing a database or mocking the environment), not for its return value. In such cases, you can use @pytest.mark.usefixtures() to activate the fixture without adding it as a function argument.
@pytest.fixture
def setup_db():
print("\nSetting up DB")
yield
print("\nTearing down DB")
@pytest.mark.usefixtures("setup_db")
def test_something():
assert Trueusefixtures also works at the class level and affects all tests inside the class:
@pytest.mark.usefixtures("setup_db")
class TestDBOperations:
def test_insert(self):
...
def test_delete(self):
...