Skip to content

Commit

Permalink
Changes to fix pytest-dev#168
Browse files Browse the repository at this point in the history
To take into account user case that sets a specific event loop policy before runnins pytest asyncio tests:
- Rollover changes in V0.14 (that clears event loop policy in pytest_fixture_post_finalizer)
- include a new unit test that checks if policy has been changed (fails with V0.14 and pass with this PR).
  • Loading branch information
alblasco committed Jun 28, 2020
1 parent 4e2e6bd commit 1792977
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
13 changes: 7 additions & 6 deletions pytest_asyncio/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)



Expand All @@ -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):
Expand Down
22 changes: 22 additions & 0 deletions tests/test_change_of_policy.py
Original file line number Diff line number Diff line change
@@ -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()

0 comments on commit 1792977

Please sign in to comment.