You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中如何为@app.on_event("shutdown")关闭事件编写单元测试

FastAPI shutdown事件单元测试实现方案

依赖准备

你需要提前安装测试所需的依赖:
pip install pytest fastapi httpx

测试代码实现

新建测试文件test_main.py,内容如下:

import os
from fastapi.testclient import TestClient
from main import app

TEST_FILE = "shutdown-test-file.txt"

def test_shutdown_handler():
    # 提前清理历史测试残留文件,避免影响测试结果
    if os.path.exists(TEST_FILE):
        os.remove(TEST_FILE)
    
    # 上下文管理器退出时会自动触发shutdown事件
    with TestClient(app):
        # 可在此处添加正常的接口请求逻辑,无相关需求也可以留空
        pass
    
    # 验证shutdown逻辑执行结果
    assert os.path.exists(TEST_FILE), "shutdown事件未触发,目标文件未生成"
    with open(TEST_FILE, "r", encoding="utf-8") as f:
        content = f.read()
    assert content == "FastAPI app has been terminated", "shutdown事件写入内容不符合预期"

    # 测试完成后清理文件,避免残留
    os.remove(TEST_FILE)

运行测试

直接在项目根目录的终端执行pytest命令即可:
pytest test_main.py -v

原理解释

  • FastAPI的TestClient实现了上下文管理器协议,with块进入时会自动触发所有注册的startup事件,块退出时自动触发所有注册的shutdown事件,完全模拟应用真实的启停流程,测试结果和生产运行表现一致
  • 如果你定义的是异步shutdown处理函数,只需要将TestClient替换为httpx.AsyncClient,使用async with语法管理上下文即可

内容的提问来源于stack exchange,提问作者JPG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 18:54:07