用途:为 Python 异步代码提供正确的测试搭建模式,覆盖 async def 函数、异步 fixture、异步服务 mock、async with 上下文管理器与 async for 生成器等场景。
主要能力:配置 pytest-asyncio(pyproject.toml 中 asyncio_mode = "auto");用 @pytest_asyncio.fixture 配合 AsyncGenerator 创建带 setup/teardown 的异步 fixture;用 unittest.mock.AsyncMock 模拟异步方法,支持 return_value、side_effect(异常、序列、自定义协程函数);模拟异步上下文管理器(aenter/aexit);使用 assert_awaited_once()、assert_awaited_once_with()、await_count、assert_not_awaited() 等异步断言;测试异步异常与重试逻辑。
使用方式:安装依赖 uv pip install pytest-asyncio;在 pyproject.toml 配置 asyncio_mode = "auto";异步测试加 @pytest.mark.asyncio;异步资源用 @pytest_asyncio.fixture,mock 可用普通 @pytest.fixture;异步方法必须用 AsyncMock,同步对象(如驱动本身)用 MagicMock。
适用场景:异步函数单元测试、异步数据库/API 客户端测试、FastAPI 异步端点测试、异步资源池与并发操作测试。
限制:资料未提供具体版本兼容范围之外的保证,也未说明收费、平台或效果数据;需具备 Python async/await、pytest fixture 与 mock 基础知识。