FastAPI:测试环境下异常处理器未执行,如何解决?
测试FastAPI异常处理器时无法触发执行的问题
我正在实现异常处理器逻辑,用于拦截服务层抛出的RetryError。需要说明的是,该处理器签名async def my_handler(request: Request, call_next)中的第二个参数call_next实际是RetryError实例,而非可调用对象。
通过应用运行时的手动测试,我确认修复方案有效,但在为该处理器添加非E2E测试覆盖时遇到极大困难。
核心问题
测试用例无法触发执行处理器函数,但运行时可正常执行。
测试代码
import pytest from fastapi import FastAPI, APIRouter, Request from fastapi.testclient import TestClient from tenacity import retry, stop_max_delay, stop_max_attempt_number, wait_fixed @pytest.fixture(scope="session", name="exception_handler_test_client") def get_test_client() -> TestClient: app = FastAPI() router = APIRouter() # 下方是抛出RetryError的「service」函数 router.add_api_route("/test_exception_handler/", retryable_failure, methods=["GET"]) app.include_router(router) # 实际测试中会将foo替换为待测试的真实异常处理器 app.add_exception_handler(Exception, foo) test_client = TestClient(router) return test_client async def foo(request: Request, call_next): # 为方便展示,真实处理器位于代码库其他位置 # 无论真实处理器还是此示例处理器,异常抛出时均未执行 pass # 该函数会按预期抛出RetryError @retry(wait_fixed=100, stop_max_delay=1000, stop_max_attempt_number=2, retry_on_result=lambda _: True) def retryable_failure(): """ 为测试目的,程序化触发重试函数失败。 """ pass # 实际测试用例 @pytest.mark.asyncio def test_retry_error_handled_without_hard_failure(exception_handler_test_client: TestClient) -> None: # TODO 待处理器正常工作后,断言JSON响应和HTTP状态码 exception_handler_test_client.get("/test_exception_handler/")
测试失败的原因是:RetryError如期抛出,但处理器从未执行。我尝试过相关解决方案,但其中提到的pytest.raises方案仅能让测试通过,无法触发处理器执行。
补充说明
即使将触发重试失败的函数替换为普通的、仅抛出Exception的非重试函数,测试中的异常处理器仍无法执行。
内容的提问来源于stack exchange,提问作者Mena
相关产品推荐
相关产品推荐

