Fixtures and Setup/Teardown
Use fixtures for shared test state and resource setup.
What Are Fixtures?
Fixtures are functions decorated with @pytest.fixture that provide test dependencies. pytest injects them by name.
import pytest
@pytest.fixture
def user():
return {"name": "Alice", "age": 30}
def test_name(user):
assert user["name"] == "Alice"Setup and Teardown with yield
Yield the fixture value inside a fixture to separate setup (before yield) from teardown (after yield).
import pytest
@pytest.fixture
def db_connection():
conn = create_connection() # setup
yield conn
conn.close() # teardown
def test_query(db_connection):
result = db_connection.query("SELECT 1")
assert result is not NoneAll lessons in this course
- Writing Your First pytest Tests
- Fixtures and Setup/Teardown
- Parametrize and Test Coverage
- Mocking with unittest.mock