Test Get Expense
Exit

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:

  1. Create the data you need with a POST request
  2. Extract the identifier from the POST response
  3. Act on the data using the identifier (GET, DELETE, PATCH)
  4. 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.

  1. Define a function called test_get_expense.
  2. Inside it, create an expense with client.post("/expenses", json=...) and store the result in response.
  3. Extract the identifier with expense_id = response.json()["id"].
  4. Call client.get(f"/expenses/{expense_id}") and store the result in response.
  5. Add two assertions:
    • response.status_code equals 200
    • response.json()["description"] equals the description you sent