Test the New Queries
Exit

Test the New Queries

Write tests for date range filtering, spending summary aggregation, and description search

💻

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

Testing the new endpoints

Three endpoints gained new capabilities in Lesson 3. Each one needs at least one test that verifies the new behavior.

Testing date range filtering requires creating expenses with specific dates, then querying with start and end parameters. The test verifies that only expenses within the range are returned.

Testing SQL aggregation requires creating expenses across categories with known amounts, then calling GET /summary and checking the totals. The test verifies that the database-side addition produces the correct sums.

Testing description search requires creating expenses with distinct descriptions, then searching for a term that matches only one of them. The test verifies that the search filters correctly.

Each test follows the same arrange-act-assert structure:

  1. Create known data through client.post()
  2. Make the query
  3. Assert the response matches expectations

Instructions

Add three tests for the new query capabilities.

  1. Define a function called test_filter_by_date_range that accepts client.
    • Create two expenses: one with date="2024-01-01" and description "Old", and one with date="2024-06-15" and description "Recent". Both in category "food" with amount 10.
    • Call client.get("/expenses?start=2024-06-01&end=2024-06-30") and store the result in response.
    • Assert response.status_code equals 200.
    • Assert len(response.json()) equals 1.
    • Assert response.json()[0]["description"] equals "Recent".
  2. Define a function called test_spending_summary that accepts client.
    • Create three expenses: two in "food" with amounts 10 and 20, and one in "transport" with amount 5.
    • Call client.get("/summary") and store the result in response.
    • Assert response.status_code equals 200.
    • Store response.json() in data.
    • Assert data["food"] equals 30.
    • Assert data["transport"] equals 5.
  3. Define a function called test_search_descriptions that accepts client.
    • Create two expenses: one with description "Coffee at Starbucks" (category "food", amount 5) and one with description "Bus ticket" (category "transport", amount 2.50).
    • Call client.get("/expenses?search=coffee") and store the result in response.
    • Assert response.status_code equals 200.
    • Assert len(response.json()) equals 1.
    • Assert "Coffee" is in response.json()[0]["description"].