Writing tests for REST API endpoints
All the tools we need to test our FastAPI application are now ready. All these tests boil down to performing an HTTP request and checking the response to see if it corresponds to what we expect.
Let's start simple with a test for our hello_world
path operation function. You can see it in the following code:
chapter9_app_test.py
@pytest.mark.asyncio async def test_hello_world(test_client: httpx.AsyncClient): response = await test_client.get("/") assert response.status_code == status.HTTP_200_OK json = response.json() assert json == {"hello": "world"}
First of all, notice that the test function is defined as async. As we mentioned previously, to make it work with pytest, we had to install...