Test the Error Handler
Exit

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.

  1. Add from unittest.mock import patch to the imports.
  2. Define a function called test_global_exception_handler.
  3. Inside it, open a with patch("main.save_expenses", side_effect=RuntimeError("test error")): block. This temporarily replaces save_expenses with a function that raises a RuntimeError, so you can trigger the exception handler.
  4. Inside the block, call client.post("/expenses", json={"description": "Test", "amount": 5.00, "category": "food"}) and store the result in response.
  5. Add two assertions, each on its own line:
    • response.status_code equals 500
    • response.json()["detail"] equals "Internal server error"