如何 mock 异步依赖并验证调用次数?

解读

在国内一线互联网公司的 Python 服务端面试里,这道题出现的频率极高,背后考察的是“能否把 pytest 的 fixture 机制与 asyncio 生态无缝结合”。
面试官通常不会只让你“写个 mock”,而是会追问:

  1. 为什么不用传统的 unittest.mock.patch 直接套在协程上?
  2. 如果依赖是 aiohttp 的 ClientSession.get,你怎么保证事件循环里真正 awaited 的是 mock 对象?
  3. 并发场景下(pytest-asyncio-cooperative 或 anyio 的 trio backend),如何确保 call_count 线程安全?
  4. 在 CI 里跑 3.8‒3.12 多版本时,如何写一段兼容代码,既支持 AsyncMock(3.8+)又回退到 asynctest(3.7)?
    把这些问题答全,才能拿到“资深”评级。

知识点

  1. pytest-asyncio 插件:负责为每个异步测试注入独立的事件循环,并保证 loop.close() 时机正确。
  2. unittest.mock.AsyncMock:Python 3.8 之后官方协程安全 mock,自带 await_count、call_args_list。
  3. monkeypatch fixture:比 patch 上下文管理器更轻量,可在 fixture 层做依赖注入,避免“嵌套地狱”。
  4. pytest-mock 的 mocker:对 AsyncMock 做了一层薄封装,支持 mocker.async_stub(),并自动注册到 request.addfinalizer,防止循环未关闭导致的 ResourceWarning。
  5. assert await mock() 与 mock.await_count 区别:前者断言协程被 awaited,后者断言协程被调度次数;在 asyncio.gather 里可能不一致,需要双断言。
  6. 并发安全:若使用 anyio 的 trio backend,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

拓展思考

  1. 真实链路不做 mock:使用 respx 或 aioresponses 做“HTTP 层拦截”,在集成测试里验证契约;此时仍需 AsyncMock 对“下游微服务 SDK”做桩,形成“金字塔”策略。
  2. 性能压测场景:当 await_count 达到 10 k 级别时,AsyncMock 内部列表会膨胀,导致内存占用飙升;可自定义轻量 MagicMock,只保留 count 原子变量,并通过 pytest-benchmark 对比耗时。
  3. 多后端兼容:若公司老旧项目停留在 Python 3.7,可封装一个 compat_async_mock fixture,优先使用 unittest.mock.AsyncMock,回退时 from asynctest import CoroutineMock,保证 CI 矩阵一次通过。
  4. 与 FastAPI 依赖注入混用:FastAPI 的 Depends 默认缓存同一请求内的依赖,若 mock 对象被缓存,会导致 await_count 始终为 1;需在测试里显式 app.dependency_overrides[original_func] = mock_func,并在 teardown 阶段 app.dependency_overrides.clear()。
  5. 行为驱动:结合 pytest-bdd 的 given/when/then,把 await_count 写入 scenario 的 then 步骤,让产品经理也能读懂“下游服务被调了几次”,实现真正的“测试即文档”。