I have a simple FastAPI setup as below,
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello World"}
How can I write (unit)test for this app_shutdown(...)
functionality?
on_event("shutdown")
According to the documentation , you need to wrap it in the context manager (a with
statement) to trigger the events, something like this:
def test_read_items():
with TestClient(app) as client:
response = client.get("/items/foo")
assert response.status_code == 200
If you use pytest
, you can set up a fixture for it like this:
from main import app
from fastapi.testclient import TestClient
import pytest
@pytest.fixture
def client():
with TestClient(app) as c:
yield c
def test_read_main(client):
response = client.get("/")
assert response.status_code == 200
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.