diff --git a/pytest_asyncio/plugin.py b/pytest_asyncio/plugin.py index 2fdc5f4e..7f26b909 100644 --- a/pytest_asyncio/plugin.py +++ b/pytest_asyncio/plugin.py @@ -72,12 +72,6 @@ def get_and_strip_from(self, name, data_dict): del data_dict[name] return result -@pytest.hookimpl(trylast=True) -def pytest_fixture_post_finalizer(fixturedef, request): - """Called after fixture teardown""" - if fixturedef.argname == "event_loop": - # Set empty loop policy, so that subsequent get_event_loop() provides a new loop - asyncio.set_event_loop_policy(None) @@ -88,7 +82,14 @@ def pytest_fixture_setup(fixturedef, request): outcome = yield loop = outcome.get_result() policy = asyncio.get_event_loop_policy() + try: + old_loop = policy.get_event_loop() + except RuntimeError as exc: + if 'no current event loop' not in str(exc): + raise + old_loop = None policy.set_event_loop(loop) + fixturedef.addfinalizer(lambda: policy.set_event_loop(old_loop)) return if isasyncgenfunction(fixturedef.func): diff --git a/tests/test_change_of_policy.py b/tests/test_change_of_policy.py new file mode 100644 index 00000000..4feb0a2e --- /dev/null +++ b/tests/test_change_of_policy.py @@ -0,0 +1,22 @@ +import asyncio +import pytest + + +@pytest.fixture(scope="module") +def old_policy(): + policy = asyncio.get_event_loop_policy() + yield policy + + +def test_1(old_policy): + assert old_policy == asyncio.get_event_loop_policy() + +@pytest.mark.asyncio +async def test_2(old_policy): + assert old_policy == asyncio.get_event_loop_policy() + +@pytest.mark.asyncio +async def test_3(old_policy): + # This test fails with pytest-asyncio V0.14 + # due to a teardown change of event loop policy + assert old_policy == asyncio.get_event_loop_policy()