python runtime_error ai_generated true

RuntimeError: Event loop is closed

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-05-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.23.x active
0.24.x active
0.25.x active

Root Cause

With pytest-asyncio, the default function-scoped event loop is torn down after the first async test, but a session-scoped async fixture or a lingering task still references the closed loop.

generic

中文

使用 pytest-asyncio 时,默认的函数级事件循环在第一个异步测试后被销毁,但会话级的异步 fixture 或残留任务仍引用已关闭的循环。

Workarounds

  1. 90% success
    # pytest.ini
    [pytest]
    asyncio_mode = auto
    asyncio_default_fixture_loop_scope = session
  2. 85% success
    # conftest.py
    import asyncio, pytest
    
    @pytest.fixture(scope='session')
    def event_loop():
        loop = asyncio.new_event_loop()
        yield loop
        loop.close()

Dead Ends

Common approaches that don't work:

  1. 80% fail

    pytest-asyncio already manages the loop; creating a new one mid-test orphans the fixture's loop and the error persists on teardown.

  2. 70% fail

    The marker is likely already present; the problem is loop scope mismatch, not the missing marker.