Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/1233.fixed.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Allow event loop policies that reject setting a loop on the current thread to run async tests.
18 changes: 15 additions & 3 deletions pytest_asyncio/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -1015,12 +1015,24 @@ def _scoped_runner(
) -> Iterator[Runner]:
debug_mode = _get_asyncio_debug(request.config)
with _restore_event_loop_policy():
# Always hand the runner an explicit factory. Without one, the runner
# calls asyncio.set_event_loop() itself, which fails for event loop
# policies that manage the loop of the main thread on their own.
loop_factory = _asyncio_loop_factory or asyncio.new_event_loop
runner = Runner(
debug=debug_mode,
loop_factory=_asyncio_loop_factory,
loop_factory=loop_factory,
).__enter__()
if _asyncio_loop_factory is not None:
loop_is_set = False
try:
_set_event_loop(runner.get_loop())
loop_is_set = True
except RuntimeError:
# Some event loop policies manage their loop outside of
# asyncio.set_event_loop(). The runner can still execute the
# loop because it is available through asyncio.get_running_loop()
# while a coroutine is running.
pass
try:
yield runner
except Exception as e:
Expand All @@ -1038,7 +1050,7 @@ def _scoped_runner(
RuntimeWarning,
)
finally:
if _asyncio_loop_factory is not None:
if loop_is_set:
_set_event_loop(None)

return _scoped_runner
Expand Down
39 changes: 39 additions & 0 deletions tests/test_set_event_loop.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,50 @@
from __future__ import annotations

import sys
from textwrap import dedent

import pytest
from pytest import Pytester


@pytest.mark.skipif(
sys.version_info >= (3, 16),
reason="The asyncio event loop policy system was removed in Python 3.16",
)
def test_runner_works_with_policy_that_rejects_setting_loop(pytester: Pytester):
pytester.makeconftest(dedent("""\
import asyncio
import warnings

with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)

class MainContextPolicy(asyncio.DefaultEventLoopPolicy):
def set_event_loop(self, loop):
if loop is not None:
raise RuntimeError("Thread already has a main context")
super().set_event_loop(loop)

asyncio.set_event_loop_policy(MainContextPolicy())
"""))
pytester.makepyfile(dedent("""\
import asyncio
import pytest

@pytest.mark.asyncio
async def test_first():
assert asyncio.get_running_loop().is_running()

@pytest.mark.asyncio
async def test_second():
assert asyncio.get_running_loop().is_running()
"""))

result = pytester.runpytest_subprocess()

result.assert_outcomes(passed=2)


@pytest.mark.parametrize(
"test_loop_scope",
("function", "module", "package", "session"),
Expand Down
Loading