如何使用 pytest-httpx 为外部依赖注入 Mock 响应?
解读
在国内一线互联网公司的 FastAPI 面试中,这道题考察的是“可测性设计”与“外部依赖治理”能力。
面试官真正想听的是:
- 你是否能把“第三方 HTTP 调用”抽象成可替换的依赖;
- 你是否熟悉 pytest-httpx 的拦截机制,并能在异步、并发场景下正确断言;
- 你是否能在 CI/CD(GitLab-CI、Jenkins、GitHub Actions)里低成本复现这套测试策略。
回答时切忌只贴代码,要体现“工程落地”:目录怎么分、fixture 怎么复用、会不会污染全局事件循环、生产代码零侵入怎么做。
知识点
- pytest-httpx 的两种拦截模式
- 全局模式:pytest-httpx 自动注入
httpx_mockfixture,所有httpx.AsyncClient/Client请求被劫持。 - 局部模式:手动
httpx.MockTransport()注入到指定 client,避免全局污染。
- 全局模式:pytest-httpx 自动注入
- FastAPI 的
dependency_overrides机制
通过覆盖依赖函数,把真实 client 换成带 mock transport 的 client,实现“零侵入”替换。 - 异步测试事件循环
pytest-asyncio 的asyncio_mode=auto与 pytest-httpx 的协程安全要求;禁止在*args里混用同步Client。 - Pydantic 共享模型
外部服务响应与内部 DTO 共用基类,保证 mock 数据与真实数据序列化路径一致,防止“绿色测试、线上 422”。 - 并发场景下的断言
httpx_mock.get_requests()返回 List,需按(method, url)去重,避免并发导致顺序抖动。 - 国内网络镜像与 CI 缓存
把pytest-httpx锁在requirements-test.txt,CI 镜像源统一用清华或腾讯,防止“墙外依赖”拉爆流水线。
答案
工程目录
app/
├─ deps.py # 外部 client 工厂
├─ services.py # 业务逻辑
└─ main.py # FastAPI 实例
tests/
├─ conftest.py # 复用 fixture
└─ test_services.py # 业务测试
- 生产代码零侵入
# app/deps.py
import httpx
from typing import AsyncGenerator
async def get_http_client() -> AsyncGenerator[httpx.AsyncClient, None]:
async with httpx.AsyncClient(base_url="https://third-party.api.com") as client:
yield client
- 业务层依赖注入
# app/services.py
from fastapi import Depends
from app.deps import get_http_client
import httpx
async def fetch_user_score(uid: str,
client: httpx.AsyncClient = Depends(get_http_client)) -> int:
resp = await client.get(f"/score/{uid}")
resp.raise_for_status()
return resp.json()["score"]
- 测试侧 fixture:全局拦截 + 依赖覆盖
# tests/conftest.py
import pytest
from fastapi import FastAPI
from app.main import app
from app.deps import get_http_client
import httpx
@pytest.fixture
def mock_transport(httpx_mock):
# 统一注册常用路由,减少重复代码
httpx_mock.add_response(
method="GET",
url="https://third-party.api.com/score/u123",
json={"score": 98}
)
return httpx_mock
@pytest.fixture
async def override_client(mock_transport):
# 用 mock_transport 创建局部 client
async with httpx.AsyncClient(transport=mock_transport) as client:
yield client
@pytest.fixture(autouse=True)
def setup_override(override_client):
app.dependency_overrides[get_http_client] = lambda: override_client
yield
app.dependency_overrides.clear()
- 测试用例:并发 + 断言
# tests/test_services.py
import pytest
from app.services import fetch_user_score
@pytest.mark.asyncio
async def test_fetch_user_score(httpx_mock):
# 业务入口
score = await fetch_user_score("u123")
assert score == 98
# 并发场景:确认只调用一次,防止重复请求
requests = [r for r in httpx_mock.get_requests() if r.method == "GET"]
assert len(requests) == 1
- CI 模板(GitLab-CI 片段)
test:
stage: test
image: python:3.11-slim
before_script:
- pip install -r requirements-test.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
script:
- pytest -q --tb=short
coverage: '/TOTAL.*\s+(\d+%)$/'
通过以上五步,实现“本地一键通过、CI 零网络请求、生产代码无侵入”。
拓展思考
- 多环境差异化 mock
在pytest.ini里加env = qa,利用httpx_mock.add_response(..., json=load_json(f"mock/qa/{uid}.json")),同一代码库支持“QA 环境返回 500ms 延迟、Prod 环境返回 99 分”的差异化验收。 - 与 FactoryBoy 结合
把外部响应封装成ScoreFactory,使用pytest-factoryboy的register(ScoreFactory),在测试中直接score = ScoreFactory(),再httpx_mock.add_response(json=score.dict()),实现“mock 数据即工厂”,避免手写 JSON。 - 链路压测
当接口内部级联 3 个外部服务时,用pytest-httpx的side_effect=lambda req: httpx.Response(200, json=...)动态计算响应,配合pytest-benchmark统计 FastAPI 的async吞吐,提前发现gather(*coros)的并发瓶颈。 - 灰度回归
在预发布环境开启“影子模式”:把真实请求与 mock 请求双发,通过httpx_mock.add_response(..., passthrough=True)对比返回值差异,实现“零回归”上线。