Python "asyncio.run() cannot be called from a running event loop" in CI
asyncio.run() creates and owns a fresh event loop; it cannot be called when one is already running. Calling it inside an async test or an already-async context raises this RuntimeError.
What this error means
A test fails with "RuntimeError: asyncio.run() cannot be called from a running event loop," typically when an async test body calls asyncio.run(...) on a coroutine.
pytest
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'fetch' was never awaitedCommon causes
asyncio.run() nested inside a running loop
An async test (or async framework handler) is already inside a loop, so a fresh asyncio.run() cannot start another.
Wrapping awaitables instead of awaiting them
Calling asyncio.run(coro()) where a plain await coro() was intended re-enters the loop.
How to fix it
Await directly in async tests
- Mark the test async and use
pytest-asyncio. - Replace
asyncio.run(coro())withawait coro(). - Re-run.
Python
import pytest
@pytest.mark.asyncio
async def test_fetch():
result = await fetch() # not asyncio.run(fetch())
assert result.okRun blocking async code off the loop when needed
If you truly must drive a coroutine from sync code already inside a loop, offload it to another thread.
Python
import asyncio
result = asyncio.run_coroutine_threadsafe(coro(), loop).result()How to prevent it
- Use
awaitinside async contexts; reserveasyncio.run()for the top-level entry point. - Adopt
pytest-asynciofor async tests rather than manual loop management. - Avoid wrapping coroutines in
asyncio.run()deep in a call stack.
Related guides
Python "DeprecationWarning: There is no current event loop" in CIFix "DeprecationWarning: There is no current event loop" in CI - get_event_loop() with no running loop is dep…
Python "TypeError: object X can't be used in await expression" in CIFix "TypeError: object X can't be used in 'await' expression" in CI - you awaited a non-awaitable, such as a…
pytest-asyncio "RuntimeError: Event loop is closed" in CIFix pytest-asyncio "RuntimeError: Event loop is closed" in CI - an async test or teardown used a loop that wa…