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

如何在FastAPI测试中Mock CustomStreamingResponse?

正确Mock CustomStreamingResponse的方法

核心结论

不需要Mock __call__ 方法,你只需要验证CustomStreamingResponse类是否被实例化/调用,关键是要Mock被测试模块(app.py)中实际引用的类对象。

常见问题原因

之前验证失败大概率是Mock路径错误:如果app.py中是通过from .responses import CustomStreamingResponse导入的类,直接Mocksrc.responses.CustomStreamingResponse不会生效——因为app模块已经持有了原类的引用,Mock原模块的类不会影响app模块内的已有引用。

正确Mock步骤及代码示例

以test_download.py为例:

from fastapi.testclient import TestClient
from src.app import app

client = TestClient(app)

def test_download_uses_custom_response(mocker):
    # 关键:Mock app模块内的CustomStreamingResponse引用
    mock_custom_response = mocker.patch("src.app.CustomStreamingResponse")
    
    # 调用目标接口
    client.get("/your-download-path")  # 替换成实际的接口路径
    
    # 验证CustomStreamingResponse被调用
    mock_custom_response.assert_called_once()  # 断言至少被调用一次
    # 若需要验证调用参数,可添加:
    # mock_custom_response.assert_called_once_with(your_expected_args, your_expected_kwargs)

注意事项

  • 始终Mock被测试代码中直接使用的那个类引用,而不是原定义模块的类。
  • 因为你的需求只是验证响应类是否被使用,Mock后的类不需要实现任何实际逻辑,pytest-mock的Mock对象会自动处理实例化逻辑。
  • 只有当你的代码中显式调用了CustomStreamingResponse的__call__方法时,才需要额外Mock该方法,FastAPI框架处理响应时的调用不需要你手动Mock。

内容的提问来源于stack exchange,提问作者Альберт Александров

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 12:24:57