pytest-asyncio 0.21.0+ 是 python 3.10+ 异步测试必备版本,需显式加 @pytest.mark.asyncio 装饰器、配置 asyncio_mode="auto",并避免事件循环生命周期错配导致的未 await 或 loop 关闭错误。

pytest-asyncio 是目前最主流的异步测试方案,但 Python 3.10+ 的协程行为变化和插件版本兼容性容易导致 RuntimeWarning: coroutine 'test_xxx' was never awaited 或 Event loop is closed 这类错误——根本原因不是代码写错了,而是事件循环生命周期没对齐。
确认 pytest-asyncio 版本与 Python 3.10+ 兼容
旧版 pytest-asyncio 在 Python 3.10+ 上默认使用已弃用的 <code>asyncio.get_event_loop(),会触发 DeprecationWarning 甚至崩溃。必须升级:
-
pip install -U pytest-asyncio>=0.21.0(推荐 0.23.0+) - 检查是否启用了
asyncio_mode = auto(新版默认),而非过时的auto模式需显式配置 - 如果项目用
pyproject.toml,确保有:[tool.pytest.ini_options] asyncio_mode = "auto"
给 async 测试函数加 @pytest.mark.asyncio 装饰器
不加这个标记,pytest 会把 async def test_xxx() 当普通函数执行,协程对象不会被 await,直接报 was never awaited。它不是可选的,是强制的。
Python 3.14.2是Python编程语言在2025年12月5日发布的稳定版本,属于3.14系列的第二个维护更新。该版本包含了18项修复,重点解决了多进程、数据类及正则表达式等模块的回归问题,并修复了CVE-2025-12084等安全漏洞。此版本标志着自由线程模式(移除GIL)正式获得官方支持,是Python发展的重要里程碑。
- 正确写法:
import pytest <p>@pytest.mark.asyncio async def test_fetch_data(): result = await some_async_func() assert result == "ok"</p>
- 不能只靠函数名含
async或文件名带_async—— pytest 不自动识别 - 若想全局启用(不加装饰器),可在
pytest.ini中设asyncio_mode = auto,但仅对函数名匹配^test且含async def生效;实际项目中仍建议显式加@pytest.mark.asyncio,避免隐式行为出错
避免在 fixture 中混用 sync/async 初始化逻辑
常见陷阱:用 @pytest.fixture 定义一个返回协程对象的 fixture,但没用 @pytest.fixture 的 scope="function" + autouse=True 组合,或忘了 await 它。
- 同步 fixture 不能直接调
await:@pytest.fixture def bad_fixture(): return asyncio.sleep(0.1) # 返回协程对象,但没 await → 后续用的地方会报错 - 正确方式是用
@pytest.fixture+async def+@pytest.mark.asyncio(注意:fixture 本身不支持@pytest.mark.asyncio,得换思路):@pytest.fixture async def good_fixture(): return await some_async_setup() <p>@pytest.mark.asyncio async def test_with_fixture(good_fixture): assert await good_fixture == "ready"</p> - 更稳妥做法:用
asyncio.run()包一层(仅限简单场景,因会新建 event loop):@pytest.fixture def db_client(): return asyncio.run(setup_db()) # ⚠️ 不推荐用于嵌套 await 场景
处理全局 event loop 关闭导致的 RuntimeError
Python 3.10+ 默认在主线程 exit 时关闭 event loop,而 pytest 的多个 test session 可能复用 loop,引发 RuntimeError: Event loop is closed。
- 在
conftest.py中重置 loop(推荐):import asyncio import pytest <p>@pytest.fixture(autouse=True) def reset_event_loop(): asyncio.set_event_loop(asyncio.new_event_loop())</p>
- 或者禁用 pytest 的 loop 复用(较重):
pytest --asyncio-mode=strict,此时每个 test 都新建 loop - 如果测试中手动调了
asyncio.get_event_loop().close(),务必确认这是必要操作——多数情况下不该主动 close
最易被忽略的是:即使所有测试都标了 @pytest.mark.asyncio,只要有一个测试函数里漏了 await 某个协程调用,整个 session 的 event loop 就可能提前终止,后续测试全挂。建议用 pytest-asyncio 的 --asyncio-mode=auto 配合严格 lint(如 pylint 的 unnecessary-await 和 missing-await 规则)来兜底。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










