Skip to content

Commit

Permalink
Don't close event loop if the loop doesn't exist (#261)
Browse files Browse the repository at this point in the history
  • Loading branch information
asvetlov committed Jan 15, 2022
1 parent 6cc430c commit 0a3328f
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.rst
Expand Up @@ -259,6 +259,7 @@ Changelog
0.17.1 (UNRELEASED)
~~~~~~~~~~~~~~~~~~~
- Fixes a bug that prevents async Hypothesis tests from working without explicit ``asyncio`` marker when ``--asyncio-mode=auto`` is set. `#258 <https://github.com/pytest-dev/pytest-asyncio/issues/258>`_
- Fixed a bug that closes the default event loop if the loop doesn't exist `#257 <https://github.com/pytest-dev/pytest-asyncio/issues/257>`_

0.17.0 (22-01-13)
~~~~~~~~~~~~~~~~~~~
Expand Down
9 changes: 7 additions & 2 deletions pytest_asyncio/plugin.py
Expand Up @@ -169,8 +169,13 @@ def pytest_fixture_post_finalizer(fixturedef, request):
"""Called after fixture teardown"""
if fixturedef.argname == "event_loop":
policy = asyncio.get_event_loop_policy()
# Clean up existing loop to avoid ResourceWarnings
policy.get_event_loop().close()
try:
loop = policy.get_event_loop()
except RuntimeError:
loop = None
if loop is not None:
# Clean up existing loop to avoid ResourceWarnings
loop.close()
new_loop = policy.new_event_loop() # Replace existing event loop
# Ensure subsequent calls to get_event_loop() succeed
policy.set_event_loop(new_loop)
Expand Down
6 changes: 6 additions & 0 deletions tests/test_event_loop_scope.py
Expand Up @@ -29,3 +29,9 @@ def test_3():
current_loop = asyncio.get_event_loop_policy().get_event_loop()
# Now the event loop from test_2 should have been cleaned up
assert loop is not current_loop


def test_4(event_loop):
# If a test sets the loop to None -- pytest_fixture_post_finalizer()
# still should work
asyncio.get_event_loop_policy().set_event_loop(None)

0 comments on commit 0a3328f

Please sign in to comment.