-
Notifications
You must be signed in to change notification settings - Fork 161
Description
When using a shared event loop (e.g., when loop_scope="session"
) and asyncio.set_event_loop(None)
is called from a test, any subsequent async test raises RuntimeError: There is no current event loop in thread 'MainThread'
.
This will happen in any test that calls asyncio.Runner
or asyncio.run
, which call asyncio.set_event_loop(None)
as part of its clean-up code.
To reproduce:
import asyncio
import pytest
@pytest.mark.asyncio
async def test_before() -> None:
pass
def test_set_event_loop_none() -> None:
asyncio.set_event_loop(None)
@pytest.mark.asyncio
async def test_after() -> None:
pass
$ pytest -o 'asyncio_default_test_loop_scope=module' test_mre.py
The expected behaviour is for all tests to pass, but an exception is raised instead. The exception is not raised if either test_before
or test_after
are skipped.
I found issue #658 which is related; however, that issue is closed and related to fixtures (whereas this is not), so decided to create a new one instead.
I have a patch that resolves the issue by reinstating the event loop if needed. Let me know if a PR would be welcome!
Update: I bisected the issue to the v0.23 release, so this isn't a recent regression.