Setting up testing tools for FastAPI with HTTPX
If you look at the FastAPI documentation regarding testing, you’ll see that it recommends that you use TestClient
provided by Starlette. In this book, we’ll show you a different approach involving an HTTP client called HTTPX.
Why? The default TestClient
is implemented in a way that makes it completely synchronous, meaning you can write tests without worrying about async
and await
. This might sound nice, but we found that it causes some problems in practice: since your FastAPI app is designed to work asynchronously, you’ll likely have lots of services working asynchronously, such as the database drivers we saw in Chapter 6, Databases and Asynchronous ORMs. Thus, in your tests, you’ll probably need to perform some actions on those asynchronous services, such as filling a database with dummy data, which will make your tests asynchronous anyway. Melding the two approaches often leads to strange errors that are...