Ir para o conteúdo

Testing Events: startup - shutdown


The current page still doesn't have a translation for this language.

But you can help translating it: Contributing.

When you need your event handlers (startup and shutdown) to run in your tests, you can use the TestClient with a with statement:

from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

items = {}

async def startup_event():
    items["foo"] = {"name": "Fighters"}
    items["bar"] = {"name": "Tenders"}

async def read_items(item_id: str):
    return items[item_id]

def test_read_items():
    with TestClient(app) as client:
        response = client.get("/items/foo")
        assert response.status_code == 200
        assert response.json() == {"name": "Fighters"}