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

如何在使用httpx AsyncClient测试FastAPI时禁用服务器异常抛出

解决方案

httpx 异步客户端的异常抛出控制参数不属于AsyncClient的顶层入参,需要通过ASGI传输层显式配置,修改后的fixture代码如下:

import pytest
from httpx import AsyncClient, ASGITransport

@pytest.fixture
async def client(test_app):
    # 显式构造ASGI传输层,关闭异常冒泡
    transport = ASGITransport(
        app=test_app,
        raise_app_exceptions=False
    )
    async with AsyncClient(
        transport=transport,
        base_url="http://testserver"
    ) as client:
        yield client
  • raise_app_exceptions参数设为False后,FastAPI应用运行时抛出的异常不会直接传递到测试代码中,而是会转化为标准的500响应返回,和同步TestClient的raise_server_exceptions=False效果完全一致,也可以解决本地和CI环境测试表现不一致的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:39:05