Tests automatisés avec FastAPI

Introduction à FastAPI

Matt Eckerle

Software and Data Engineering Leader

Qu'est-ce qu'un test automatisé ?

Tests unitaires

  • Focus : Code isolé
  • Objectif : Valider le fonctionnement du code
  • Portée : Fonction ou méthode
  • Environnement : Environnement Python isolé
def test_main():
    response = main()
    assert response == {"msg": "Hello"}

Tests système

  • Focus : Opérations système isolées
  • Objectif : Valider le fonctionnement du système
  • Portée : Endpoint
  • Environnement : Environnement Python avec l'app en cours d'exécution
def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": 
                               "Hello"}
Introduction à FastAPI

Utiliser TestClient

TestClient : client HTTP pour pytest

# Importer TestClient et l'app
from fastapi.testclient import TestClient
from .main import app

# Créer un client de test avec le contexte de l'application
client = TestClient(app)

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

Tester les réponses d'erreur ou d'échec

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."}
Introduction à FastAPI

Passons à la pratique !

Introduction à FastAPI

Preparing Video For Download...