Test Data Isolation
Exit

Test Data Isolation

Write a test that proves two users each see only their own expenses

💻

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

The most important test

This single test proves the entire authentication system works correctly. Two different users each create an expense, and each user sees only their own data.

This test exercises every layer of the auth system at once: registration, login, token generation, token validation, expense creation with user ownership, and per-user filtering. If this test passes, your API properly isolates data between users.

Instructions

Write a test that proves two users each see only their own expenses. This single test exercises every layer of the auth system: registration, login, token generation, token validation, expense creation with ownership, and per-user filtering.

  1. Define a function called test_data_isolation that takes client.
  2. Set up two separate users with their own credentials and tokens:
    • Store auth_header(client, "alice@example.com", "pass123") in headers_a
    • Store auth_header(client, "bob@example.com", "pass456") in headers_b
  3. Create one expense for each user:
    • Call client.post("/expenses", json={"description": "Alice lunch", "amount": 10, "category": "food"}, headers=headers_a)
    • Call client.post("/expenses", json={"description": "Bob bus", "amount": 5, "category": "transport"}, headers=headers_b)
  4. Fetch each user's expenses to verify they only see their own:
    • Store client.get("/expenses", headers=headers_a).json() in alice_expenses
    • Store client.get("/expenses", headers=headers_b).json() in bob_expenses
  5. Assert that Alice sees only her expense:
    • Assert len(alice_expenses) equals 1
    • Assert alice_expenses[0]["description"] equals "Alice lunch"
  6. Assert that Bob sees only his expense:
    • Assert len(bob_expenses) equals 1
    • Assert bob_expenses[0]["description"] equals "Bob bus"