Unit Tests
NotesYou may prefer to move forward using Test-driven development (TDD), which is a software development methodology that emphasizes the creation of automated tests before writing the code itself. The process starts with writing a test case that defines the desired behaviour of the software. The developer then writes the minimal amount of code necessary to pass that test and refactors the code as required to ensure that it is maintainable and efficient. TDD also promotes good coding practices, such as modularization and separation of concerns, by forcing developers to think about the design and architecture of the software before writing any code. While TDD can require more effort and time upfront, it can ultimately result in higher-quality software with fewer bugs and greater flexibility.
The pytest framework makes it easy to write small tests. FastAPI’s TestClient is built on httpx, which fastapi[standard] already includes, so only pytest is needed:
pip install pytestAdd it to non_ver_reqs.txt:
fastapi[standard]
pydantic-settings
pytestpip freeze > requirements.txtThe following example is a basic unit tests for the health API that checks the status code and JSON response, add a file test_main.py in the root of your project:
from fastapi.testclient import TestClient
from main import main_app
client = TestClient(main_app)
# Test health API
def test_get_health():
response = client.get("/api/v1/health")
assert response.status_code == 200
assert response.json() == {"health": "ok"}
assert response.headers["x-health-check"] == "ok"
assert "x-process-time" in response.headersTest functions are plain def functions and the client calls aren’t awaited, even though the endpoints are async. TestClient takes care of that.
You simply run the command pytest to run the test/s:
pytest============================= test session starts ==============================
platform linux -- Python 3.14.10, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/pywebdev/projects/example-for-you
plugins: anyio-4.16.0
collected 1 item
test_main.py . [100%]
============================== 1 passed in 0.20s ===============================