[英]Difference between connecting to the database in app.on_event('startup') vs in a dependency in FastAPI
[英]How to test @app.on_event("shutdown") in FastAPI?
我有一個簡單的 FastAPI 設置,如下所示,
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.on_event("shutdown") def app_shutdown(): with open("shutdown-test-file.txt", "w") as fp: fp.write("FastAPI app has been terminated")
@app.get("/")
def root():
return {"message": "Hello World"}
如何為此app_shutdown(...)
功能編寫(單元)測試?
根據文檔,您需要將其包裝在上下文管理器( with
語句)中以觸發事件,如下所示:
def test_read_items():
with TestClient(app) as client:
response = client.get("/items/foo")
assert response.status_code == 200
如果您使用pytest
,您可以為它設置一個夾具,如下所示:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.