Sub topic 9
Sharing fixtures through conftest.py
This chapter assumes you can write a basic pytest fixture with @pytest.fixture and know how pytest finds test files. Here you will move fixtures out of individual test files so that many files can use them.
The problem: copied fixtures
Suppose test_users.py and test_orders.py both need the in-memory database from the previous chapter. Copying the db fixture into each file works, but the copies drift apart. A fix in one file is easy to forget in the other.
What conftest.py does
conftest.py is a special file that pytest loads on its own. Any fixture defined in it is available to every test in the same directory and in all subdirectories. You never import it. Pytest finds it during collection, which is the step where it discovers tests.
# tests/conftest.py
import sqlite3
import pytest
@pytest.fixture
def db():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT)")
yield conn
conn.close()# tests/test_users.py
def test_insert_user(db):
db.execute("INSERT INTO users VALUES ('ada')")
count = db.execute("SELECT COUNT(*) FROM users").fetchone()[0]
assert count == 1test_users.py has no import for db. Pytest sees the argument name db, looks in the test module, and then in each conftest.py going up the directory tree.
Scope of a conftest.py
A conftest.py only serves tests at or below its own directory.
tests/
conftest.py # fixtures for every test
test_users.py
api/
conftest.py # fixtures for tests in api/ only
test_routes.pyA fixture in tests/api/conftest.py is invisible to tests/test_users.py. Put a fixture as deep as possible while still covering every test that needs it.
Overriding a fixture
If a fixture has the same name at several levels, the closest one wins. Order of lookup is the test module, then the nearest conftest.py, then the parents. This lets a subdirectory replace a general fixture, for example to use a different database.
The diagram below shows the lookup order.
Common errors
- Importing from conftest. Do not write
from conftest import db. This can load the file twice and breaks the lookup rules. Request the fixture by argument name only. - Fixture not found. The fixture is in a
conftest.pythat is not above the test. Check the directory layout. - Putting tests in conftest.py. Pytest does not collect tests from it by default. Keep it for fixtures and hooks.
- Too much in one file. A huge root
conftest.pyis hard to read. Keep only widely shared fixtures at the root.
Exercise
A fixture client is defined in tests/api/conftest.py. Can a test in tests/test_users.py use it? Where would you move the fixture so both can use it?
Show answer
No. A conftest.py only applies to its own directory and below, and tests/test_users.py sits above tests/api/. Move the fixture to tests/conftest.py so tests in both places can request it by name.