Geautomatiseerd testen met FastAPI

Introductie tot FastAPI

Matt Eckerle

Software and Data Engineering Leader

Wat zijn geautomatiseerde tests?

Unittests

  • Focus: Geïsoleerde code
  • Doel: Functie van code valideren
  • Scope: Functie of methode
  • Omgeving: Afgezonderde Python-omgeving
def test_main():
    response = main()
    assert response == {"msg": "Hello"}

Systeemtests

  • Focus: Geïsoleerde systeemacties
  • Doel: Systeemfunctie valideren
  • Scope: Endpoint
  • Omgeving: Python-omgeving met app actief
def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": 
                               "Hello"}
Introductie tot FastAPI

TestClient gebruiken

TestClient: HTTP‑client voor pytest

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

# Maak testclient met app-context
client = TestClient(app)

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

Fout- of falende responses testen

App

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."}
Introductie tot FastAPI

Laten we oefenen!

Introductie tot FastAPI

Preparing Video For Download...