How to Use pytest Fixtures for Clean Tests
In this tutorial, you'll learn about How to Use pytest Fixtures for Clean Tests. We cover key concepts, practical examples, and best practices.
The Problem
Every test duplicates the same setup code — creating database connections, loading config files, or instantiating objects. This makes tests harder to read and maintain. pytest fixtures solve this by defining reusable setup and teardown logic in a single place. Without fixtures, a change to your database schema requires updating every test that creates a connection.
Quick Fix
1. Define a fixture with @pytest.fixture
import pytest
@pytest.fixture
def db_connection():
conn = create_database_connection("test.db")
yield conn
conn.close()
The yield splits setup (before) from teardown (after). Everything before yield runs before the test; everything after runs after the test completes.
2. Use the fixture by declaring it as a parameter
def test_user_insert(db_connection):
db_connection.execute("INSERT INTO users (name) VALUES ('Alice')")
result = db_connection.query("SELECT * FROM users")
assert len(result) == 1
Expected output:
collected 1 item
test_db.py::test_user_insert PASSED
pytest matches the parameter name to the fixture function and injects the return value automatically.
3. Set scope to control fixture lifetime
@pytest.fixture(scope="session")
def config():
return load_config("test_config.yaml")
@pytest.fixture(scope="module")
def database():
db = setup_test_database()
yield db
teardown_test_database(db)
Scope options: function (default, per test), class, module, session (once per run). Use session for expensive setup like loading ML models.
4. Share fixtures across test files with conftest.py
# conftest.py
import pytest
@pytest.fixture
def api_client():
from myapp import create_app
app = create_app()
return app.test_client()
Any test file in the same directory or subdirectories can use api_client without importing it.
5. Parameterize a fixture for multiple scenarios
@pytest.fixture(params=["sqlite", "postgresql"])
def database(request):
if request.param == "sqlite":
db = setup_sqlite()
else:
db = setup_postgres()
yield db
db.close()
This runs every test that uses database once for each parameter value.
6. Use built-in fixtures
def test_file_write(tmp_path):
d = tmp_path / "subdir"
d.mkdir()
f = d / "test.txt"
f.write_text("hello")
assert f.read_text() == "hello"
def test_output(capsys):
print("hello")
captured = capsys.readouterr()
assert captured.out == "hello\n"
7. Autouse fixtures for setup that must always run for every test
@pytest.fixture(autouse=True)
def setup_test_environment():
os.environ["TESTING"] = "true"
yield
os.environ.pop("TESTING", None)
The autouse=True parameter runs the fixture for every test automatically without declaring it as a parameter. Useful for environment variables, temp directories, or mock patches that every test needs. Use autouse sparingly — too many implicit fixtures make tests harder to debug and understand.
8. Teardown with addfinalizer for complex cleanup
@pytest.fixture
def db():
db = setup_database()
def teardown():
db.close()
cleanup_temp_files()
request.addfinalizer(teardown)
return db
Use request.addfinalizer when you need multiple cleanup actions or when cleanup logic depends on fixture state that changes during the test.
Prevention
- Use
scope="session"for expensive fixtures like database connections - Keep shared fixtures in
conftest.pyso test files don't need imports - Use
yieldinstead ofreturnfor fixtures that need cleanup - Never call fixtures directly — let pytest inject them
- Name fixtures clearly:
db_sessionnots - Use
autouse=Truesparingly — implicit fixtures can make tests harder to understand
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro