Rewrite Existing Tests
Update all existing tests to use the client fixture for database isolation
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
What changed in test_main.py
The starter code for this chapter already reflects the updates. Here is what happened and why:
The global client is gone. The old client = TestClient(app) at the top of the file created one client shared by all tests. That meant all tests wrote to the same database and could interfere with each other. It has been removed.
Every test now accepts client as a parameter. When pytest sees a test function with a parameter named client, it calls the client_fixture and passes the result in automatically. Each test gets its own fresh database — no leftover data from previous tests.
The Pydantic unit tests remain unchanged. test_valid_date, test_invalid_date_format, and test_date_none_allowed test the Expense model directly — no HTTP request, no database. They do not need the client fixture.
The global exception handler test uses a different approach. Instead of patching save_expenses (which no longer exists), it overrides get_session directly with a function that raises an error, then clears the override after the assertion.
Your task
Read through the updated test file. Then add the one missing test — test_global_exception_handler — using the approach described in the content above.
Instructions
Add the global exception handler test.
- Define a function called
test_global_exception_handler. It does not accept theclientfixture — it sets up its own broken client. - Inside it, define a nested function called
broken_sessionthat raisesRuntimeError("test error"). - Set
app.dependency_overrides[get_session] = broken_session. - Create
broken_client = TestClient(app). - Call
broken_client.post("/expenses", json={"description": "Test", "amount": 5.00, "category": "food"})and store the result inresponse. - Set
app.dependency_overrides.clear(). - Assert that
response.status_codeequals500. - Assert that
response.json()["detail"]equals"Internal server error".
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding