python
runtime_error
ai_generated
true
RuntimeError: Event loop is closed
ID: python/pytest-asyncio-event-loop-closed
80%Fix Rate
85%Confidence
0Evidence
2024-05-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 0.21 | active | — | — | — |
| 0.23 | active | — | — | — |
Root Cause
pytest-asyncio creates a new event loop per test by default. If an async resource (e.g., aiohttp session, async DB connection) is created in one test and used in another, or if the loop is closed before cleanup, this error occurs.
generic中文
pytest-asyncio 默认每个测试创建一个新的事件循环。如果异步资源(如 aiohttp 会话、异步数据库连接)在一个测试中创建并在另一个测试中使用,或者在清理前循环已关闭,就会发生此错误。
Workarounds
-
95% success
In conftest.py: import pytest import asyncio @pytest.fixture(scope='session') def event_loop(): loop = asyncio.new_event_loop() yield loop loop.close() Or use pytest-asyncio's built-in: set asyncio_mode = auto and use @pytest.mark.asyncio(scope='session'). -
90% success
@pytest_asyncio.fixture(scope='module') async def client(): session = aiohttp.ClientSession() yield session await session.close()
Dead Ends
Common approaches that don't work:
-
90% fail
Sleeping does not prevent the loop from being closed between tests.
-
85% fail
This only affects Windows and does not address the per-test loop creation.