python runtime_error ai_generated true

RuntimeError: 没有正在运行的事件循环 async def 函数未被原生支持。你需要为异步框架安装合适的插件,例如:- anyio - pytest-asyncio

RuntimeError: no running event loop async def functions are not natively supported. You need to install a suitable plugin for your async framework, for example: - anyio - pytest-asyncio

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

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

版本兼容性

版本状态引入弃用备注
7.x active
8.x active

根因分析

pytest 在没有插件的情况下不会运行异步测试函数;未配置 pytest-asyncio(或 anyio)时,协程测试被跳过或抛出此错误。

English

pytest does not run async test functions without a plugin; without pytest-asyncio (or anyio) configured, coroutine tests are skipped or raise this error.

generic

解决方案

  1. 95% 成功率
    pip install pytest-asyncio
    
    # pytest.ini
    [pytest]
    asyncio_mode = auto
    
    # tests
    import pytest
    
    @pytest.mark.asyncio
    async def test_fetch():
        assert await fetch()
  2. 90% 成功率
    pip install anyio
    
    # pytest.ini
    [pytest]
    addopts = --anyio-mode=auto
    
    # tests
    import pytest
    
    @pytest.mark.anyio
    async def test_fetch():
        assert await fetch()

无效尝试

常见但无效的做法:

  1. 60% 失败

    Works for trivial tests but breaks fixtures, event-loop-scoped resources, and any test that relies on pytest's async fixtures.

  2. 90% 失败

    The marker is unknown to pytest and triggers a PytestUnknownMarkWarning; the coroutine is still not awaited.

  3. 95% 失败

    The ini option is only recognized by pytest-asyncio; without the plugin it has no effect.