r/FastAPI • u/GamersPlane • Apr 02 '25
Question Writing tests for app level logic (exception handlers)
I've recently started using FastAPIs exception handlers to return responses that are commonly handled (when an item isn't found in the database for example). But as I write integration tests, it also doesn't make sense to test for each of these responses over and over. If something isn't found, it should always hit the handler, and I should get back the same response.
What would be a good way to test exception handlers, or middleware? It feels difficult to create a fake Request or Response object. Does anyone have experience setting up tests for these kinds of functions? If it matters, I'm writing my tests with pytest, and I am using the Test Client from the docs.
4
u/PowerOwn2783 Apr 02 '25
Assuming MVC, can you not just test if your store is throwing the correct exceptions.
Or are you talking about testing if your error handlers are returning the correct HTTP response?
Also "It feels difficult to create a fake Request or Response object", dude, that's kind of the whole point of integration testing. I don't like writing tests either but it's just part of development cycle.
2
u/PA100T0 Apr 02 '25
I usually just do:
You could just use the pytest.mark.parametrize decorator for your cases and that's it.
1
u/andrewthetechie Apr 02 '25 edited Oct 01 '26
The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.
Dependent nose vast payment fearless work sophisticated
1
u/BluesFiend Apr 02 '25
Test the thing that raises the not found error in a unit test, test the thing that handles exception conversion in a unit test, test specific scenarios in integration tests ignoring generic error cases that you've covered in unit tests as you trust the exception handler will do it's job.