Test Error Cases
Write tests that verify your API returns the correct errors for invalid requests
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Why test errors
Your API already handles errors — requesting a nonexistent expense returns a 404, and sending invalid data returns a 422. But without tests, you have no way to know these error responses stay consistent as you change the code.
Error tests are especially valuable because they catch regressions. If you accidentally remove a validation rule or change an error message, the test fails immediately.
What to test
You will write three error tests:
- GET a nonexistent expense: should return 404
- POST with a negative amount: should return 422 (Pydantic validation rejects it)
- DELETE a nonexistent expense: should return 404
Each test sends a request that should fail and asserts the correct status code. The pattern is simpler than success tests because you do not need to check response body details — the status code is the important signal.
Instructions
Add tests for error cases.
- Define a function called
test_get_nonexistent. Callclient.get("/expenses/999999")and assert thatresponse.status_codeequals404. - Define a function called
test_create_invalid. Callclient.post("/expenses", json={"description": "Test", "amount": -5, "category": "food"})and assert thatresponse.status_codeequals422. - Define a function called
test_delete_nonexistent. Callclient.delete("/expenses/999999")and assert thatresponse.status_codeequals404.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding