如何在测试中触发 startup/shutdown 事件?

解读

国内一线互联网公司在单元测试/集成测试阶段,普遍要求“零副作用”与“可重复”两条硬指标。
FastAPI 的 startup/shutdown 事件通常用来初始化连接池、注册钩子、清理临时文件,如果测试用例里不触发它们,会出现“本地能跑、CI 爆红”的典型事故。
面试官问这道题,核心想确认两点:

  1. 你是否知道 TestClient 默认不会自动触发 lifespan 事件;
  2. 你是否掌握官方推荐的 TestClient(app) 上下文管理器写法,以及如何在 pytest fixture 里复用,从而保证测试代码与生产代码生命周期一致。

知识点

  1. Starlette 的 lifespan 协议:ASGI 的 {"type": "lifespan.startup"} 与 {"type": "lifespan.shutdown"} 消息。
  2. fastapi.testclient.TestClient 是对 starlette.testclient.TestClient 的薄封装,内部使用 requests.Session 同步调用,只有在 with TestClient(app) as c: 进入/退出时才会发送 lifespan 消息。
  3. 直接 client = TestClient(app) 而不使用上下文管理器,Starlette 会回退到旧模式,不触发任何事件。
  4. pytest 中推荐把 client 做成 session 或 function 级别的 fixture,并显式 yield 以保证 shutdown 一定被执行。
  5. 如果使用了 async 路由,需要再包一层 httpx.AsyncClient 与 async with LifespanManager(app),但 99% 的国内项目目前仍用同步 TestClient 即可。
  6. 事件里如果抛出异常,Starlette 会将其封装成 starlette.exceptions.LifespanFailure,测试侧可直接 pytest.raises 捕获,验证失败场景。

答案

代码层面最简洁、面试最加分的写法是“pytest fixture + 上下文管理器”:

# conftest.py
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app.main import app  # 业务 FastAPI 实例

@pytest.fixture(scope="function", autouse=False)
def client():
    # 进入 with 块时自动发送 lifespan.startup
    with TestClient(app) as c:
        yield c
    # 退出 with 块时自动发送 lifespan.shutdown

测试用例里直接注入即可:

def test_ping(client):
    resp = client.get("/ping")
    assert resp.status_code == 200

如果面试官追问“如何手动触发”,可补充:

from fastapi.testclient import TestClient
client = TestClient(app)
# 手动触发
client.app.state.router.lifespan.startup()
# 测试逻辑...
client.app.state.router.lifespan.shutdown()

但强调:官方文档明确不推荐手动调用,容易遗漏异常处理,生产测试应一律使用上下文管理器。

拓展思考

  1. 全异步栈:当项目全部路由都是 async def 且使用了 httpx.AsyncClient 时,需要引入 asgi-lifespan 的 LifespanManager,否则依旧不会触发事件。
  2. 多实例场景:微服务单元测试常出现“一个 pytest 进程里起多个 FastAPI 子服务”,此时每个子服务必须各自 with TestClient(sub_app) as c:,否则连接池会串扰,导致“端口占用”或“数据库事务未回滚”的假失败。
  3. 事件异常测试:在 startup 里主动 raise RuntimeError("db connect fail"),用 pytest.raises(RuntimeException) 捕获 Starlette 抛出的 LifespanFailure,可验证启动失败时的降级逻辑,这是高级测试用例的加分项。