Testing FastAPI applications
Testing is necessary to ensure that your application behaves the way it is supposed to. This chapter won’t cover test-driven development (TDD), in which tests are written before the actual code. However, there are some specific issues that you may run into when working with the async MongoDB Python driver, called Motor, and FastAPI.
Unit testing your API is essential and simple to set up. Every endpoint should be tested, and each should perform the tasks they are delegated. While unit testing in Python already has several mature frameworks, such as unittest
and pytest
, some FastAPI-specific points are worth mentioning.
The FastAPI documentation (https://fastapi.tiangolo.com/tutorial/testing/) recommends that you use the TestClient
class provided by Starlette. Francois Voron, in his excellent book Building Data Science Applications with FastAPI, recommends a slightly more advanced setup using HTTPX
(an async HTTP library similar to Requests...