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