Test Registration and Login
Exit

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 id and email but 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)

  1. Define a function called test_register_user that takes client.
  2. Call client.post("/register", json={"email": "new@example.com", "password": "pass123"}) and store the result in response.
  3. Assert response.status_code equals 201.
  4. Assert response.json()["email"] equals "new@example.com" and assert "id" is in response.json().
  5. Assert "password" is not in response.json() — the password must never appear in the response.

Test 2: Duplicate registration rejected (Steps 6–8)

  1. Define a function called test_register_duplicate_email that takes client.
  2. 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 in response.
  3. Assert response.status_code equals 400.

Test 3: Wrong password rejected (Steps 9–11)

  1. Define a function called test_login_wrong_password that takes client.
  2. Call client.post("/register", json={"email": "user@example.com", "password": "correct"}) to create an account. Then call client.post("/login", json={"email": "user@example.com", "password": "wrong"}) and store the result in response.
  3. Assert response.status_code equals 401.