Skip to main content

Setting up test cases

FastAPI has built-in support for testing which allows us to create automated tests for our applications. In this tutorial, we will learn how to set up test cases for our FastAPI application.

What is Testing in FastAPI?

Testing is a crucial part of the development process. It allows us to automatically verify our code works as expected and helps prevent regressions when changes are made.

In FastAPI, we use the pytest module for testing. pytest is a powerful Python testing framework that can test all levels of your application, from unit to end-to-end tests.

Setting Up Your Environment

Before we start writing tests, we need to set up our environment. First, install pytest:

pip install pytest

Then, create a new file in your project directory named test_main.py. This is where we will write our tests.

Writing Your First Test

Let's create a very basic test. In this test, we will check if the application instance is created successfully.

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_read_main():
response = client.get("/")
assert response.status_code == 200

Here, we create a TestClient instance with our FastAPI application. We then send a GET request to the root ("/") path. We expect the status code to be 200, indicating a successful request.

Running Your Tests

To run your tests, use the following command in your terminal:

pytest

If everything is set up correctly, you should see output indicating the tests are passing.

Testing POST Requests

Testing POST requests is a bit more involved because you need to send data with the request. Here's how you can do it:

def test_create_item():
response = client.post("/items/", json={"name": "Foo", "price": 42.0})
assert response.status_code == 201
assert response.json() == {"id": "Foo", "price": 42.0}

Here, we send a POST request to "/items/" with a JSON payload. We then check if the status code is 201 (created) and the response matches our input.

Summary

Setting up test cases in FastAPI with pytest is straightforward. We've covered how to set up your environment, write basic tests, run them, and how to test POST requests. Remember that testing is an essential part of the development process that improves the quality of your code and makes it more maintainable.


That's all for this tutorial. Happy testing!