python runtime_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-01-19First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active
8.x active

Root Cause

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

中文

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

Workarounds

  1. 95% success
    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% success
    pip install anyio
    
    # pytest.ini
    [pytest]
    addopts = --anyio-mode=auto
    
    # tests
    import pytest
    
    @pytest.mark.anyio
    async def test_fetch():
        assert await fetch()

Dead Ends

Common approaches that don't work:

  1. 60% fail

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

  2. 90% fail

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

  3. 95% fail

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