We use cookies to enhance your experience on the site
CodeWorlds

Testing - verifying stability

Welcome, @name! Darwin here with testing for FastAPI! 🧪✅

Testing is a critical part of production applications. FastAPI has great support for pytest!

Safari Analogy: Testing is like verifying equipment before a safari - we check if the GPS works, if the vehicle is operational, if the radio has signal! Better to detect problems before the trip! 🔧✅

Installation

1pip install pytest httpx pytest-asyncio

Basic FastAPI test

1# test_main.py
2from fastapi.testclient import TestClient
3from main import app
4
5client = TestClient(app)
6
7def test_root():
8    response = client.get("/")
9    assert response.status_code == 200
10    assert response.json() == {"message": "Hello Safari"}
11
12def test_list_species():
13    response = client.get("/species")
14    assert response.status_code == 200
15    assert isinstance(response.json(), list)
16
17def test_get_species():
18    response = client.get("/species/1")
19    assert response.status_code == 200
20    data = response.json()
21    assert data["id"] == 1
22    assert "name" in data
23
24def test_create_species():
25    response = client.post("/species", json={
26        "name": "Cheetah",
27        "scientific_name": "Acinonyx jubatus",
28        "population": 7100,
29        "habitat": "savanna"
30    })
31    assert response.status_code == 201
32    assert response.json()["name"] == "Cheetah"
33
34def test_species_not_found():
35    response = client.get("/species/999")
36    assert response.status_code == 404

Run tests:

1pytest

Async tests

1import pytest
2from httpx import AsyncClient
3from main import app
4
5@pytest.mark.asyncio
6async def test_list_species_async():
7    async with AsyncClient(app=app, base_url="http://test") as client:
8        response = await client.get("/species")
9        assert response.status_code == 200

Next lesson: Production deployment! 🚀

Go to CodeWorlds