Test the Logging Middleware
Exit

Test the Logging Middleware

Write a test that verifies the middleware does not break your API responses

💻

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

What to test about middleware

Middleware wraps every request. If the middleware has a bug — for example, it forgets to return the response — every endpoint breaks. A middleware test verifies that requests still work correctly after the middleware is added.

You do not need to test the log output itself. The important thing is that the middleware does not interfere with the normal request-response cycle. If a POST to /expenses still returns 201 with the correct data, the middleware is working correctly.

Reusing the TestClient

Your test file already has a TestClient from the previous lesson. The middleware test uses the same client — TestClient exercises the full middleware stack automatically. Any middleware registered on your app runs on every TestClient request, just like it would on a real server.

Instructions

Add a test that verifies the middleware does not break responses.

  1. Define a function called test_middleware_does_not_break_response.
  2. Inside it, call client.post("/expenses", json={"description": "Test", "amount": 5.00, "category": "food"}) and store the result in response.
  3. Add two assertions, each on its own line:
    • response.status_code equals 201
    • response.json()["description"] equals "Test"