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

如何解决PyTest中FastAPI的'app'快捷方式弃用警告?

解决PyTest中TestClient的DeprecationWarning与TypeError问题

问题分析

出现DeprecationWarning是因为新版httpx不再支持直接向TestClient传入app参数,要求显式指定transport;后续的TypeError则是因为使用的TestClient版本(或导入来源)不兼容transport参数,核心是依赖版本或导入路径不匹配。

解决方案

情况1:使用FastAPI官方的TestClient

如果代码是从fastapi.testclient导入TestClient,无需手动配置transport:

  • 保留原有代码即可,警告通常是httpx版本过高引发的兼容问题。
  • 可降级httpx到<0.25版本,或升级FastAPI到最新稳定版,适配新版httpx的API。

原有代码:

@pytest.fixture
def client(app: FastAPI) -> Generator:
    with TestClient(app, base_url="http://localhost") as client:
        yield client

情况2:使用httpx原生的TestClient

如果直接从httpx导入TestClient,需匹配版本并正确配置transport:

  1. 确保httpx版本≥0.25.0,版本过低先执行升级:
    pip install --upgrade httpx
    
  2. 修改fixture代码,显式创建ASGITransport并传入:
    from httpx import TestClient, ASGITransport
    from fastapi import FastAPI
    import pytest
    from typing import Generator
    
    @pytest.fixture
    def client(app: FastAPI) -> Generator:
        transport = ASGITransport(app=app)
        with TestClient(transport=transport, base_url="http://localhost") as client:
            yield client
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 12:00:59