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:
- Create known data through
client.post() - Make the query
- Assert the response matches expectations
Instructions
Add three tests for the new query capabilities.
- Define a function called
test_filter_by_date_rangethat acceptsclient.- Create two expenses: one with
date="2024-01-01"and description"Old", and one withdate="2024-06-15"and description"Recent". Both in category"food"with amount10. - Call
client.get("/expenses?start=2024-06-01&end=2024-06-30")and store the result inresponse. - Assert
response.status_codeequals200. - Assert
len(response.json())equals1. - Assert
response.json()[0]["description"]equals"Recent".
- Create two expenses: one with
- Define a function called
test_spending_summarythat acceptsclient.- Create three expenses: two in
"food"with amounts10and20, and one in"transport"with amount5. - Call
client.get("/summary")and store the result inresponse. - Assert
response.status_codeequals200. - Store
response.json()indata. - Assert
data["food"]equals30. - Assert
data["transport"]equals5.
- Create three expenses: two in
- Define a function called
test_search_descriptionsthat acceptsclient.- Create two expenses: one with description
"Coffee at Starbucks"(category"food", amount5) and one with description"Bus ticket"(category"transport", amount2.50). - Call
client.get("/expenses?search=coffee")and store the result inresponse. - Assert
response.status_codeequals200. - Assert
len(response.json())equals1. - Assert
"Coffee"is inresponse.json()[0]["description"].
- Create two expenses: one with description
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding