簡體   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