简体   繁体   中英

How to test @app.on_event("shutdown") in FastAPI?

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?


Related Posts

  • This SO post is also asking similar question, but, not in a "testing context"
  • The official doc has something similar, but, there is no example for 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.

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