Why Your Tests Broke
Exit

Why Your Tests Broke

Understand why every test returns 401 and how to fix them

Every test fails with 401

Every expense endpoint now requires a valid JWT token. The existing tests send requests without an Authorization header. FastAPI rejects each request with a 401 Unauthorized response before the endpoint code runs.

Run the tests now and you see 14 failures. The three Pydantic validation tests still pass because they test the Expense model directly — no HTTP request, no authentication needed. The global exception handler test also passes because it overrides the session dependency before authentication runs.

The fix: two helper functions

You need two helper functions that handle registration and login for your tests:

  • register_user(client, email, password): calls POST /register with the given email and password, and returns the response
  • auth_header(client, email, password): calls register_user, then POST /login, extracts the access token, and returns a dict {"Authorization": "Bearer "} ready to pass as headers=

With these helpers, updating a test takes one extra line:

def test_create_expense(client):
    headers = auth_header(client)
    response = client.post("/expenses", json={...}, headers=headers)

The starter code in the next chapter already has all 18 existing tests updated to use headers=auth_header(client). You only write the two helper functions.

Next Chapter →