From 1f652ee84add4cd8b07773ddda019a8b496e24ae Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Fri, 14 Jan 2022 14:29:42 +0200 Subject: [PATCH 1/2] Don't close event loop if the loop doesn't exist --- README.rst | 1 + pytest_asyncio/plugin.py | 9 +++++++-- tests/test_event_loop_scope.py | 6 ++++++ 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/README.rst b/README.rst index 9d2257a5..9e1c5aa2 100644 --- a/README.rst +++ b/README.rst @@ -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 `_ +- Fixed a bug that closes the default event loop if the loop doesn't exist `#258 `_ 0.17.0 (22-01-13) ~~~~~~~~~~~~~~~~~~~ diff --git a/pytest_asyncio/plugin.py b/pytest_asyncio/plugin.py index 04b5e139..a7989b68 100644 --- a/pytest_asyncio/plugin.py +++ b/pytest_asyncio/plugin.py @@ -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) diff --git a/tests/test_event_loop_scope.py b/tests/test_event_loop_scope.py index 8ae4eb1e..21fd6415 100644 --- a/tests/test_event_loop_scope.py +++ b/tests/test_event_loop_scope.py @@ -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) From 953d9a1801a54ecbd8a02f312c92620c90c1c891 Mon Sep 17 00:00:00 2001 From: Andrew Svetlov Date: Fri, 14 Jan 2022 14:49:55 +0200 Subject: [PATCH 2/2] Fix issue number --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 9e1c5aa2..58e13553 100644 --- a/README.rst +++ b/README.rst @@ -259,7 +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 `_ -- Fixed a bug that closes the default event loop if the loop doesn't exist `#258 `_ +- Fixed a bug that closes the default event loop if the loop doesn't exist `#257 `_ 0.17.0 (22-01-13) ~~~~~~~~~~~~~~~~~~~