Automatyczne testowanie FastAPI

Wprowadzenie do FastAPI

Matt Eckerle

Software and Data Engineering Leader

Czym są testy automatyczne?

Testy jednostkowe

  • Zakres: Izolowany kod
  • Cel: Weryfikacja funkcji kodu
  • Obszar: Funkcja lub metoda
  • Środowisko: Izolowane środowisko Python
def test_main():
    response = main()
    assert response == {"msg": "Hello"}

Testy systemowe

  • Zakres: Izolowane operacje systemu
  • Cel: Weryfikacja funkcji systemu
  • Obszar: Endpoint
  • Środowisko: Środowisko Python z uruchomioną aplikacją
def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": 
                               "Hello"}
Wprowadzenie do FastAPI

Korzystanie z TestClient

TestClient: klient HTTP dla pytest

# Import TestClient and app
from fastapi.testclient import TestClient
from .main import app

# Create test client with application context
client = TestClient(app)

def test_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello"}
Wprowadzenie do FastAPI

Testowanie odpowiedzi błędów i niepowodzeń

Aplikacja

app = FastAPI()

@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        raise HTTPException(
            status_code=404, 
            detail="Item not found.")
    else:
        delete_item_in_database(item)
        return {}

Test

def test_delete_nonexistent_item():
    response = client.delete(
        "/items",
        json={"id": -999})
    assert response.status_code == 404
    json = response.json()
    assert json == {"detail":
                    "Item not found."}
Wprowadzenie do FastAPI

Czas na ćwiczenia!

Wprowadzenie do FastAPI

Preparing Video For Download...