Skip to content

Commit 5f3dee6

Browse files
committed
Teardown of the event_loop fixture no longer replaces the event loop policy.
Signed-off-by: Michael Seifert <[email protected]>
1 parent dceeb68 commit 5f3dee6

File tree

4 files changed

+40
-2
lines changed

4 files changed

+40
-2
lines changed

README.rst

+4
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,10 @@ Only test coroutines will be affected (by default, coroutines prefixed by
164164

165165
Changelog
166166
---------
167+
0.17.0 (UNRELEASED)
168+
~~~~~~~~~~~~~~~~~~~
169+
- `pytest-asyncio` no longer alters existing event loop policies. `#168 <https://github.com/pytest-dev/pytest-asyncio/issues/168>`_, `#188 <https://github.com/pytest-dev/pytest-asyncio/issues/168>`_
170+
167171
0.16.0 (2021-10-16)
168172
~~~~~~~~~~~~~~~~~~~
169173
- Add support for Python 3.10

pytest_asyncio/plugin.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,9 @@ def get_and_strip_from(self, name, data_dict):
8080
def pytest_fixture_post_finalizer(fixturedef, request):
8181
"""Called after fixture teardown"""
8282
if fixturedef.argname == "event_loop":
83-
# Set empty loop policy, so that subsequent get_event_loop() provides a new loop
84-
asyncio.set_event_loop_policy(None)
83+
policy = asyncio.get_event_loop_policy()
84+
new_loop = policy.new_event_loop() # Replace existing event loop
85+
policy.set_event_loop(new_loop) # Ensure subsequent calls to get_event_loop() succeed
8586

8687

8788
@pytest.hookimpl(hookwrapper=True)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
"""Defines and sets a custom event loop policy"""
2+
import asyncio
3+
from asyncio import DefaultEventLoopPolicy, SelectorEventLoop
4+
5+
6+
class TestEventLoop(SelectorEventLoop):
7+
pass
8+
9+
10+
class TestEventLoopPolicy(DefaultEventLoopPolicy):
11+
def new_event_loop(self):
12+
return TestEventLoop()
13+
14+
15+
# This statement represents a code which sets a custom event loop policy
16+
asyncio.set_event_loop_policy(TestEventLoopPolicy())
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
"""Tests that any externally provided event loop policy remains unaltered."""
2+
import asyncio
3+
4+
import pytest
5+
6+
7+
@pytest.mark.asyncio
8+
async def test_uses_loop_provided_by_custom_policy():
9+
"""Asserts that test cases use the event loop provided by the custom event loop policy"""
10+
assert type(asyncio.get_event_loop()).__name__ == "TestEventLoop"
11+
12+
13+
@pytest.mark.asyncio
14+
async def test_custom_policy_is_not_overwritten():
15+
"""Asserts that any custom event loop policy stays the same across test cases"""
16+
assert type(asyncio.get_event_loop()).__name__ == "TestEventLoop"
17+

0 commit comments

Comments
 (0)