python
runtime_error
ai_generated
true
RuntimeError: no running event loop
ID: python/pytest-asyncio-no-running-event-loop
80%Fix Rate
87%Confidence
0Evidence
2024-06-04First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 0.21.x | active | — | — | — |
| 0.23.x | active | — | — | — |
Root Cause
An async test or fixture is executed without an active asyncio event loop. Typically pytest-asyncio mode is not configured, the test lacks @pytest.mark.asyncio, or the fixture is sync but awaits.
generic中文
异步测试或 fixture 在没有活动 asyncio 事件循环的情况下执行。通常是 pytest-asyncio 模式未配置、测试缺少 @pytest.mark.asyncio 标记,或 fixture 是同步的却在 await。
Workarounds
-
93% success
# pyproject.toml [tool.pytest.ini_options] asyncio_mode = "auto" # or pytest.ini # [pytest] # asyncio_mode = auto
-
90% success
import pytest, pytest_asyncio @pytest_asyncio.fixture async def client(): async with AsyncClient() as c: yield c @pytest.mark.asyncio async def test_ping(client): r = await client.get('/ping') assert r.status_code == 200
Dead Ends
Common approaches that don't work:
-
70% fail
pytest-asyncio already manages the loop; nested asyncio.run raises 'asyncio.run() cannot be called from a running event loop' or double-closes the loop.
-
65% fail
Sync fixtures cannot yield awaited values; the coroutine object is returned instead of the resolved value, causing the exact error downstream.