pytest fixture provides test setup and teardown functionality.
1import pytest2import tempfile3import os45# Simple fixture6@pytest.fixture7def sample_data():8 return {"users": [{"name": "Alice"}, {"name": "Bob"}]}910def test_user_count(sample_data):11 assert len(sample_data["users"]) == 21213# Fixture with setup/teardown14@pytest.fixture15def temp_file():16 # Setup17 fd, path = tempfile.mkstemp()18 with os.fdopen(fd, "w") as f:19 f.write("test data")2021 yield path # Test runs here2223 # Teardown24 os.unlink(path)2526def test_file_content(temp_file):27 with open(temp_file) as f:28 assert f.read() == "test data"2930# Fixture scope31@pytest.fixture(scope="module") # Once per module32def db_connection():33 conn = create_connection()34 yield conn35 conn.close()3637@pytest.fixture(scope="session") # Once per test session38def app():39 return create_app(testing=True)4041# Autouse fixture42@pytest.fixture(autouse=True)43def reset_db():44 db.session.begin_nested()45 yield46 db.session.rollback()
Scope options:
function — per test (default).class — per test class.module — per test file.session — entire test run.