Witaj, @name! Darwin z testing dla FastAPI! 🧪✅
Testing to krytyczna część produkcyjnych aplikacji. FastAPI ma świetne wsparcie dla pytest!
Analogia Safari: Testing to jak weryfikacja sprzętu przed safari - sprawdzamy, czy GPS działa, czy pojazd jest sprawny, czy radio łapie! Lepiej wykryć problemy przed wycieczką! 🔧✅
1pip install pytest httpx pytest-asyncio1# 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": "Gepard",
27 "scientific_name": "Acinonyx jubatus",
28 "population": 7100,
29 "habitat": "savanna"
30 })
31 assert response.status_code == 201
32 assert response.json()["name"] == "Gepard"
33
34def test_species_not_found():
35 response = client.get("/species/999")
36 assert response.status_code == 404Uruchom testy:
1pytest1import 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 == 200Następna lekcja: Production deployment! 🚀