Rewrite Existing Tests
Exit

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.

  1. Define a function called test_global_exception_handler. It does not accept the client fixture — it sets up its own broken client.
  2. Inside it, define a nested function called broken_session that raises RuntimeError("test error").
  3. Set app.dependency_overrides[get_session] = broken_session.
  4. Create broken_client = TestClient(app).
  5. Call broken_client.post("/expenses", json={"description": "Test", "amount": 5.00, "category": "food"}) and store the result in response.
  6. Set app.dependency_overrides.clear().
  7. Assert that response.status_code equals 500.
  8. Assert that response.json()["detail"] equals "Internal server error".