![](/img/trans.png)
[英]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.