python runtime_error ai_generated true

RuntimeError: 事件循环已关闭

RuntimeError: Event loop is closed

ID: python/pytest-asyncio-event-loop-closed

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 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').
  2. 90% 成功率
    @pytest_asyncio.fixture(scope='module')
    async def client():
        session = aiohttp.ClientSession()
        yield session
        await session.close()

无效尝试

常见但无效的做法:

  1. 90% 失败

    Sleeping does not prevent the loop from being closed between tests.

  2. 85% 失败

    This only affects Windows and does not address the per-test loop creation.