Test the Error Handler
Write a test that triggers an unhandled error and verifies the consistent response
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Testing the global handler
Your global exception handler catches any unhandled exception and returns a 500 response with {"detail": "Internal server error"}. To test it, you need to trigger an unhandled exception in one of your endpoints.
How to trigger an error in tests
The simplest approach: use Python's unittest.mock.patch to temporarily replace a function with one that raises an error. You can patch save_expenses to raise a RuntimeError. When the create_expense endpoint calls save_expenses(), the error propagates up to the global exception handler.
from unittest.mock import patch
with patch("main.save_expenses", side_effect=RuntimeError("disk full")):
response = client.post(...)Inside the with block, any call to save_expenses in main.py raises a RuntimeError instead of saving to disk. Outside the block, the original function is restored automatically.
Instructions
Add a test for the global exception handler.
- Add
from unittest.mock import patchto the imports. - Define a function called
test_global_exception_handler. - Inside it, open a
with patch("main.save_expenses", side_effect=RuntimeError("test error")):block. This temporarily replacessave_expenseswith a function that raises aRuntimeError, so you can trigger the exception handler. - Inside the block, 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_codeequals500response.json()["detail"]equals"Internal server error"
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding