python
runtime_error
ai_generated
true
RuntimeError: 事件循环已关闭
RuntimeError: Event loop is closed
ID: python/pytest-asyncio-event-loop-closed
80%修复率
85%置信度
0证据数
2024-05-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 0.21 | active | — | — | — |
| 0.23 | active | — | — | — |
根因分析
pytest-asyncio 默认每个测试创建一个新的事件循环。如果异步资源(如 aiohttp 会话、异步数据库连接)在一个测试中创建并在另一个测试中使用,或者在清理前循环已关闭,就会发生此错误。
English
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.
解决方案
-
95% 成功率
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% 成功率
@pytest_asyncio.fixture(scope='module') async def client(): session = aiohttp.ClientSession() yield session await session.close()
无效尝试
常见但无效的做法:
-
90% 失败
Sleeping does not prevent the loop from being closed between tests.
-
85% 失败
This only affects Windows and does not address the per-test loop creation.