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.
- Define a function called
test_middleware_does_not_break_response. - Inside it, call
client.post("/expenses", json={"description": "Test", "amount": 5.00, "category": "food"})and store the result inresponse. - Add two assertions, each on its own line:
response.status_codeequals201response.json()["description"]equals"Test"
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding