Test Registration and Login
Write tests for the registration and login endpoints
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Testing the auth endpoints
The expense tests all use auth_header(client) to get a token, but nothing tests whether registration and login themselves work correctly. If the registration endpoint silently leaks password hashes, or if login accepts wrong passwords, no existing test would catch it.
Three tests cover the most critical auth behaviors:
- Successful registration: The response must include
idandemailbut never the password. Leaking password data — even hashed — is a security risk. - Duplicate registration: Registering the same email twice must return
400. Without this, users could overwrite each other's accounts. - Wrong password login: Bad credentials must return
401. This confirms the password hashing and verification logic actually works.
Each test calls the auth endpoints directly. No helper functions needed — these tests exercise the raw behavior of POST /register and POST /login.
Instructions
Add three tests for the auth endpoints. Each test uses a different email to avoid conflicts between tests.
Test 1: Successful registration (Steps 1–5)
- Define a function called
test_register_userthat takesclient. - Call
client.post("/register", json={"email": "new@example.com", "password": "pass123"})and store the result inresponse. - Assert
response.status_codeequals201. - Assert
response.json()["email"]equals"new@example.com"and assert"id"is inresponse.json(). - Assert
"password"is not inresponse.json()— the password must never appear in the response.
Test 2: Duplicate registration rejected (Steps 6–8)
- Define a function called
test_register_duplicate_emailthat takesclient. - Call
client.post("/register", json={"email": "dupe@example.com", "password": "pass123"})to create the first account. Then call the same endpoint again with the same email and store the result inresponse. - Assert
response.status_codeequals400.
Test 3: Wrong password rejected (Steps 9–11)
- Define a function called
test_login_wrong_passwordthat takesclient. - Call
client.post("/register", json={"email": "user@example.com", "password": "correct"})to create an account. Then callclient.post("/login", json={"email": "user@example.com", "password": "wrong"})and store the result inresponse. - Assert
response.status_codeequals401.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding