繁体   English   中英

如何在 FastAPI 中测试 @app.on_event("shutdown")?

[英]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(...)功能编写(单元)测试?


相关文章

  • 这篇 SO 帖子也提出了类似的问题,但不是在“测试环境”中
  • 官方文档有类似的东西,但是没有on_event("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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM