Auth Test Helpers

Write register_user and auth_header helper functions for authenticated tests

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Every test needs a token now

Your endpoints are protected. Every test that creates, reads, updates, or deletes an expense must send a valid token in the request headers. Without it, the endpoint returns 401 Unauthorized.

Getting a token requires two API calls: register a user, then log in. That is four lines of setup code. If you copy those four lines into every test, you end up with duplicated code that is hard to maintain.

Instead, you write two helper functions:

  • register_user: Creates a test account by calling POST /register. Takes client, email, and password as parameters, with defaults so most tests can call register_user(client) with no extra arguments.
  • auth_header: Does the full flow — calls register_user, then logs in with POST /login, extracts the token, and returns a ready-to-use headers dictionary. Every test below calls auth_header(client) to get that dictionary.

Instructions

Write two helper functions at the top of the test file. Every protected-endpoint test below already calls these functions — you just need to implement them.

register_user — create a test account (Steps 1–2)

  1. Define a function called register_user that takes three parameters: client, email with default "test@example.com", and password with default "testpass123".
  2. Return client.post("/register", json={"email": email, "password": password}).

auth_header — register, log in, return headers (Steps 3–7)

  1. Define a function called auth_header that takes the same three parameters: client, email with default "test@example.com", and password with default "testpass123".
  2. Call register_user(client, email, password) to create the account.
  3. Call client.post("/login", json={"email": email, "password": password}) and store the result in response.
  4. Extract the token: store response.json()["access_token"] in token.
  5. Return the headers dictionary {"Authorization": f"Bearer {token}"} — this is the format that FastAPI expects for bearer token authentication.