Test Get Expense
Write a test for retrieving a single expense by its identifier
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Testing endpoints with path parameters
The GET /expenses/{expense_id} endpoint uses a path parameter to identify which expense to retrieve. To test it, you first create an expense, extract its identifier from the response, and then use that identifier in the next request.
The create-then-act pattern
This pattern appears in most endpoint tests:
- Create the data you need with a POST request
- Extract the identifier from the POST response
- Act on the data using the identifier (GET, DELETE, PATCH)
- Assert the result
You will use this same pattern in the next few chapters to test GET, DELETE, and PATCH.
Instructions
Add a test for the get endpoint.
- Define a function called
test_get_expense. - Inside it, create an expense with
client.post("/expenses", json=...)and store the result inresponse. - Extract the identifier with
expense_id = response.json()["id"]. - Call
client.get(f"/expenses/{expense_id}")and store the result inresponse. - Add two assertions:
response.status_codeequals200response.json()["description"]equals the description you sent
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding