Test List and Filter
Write tests for listing expenses and filtering by category
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Testing endpoints that return lists
The GET /expenses endpoint returns all expenses, and it supports an optional category query parameter to filter results. Testing this requires a setup step: you need to create expenses before you can list them.
Setting up test data
Each test creates its own data by calling client.post(). This keeps tests independent — they do not rely on data from other tests. When you need two expenses to test the list endpoint, create two expenses at the start of the test.
Testing query parameters
To test filtering, pass query parameters in the URL: client.get("/expenses?category=food"). The response should contain only expenses that match the category.
The key assertion for filtering: check that every returned expense has the expected category. If the filter is broken and returns all expenses, this assertion catches it.
Instructions
Add tests for the list and filter endpoints.
- Define a function called
test_list_expenses. - Inside it, create two expenses by calling
client.post("/expenses", json=...)twice:- One with
category="food" - One with
category="transport"
- One with
- Call
client.get("/expenses")and store the result inresponse. - Add two assertions:
response.status_codeequals200len(response.json())is greater than or equal to2
- Define a function called
test_filter_by_category. - Inside it, create an expense with
category="transport"usingclient.post(). - Call
client.get("/expenses?category=transport")and store the result inresponse. - Add two assertions:
response.status_codeequals200- Every item has
categoryequal to"transport"— useall(e["category"] == "transport" for e in response.json())
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding