Test List and Filter
Exit

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.

  1. Define a function called test_list_expenses.
  2. Inside it, create two expenses by calling client.post("/expenses", json=...) twice:
    • One with category="food"
    • One with category="transport"
  3. Call client.get("/expenses") and store the result in response.
  4. Add two assertions:
    • response.status_code equals 200
    • len(response.json()) is greater than or equal to 2
  5. Define a function called test_filter_by_category.
  6. Inside it, create an expense with category="transport" using client.post().
  7. Call client.get("/expenses?category=transport") and store the result in response.
  8. Add two assertions:
    • response.status_code equals 200
    • Every item has category equal to "transport" — use all(e["category"] == "transport" for e in response.json())