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.
- Define a function called
test_data_isolationthat takesclient. - Set up two separate users with their own credentials and tokens:
- Store
auth_header(client, "alice@example.com", "pass123")inheaders_a - Store
auth_header(client, "bob@example.com", "pass456")inheaders_b
- Store
- 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)
- Call
- Fetch each user's expenses to verify they only see their own:
- Store
client.get("/expenses", headers=headers_a).json()inalice_expenses - Store
client.get("/expenses", headers=headers_b).json()inbob_expenses
- Store
- Assert that Alice sees only her expense:
- Assert
len(alice_expenses)equals1 - Assert
alice_expenses[0]["description"]equals"Alice lunch"
- Assert
- Assert that Bob sees only his expense:
- Assert
len(bob_expenses)equals1 - Assert
bob_expenses[0]["description"]equals"Bob bus"
- Assert
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding