@@ -357,8 +357,15 @@ def pytest_fixture_post_finalizer(fixturedef: FixtureDef, request: SubRequest) -
357
357
except RuntimeError :
358
358
loop = None
359
359
if loop is not None :
360
- # Clean up existing loop to avoid ResourceWarnings
361
- loop .close ()
360
+ # Cleanup code based on the implementation of asyncio.run()
361
+ try :
362
+ if not loop .is_closed ():
363
+ asyncio .runners ._cancel_all_tasks (loop )
364
+ loop .run_until_complete (loop .shutdown_asyncgens ())
365
+ if sys .version_info >= (3 , 9 ):
366
+ loop .run_until_complete (loop .shutdown_default_executor ())
367
+ finally :
368
+ loop .close ()
362
369
new_loop = policy .new_event_loop () # Replace existing event loop
363
370
# Ensure subsequent calls to get_event_loop() succeed
364
371
policy .set_event_loop (new_loop )
@@ -483,22 +490,13 @@ def pytest_runtest_setup(item: pytest.Item) -> None:
483
490
@pytest .fixture
484
491
def event_loop (request : "pytest.FixtureRequest" ) -> Iterator [asyncio .AbstractEventLoop ]:
485
492
"""Create an instance of the default event loop for each test case."""
486
- loop = asyncio .get_event_loop_policy ().new_event_loop ()
487
- yield loop
488
- # Cleanup code copied from the implementation of asyncio.run()
489
- try :
490
- if not loop .is_closed ():
491
- asyncio .runners ._cancel_all_tasks (loop )
492
- loop .run_until_complete (loop .shutdown_asyncgens ())
493
- if sys .version_info >= (3 , 9 ):
494
- loop .run_until_complete (loop .shutdown_default_executor ())
495
- finally :
496
- loop .close ()
497
- # Call the garbage collector to trigger ResourceWarning's as soon
498
- # as possible (these are triggered in various __del__ methods).
499
- # Without this, resources opened in one test can fail other tests
500
- # when the warning is generated.
501
- gc .collect ()
493
+ return asyncio .get_event_loop_policy ().new_event_loop ()
494
+ # Call the garbage collector to trigger ResourceWarning's as soon
495
+ # as possible (these are triggered in various __del__ methods).
496
+ # Without this, resources opened in one test can fail other tests
497
+ # when the warning is generated.
498
+ gc .collect ()
499
+ # Event loop cleanup handled by pytest_fixture_post_finalizer
502
500
503
501
504
502
def _unused_port (socket_type : int ) -> int :
0 commit comments