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 callingPOST /register. Takesclient,email, andpasswordas parameters, with defaults so most tests can callregister_user(client)with no extra arguments.auth_header: Does the full flow — callsregister_user, then logs in withPOST /login, extracts the token, and returns a ready-to-use headers dictionary. Every test below callsauth_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)
- Define a function called
register_userthat takes three parameters:client,emailwith default"test@example.com", andpasswordwith default"testpass123". - Return
client.post("/register", json={"email": email, "password": password}).
auth_header — register, log in, return headers (Steps 3–7)
- Define a function called
auth_headerthat takes the same three parameters:client,emailwith default"test@example.com", andpasswordwith default"testpass123". - Call
register_user(client, email, password)to create the account. - Call
client.post("/login", json={"email": email, "password": password})and store the result inresponse. - Extract the token: store
response.json()["access_token"]intoken. - Return the headers dictionary
{"Authorization": f"Bearer {token}"}— this is the format that FastAPI expects for bearer token authentication.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding