如何用 pytest-httpx 拦截真实 HTTP 请求并返回预设 JSON?

解读

国内一线互联网公司在单元/集成测试面试里,常把“第三方 HTTP 服务怎么 Mock”作为分水岭题目。
pytest-httpx 是官方推荐的同步/异步一体 Mock 方案,考察点集中在三条线:

  1. 是否知道 httpx_mock 这一内置 fixture,而不是自己手撸 patch;
  2. 能否把响应序列化、状态码、headers 一次性声明清楚;
  3. 是否理解“拦截顺序”与“匹配优先级”,避免测试用例间互相污染。
    面试官希望你用 30 秒给出最小可运行示例,再用 1 分钟讲清参数化与异常路径,最后能聊到性能(如 pytest-httpx<0.24 的 assert_no_request 对 CI 的加速意义)。答不到“响应匹配优先级”基本会被追问到卡壳。

知识点

  • pytest-httpx 0.20+ 的 httpx_mock fixture 注入机制
  • httpx_mock.add_response() 参数:method、url、json、status_code、headers、match_headers、match_content
  • 同步/异步代码通用性:pytest-httpx 自动识别 async def 用例
  • 匹配优先级:exact > regex > callback;同一 url 多次 add_response 按 FIFO 消费
  • 测试隔离:httpx_mock.reset() 或函数级 fixture 自动清理
  • 负向断言:httpx_mock.assert_no_request() 与 get_requests() 做白盒校验
  • 参数化:结合 pytest.mark.parametrize 与 add_response 动态生成场景
  • 与 pytest-xdist 并行兼容:无需额外配置,但需保证响应队列线程安全

答案

最小可运行示例(同步场景):

# test_client.py
import httpx
import pytest

def test_fetch_user(httpx_mock):
    # 1. 预设 JSON 响应
    httpx_mock.add_response(
        method="GET",
        url="https://api.example.com/users/42",
        json={"id": 42, "name": "张三"},
        status_code=200,
        headers={"content-type": "application/json; charset=utf-8"}
    )

    # 2. 业务代码(被测函数)
    def get_user(uid: int) -> dict:
        resp = httpx.get(f"https://api.example.com/users/{uid}")
        resp.raise_for_status()
        return resp.json()

    # 3. 断言
    assert get_user(42) == {"id": 42, "name": "张三"}
    # 4. 白盒校验:确实只发了一次请求
    assert len(httpx_mock.get_requests()) == 1

异步场景写法完全一致,只需把测试函数声明为 async def 并用 httpx.AsyncClient 即可,pytest-httpx 会自动识别。

参数化批量场景:

@pytest.mark.parametrize("uid,expect", [(1, "Alice"), (2, "Bob")])
def test_multi_user(httpx_mock, uid, expect):
    httpx_mock.add_response(url=f"https://api.example.com/users/{uid}",
                              json={"name": expect})
    resp = httpx.get(f"https://api.example.com/users/{uid}")
    assert resp.json()["name"] == expect

异常路径:

def test_timeout(httpx_mock):
    httpx_mock.add_response(url="https://api.example.com/timeout",
                              status_code=504, json={"msg": "Gateway Timeout"})
    resp = httpx.get("https://api.example.com/timeout")
    assert resp.status_code == 504

拓展思考

  1. 如果后端接口分页,需要连续返回 3 页不同数据,可用 add_response 三次,pytest-httpx 会按顺序弹出;记得在 teardown 里 httpx_mock.reset() 防止交叉污染。
  2. 对 GraphQL 场景,单靠 url 匹配不够,需用 match_content=lambda body: "query getUser" in body.decode() 做细粒度断言。
  3. 在 CI 并行环境下,若用例依赖同一 url 的不同响应,推荐把“响应队列”拆成函数级 fixture,避免 xdist 进程间竞争。
  4. 如果项目同时存在 requests 与 httpx,可混用 responses 与 pytest-httpx,但务必保证 patch 顺序,否则会出现“真实请求逃逸”。
  5. 对于性能敏感的大型套件,可开启 pytest-httpx 的零拷贝模式(add_response(json=..., passthrough=False)),减少序列化开销,提高流水线 10% 以上执行效率。