RuntimeError: 没有正在运行的事件循环 async def 函数未被原生支持。你需要为异步框架安装合适的插件,例如:- anyio - pytest-asyncio
RuntimeError: no running event loop async def functions are not natively supported. You need to install a suitable plugin for your async framework, for example: - anyio - pytest-asyncio
ID: python/pytest-asyncio-no-event-loop
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
pytest 在没有插件的情况下不会运行异步测试函数;未配置 pytest-asyncio(或 anyio)时,协程测试被跳过或抛出此错误。
English
pytest does not run async test functions without a plugin; without pytest-asyncio (or anyio) configured, coroutine tests are skipped or raise this error.
解决方案
-
95% 成功率
pip install pytest-asyncio # pytest.ini [pytest] asyncio_mode = auto # tests import pytest @pytest.mark.asyncio async def test_fetch(): assert await fetch() -
90% 成功率
pip install anyio # pytest.ini [pytest] addopts = --anyio-mode=auto # tests import pytest @pytest.mark.anyio async def test_fetch(): assert await fetch()
无效尝试
常见但无效的做法:
-
60% 失败
Works for trivial tests but breaks fixtures, event-loop-scoped resources, and any test that relies on pytest's async fixtures.
-
90% 失败
The marker is unknown to pytest and triggers a PytestUnknownMarkWarning; the coroutine is still not awaited.
-
95% 失败
The ini option is only recognized by pytest-asyncio; without the plugin it has no effect.