如何 mock 异步依赖并验证调用次数?
解读
在国内一线互联网公司的 Python 服务端面试里,这道题出现的频率极高,背后考察的是“能否把 pytest 的 fixture 机制与 asyncio 生态无缝结合”。
面试官通常不会只让你“写个 mock”,而是会追问:
- 为什么不用传统的
unittest.mock.patch直接套在协程上? - 如果依赖是
aiohttp的ClientSession.get,你怎么保证事件循环里真正 awaited 的是 mock 对象? - 并发场景下(
pytest-asyncio-cooperative或anyio的triobackend),如何确保call_count线程安全? - 在 CI 里跑 3.8‒3.12 多版本时,如何写一段兼容代码,既支持
AsyncMock(3.8+)又回退到asynctest(3.7)?
把这些问题答全,才能拿到“资深”评级。
知识点
pytest-asyncio插件:负责为每个异步测试注入独立的事件循环,并保证loop.close()时机正确。unittest.mock.AsyncMock:Python 3.8 之后官方协程安全 mock,自带await_count、call_args_list。monkeypatchfixture:比patch上下文管理器更轻量,可在 fixture 层做依赖注入,避免“嵌套地狱”。pytest-mock的mocker:对AsyncMock做了一层薄封装,支持mocker.async_stub(),并自动注册到request.addfinalizer,防止循环未关闭导致的ResourceWarning。assert await mock()与mock.await_count区别:前者断言协程被 awaited,后者断言协程被调度次数;在asyncio.gather里可能不一致,需要双断言。- 并发安全:若使用
anyio的triobackend,AsyncMock内部计数器是线程级隔离的,无需额外锁;但如果是pytest-xdist并行进程,需把call_count回写到主进程,得配合pytest-cache或filelock做聚合,面试时提到即可加分。
答案
以下示例覆盖“被测代码—fixture—断言”完整闭环,可直接粘到 IDE 跑通,兼容 Python 3.8-3.12,无需额外依赖 asynctest。
# src/business.py
import aiohttp
async def fetch_user(uid: int) -> dict:
"""真实依赖:外部用户服务"""
async with aiohttp.ClientSession() as sess:
async with sess.get(f"https://api.example.com/user/{uid}") as resp:
resp.raise_for_status()
return await resp.json()
# src/core.py
from .business import fetch_user
async def greet_user(uid: int) -> str:
"""被测函数:内部核心逻辑"""
user = await fetch_user(uid)
return f"Hello, {user['name']}"
# tests/conftest.py
import pytest
from unittest.mock import AsyncMock
@pytest.fixture
def mock_fetch_user(mocker):
"""
在整个测试会话层复用同一个 AsyncMock,避免重复创建。
返回 mock 对象,方便测试层做细粒度断言。
"""
mock = mocker.patch(
"src.core.fetch_user", # 注意路径是“被测代码”导入的命名空间
new_callable=AsyncMock,
)
mock.return_value = {"name": "张三"}
yield mock
# pytest-mock 会自动 stopall,这里无需手动
# tests/test_core.py
import pytest
from src.core import greet_user
@pytest.mark.asyncio
async def test_greet_user(mock_fetch_user):
# 执行被测协程
result = await greet_user(123)
# 验证返回值
assert result == "Hello, 张三"
# 验证依赖被 awaited 且仅一次
mock_fetch_user.assert_awaited_once_with(123)
# 验证调用次数
assert mock_fetch_user.await_count == 1
运行命令(国内源加速):
pip install -U pytest pytest-asyncio pytest-mock aiohttp -i https://pypi.tuna.tsinghua.edu.cn/simple
pytest -q tests/test_core.py
输出:
. [100%]
1 passed in 0.12s
若面试官追问“如何验证异常路径”,可补充:
@pytest.mark.asyncio
async def test_greet_user_timeout(mock_fetch_user):
from aiohttp import ClientTimeoutError
mock_fetch_user.side_effect = ClientTimeoutError
with pytest.raises(ClientTimeoutError):
await greet_user(123)
assert mock_fetch_user.await_count == 1
拓展思考
- 真实链路不做 mock:使用
respx或aioresponses做“HTTP 层拦截”,在集成测试里验证契约;此时仍需AsyncMock对“下游微服务 SDK”做桩,形成“金字塔”策略。 - 性能压测场景:当
await_count达到 10 k 级别时,AsyncMock内部列表会膨胀,导致内存占用飙升;可自定义轻量MagicMock,只保留count原子变量,并通过pytest-benchmark对比耗时。 - 多后端兼容:若公司老旧项目停留在 Python 3.7,可封装一个
compat_async_mockfixture,优先使用unittest.mock.AsyncMock,回退时from asynctest import CoroutineMock,保证 CI 矩阵一次通过。 - 与 FastAPI 依赖注入混用:FastAPI 的
Depends默认缓存同一请求内的依赖,若 mock 对象被缓存,会导致await_count始终为 1;需在测试里显式app.dependency_overrides[original_func] = mock_func,并在 teardown 阶段app.dependency_overrides.clear()。 - 行为驱动:结合
pytest-bdd的given/when/then,把await_count写入scenario的then步骤,让产品经理也能读懂“下游服务被调了几次”,实现真正的“测试即文档”。