Set Up the Test Fixture
Create a pytest fixture that gives each test an isolated in-memory SQLite database
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
What the fixture does
The client fixture sets up a fresh database for each test, injects it into the app, and tears it down when the test finishes:
@pytest.fixture(name="client")
def client_fixture():
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
def get_session_override():
with Session(engine) as session:
yield session
app.dependency_overrides[get_session] = get_session_override
client = TestClient(app)
yield client
app.dependency_overrides.clear()create_engine("sqlite://")— creates an in-memory database. No file on disk.SQLModel.metadata.create_all(engine)— creates theexpensetable in memory.get_session_override— a local generator function that yields sessions from the in-memory engine. This replacesget_sessionfromdatabase.pyduring tests.app.dependency_overrides[get_session] = get_session_override— tells FastAPI to useget_session_overrideinstead ofget_sessionfor any request made through this client.yield client— the fixture pauses here and hands theTestClientto the test. When the test finishes, the fixture resumes.app.dependency_overrides.clear()— removes the override so it does not affect other test runs.
You can see database.py and main.py in the read-only tabs — the fixture imports from both.
Instructions
Create the client fixture in test_main.py.
- Add these imports, each on its own line:
pytestTestClientfromfastapi.testclientSessionandSQLModelandcreate_enginefromsqlmodelget_sessionfromdatabaseappfrommainExpensefrommodelsValidationErrorfrompydantic
- Define a function called
client_fixturewith the@pytest.fixture(name="client")decorator. - Inside
client_fixture, createengine = create_engine("sqlite://", connect_args={"check_same_thread": False}). - Call
SQLModel.metadata.create_all(engine)— this creates theexpensetable in the in-memory database. - Define a nested function called
get_session_override. Inside it, open awith Session(engine) as session:block andyield session. - Set
app.dependency_overrides[get_session] = get_session_override. - Create
client = TestClient(app). yield client.- After the yield, call
app.dependency_overrides.clear().
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding