python runtime_error ai_generated true

RuntimeError: 没有正在运行的事件循环

RuntimeError: no running event loop

ID: python/pytest-asyncio-no-running-event-loop

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2024-06-04首次发现

版本兼容性

版本状态引入弃用备注
0.21.x active — — —
0.23.x active — — —

根因分析

异步测试或 fixture 在没有活动 asyncio 事件循环的情况下执行。通常是 pytest-asyncio 模式未配置、测试缺少 @pytest.mark.asyncio 标记,或 fixture 是同步的却在 await。

English

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

解决方案

  1. 93% 成功率
    # pyproject.toml
    [tool.pytest.ini_options]
    asyncio_mode = "auto"
    
    # or pytest.ini
    # [pytest]
    # asyncio_mode = auto
  2. 90% 成功率
    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

无效尝试

常见但无效的做法:

  1. 70% 失败

    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.

  2. 65% 失败

    Sync fixtures cannot yield awaited values; the coroutine object is returned instead of the resolved value, causing the exact error downstream.