SuperAPI AI 工具集

pytest-async-testing

测试与质量

查看项目

更新于 10-16 05:05

技能介绍

用途:为现代 Python 异步代码提供生产可用的 pytest 测试模式,解决事件循环、上下文管理器与异步 fixture 的特殊处理问题。

主要能力:配置 pytest-asyncio 自动识别异步测试;编写带类型标注的异步 fixture;用 AsyncMock 模拟异步方法与异步生成器;测试异步用例并校验 await 次数;用 httpx 的 AsyncClient 与 ASGITransport 测试 FastAPI 端点;测试异步上下文管理器的事务提交与回滚;消费异步生成器并支持提前终止;模拟 Kafka 生产者与消费者;清理挂起任务;用超时控制长时间异步操作。

必要用法:在 pyproject.toml 中设置 asyncio_mode = "auto" 与 asyncio_default_fixture_loop_scope = "function";异步 fixture 使用 @pytest.fixture 配合 AsyncGenerator 类型与 yield;异步测试可加 @pytest.mark.asyncio,auto 模式下可省略;FastAPI 测试用 ASGITransport(app=app) 构造 AsyncClient;超时可用 @pytest.mark.timeout(5) 或 asyncio.wait_for。

适用场景:异步服务、FastAPI 接口、数据库会话、消息队列客户端与流式数据处理的单元测试。

限制:资料要求 Python 3.11+、pytest >= 7.0、pytest-asyncio >= 0.20.0、httpx 与标准库 asyncio;未提供安装命令、收费、价格与效果数据。