Testing with Pytest
Testing with Pytest in FastAPI
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. To ensure the reliability and robustness of your FastAPI application, it's crucial to incorporate testing into your development process. In this tutorial, we'll explore how to use Pytest, a popular testing framework in Python, to test FastAPI applications.
What is Pytest?
Pytest is a mature full-featured Python testing tool that helps you write better programs. It simplifies the process of writing simple, scalable tests for your applications.
Setting up Your Environment
Before we get started, ensure you have FastAPI and Pytest installed in your environment. If you haven't, you can install them using pip:
pip install fastapi[all]
pip install pytest
Writing Your First Test
Now that we have our environment set up, let's write our first test. First, we need to create a FastAPI application. Create a new file called main.py
and add the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"Hello": "World"}
This is a basic FastAPI application with a single route.
Next, create a new file called test_main.py
. This is where we'll write our tests. Add the following code:
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"Hello": "World"}
In this code, we create a TestClient
instance with our FastAPI application. We then define a function test_read_root()
to test the root route. The function sends a GET request to the route and asserts that the response status code is 200 and the JSON response body matches {"Hello": "World"}
.
Running Your Tests
To run your tests, navigate to your project directory in your terminal and run the following command:
pytest
Pytest will automatically discover and run your tests, and provide a detailed report.
Testing POST Operations
Let's add a POST operation to our FastAPI application and a corresponding test.
Update your main.py
file to include a POST operation:
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
Now, update your test_main.py
file to include a test for the POST operation:
def test_create_item():
response = client.post("/items/", json={"name": "Foo", "price": 42.0})
assert response.status_code == 200
assert response.json() == {"name": "Foo", "price": 42.0}
Run your tests again using Pytest, and you'll see they all pass.
Conclusion
In this tutorial, we've covered the basics of testing FastAPI applications using Pytest. We've learned how to set up a testing environment, write tests for GET and POST operations, and run our tests.
Remember, testing is a crucial part of the development process. It helps you catch bugs early, ensure code quality, and improve the reliability of your application. So, make sure to write tests for all parts of your application!