Skip to content

Commit 8a63a65

Browse files
Askaholicseifertm
authored andcommitted
Add cleanup code to event_loop that mimics the behavior of asyncio.run
1 parent 5697df2 commit 8a63a65

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

pytest_asyncio/plugin.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import contextlib
44
import enum
55
import functools
6+
import gc
67
import inspect
78
import socket
89
import sys
@@ -488,7 +489,19 @@ def event_loop(request: "pytest.FixtureRequest") -> Iterator[asyncio.AbstractEve
488489
"""Create an instance of the default event loop for each test case."""
489490
loop = asyncio.get_event_loop_policy().new_event_loop()
490491
yield loop
491-
loop.close()
492+
# Cleanup code copied from the implementation of asyncio.run()
493+
try:
494+
asyncio.runners._cancel_all_tasks(loop)
495+
loop.run_until_complete(loop.shutdown_asyncgens())
496+
if sys.version_info >= (3, 9):
497+
loop.run_until_complete(loop.shutdown_default_executor())
498+
finally:
499+
loop.close()
500+
# Call the garbage collector to trigger ResourceWarning's as soon
501+
# as possible (these are triggered in various __del__ methods).
502+
# Without this, resources opened in one test can fail other tests
503+
# when the warning is generated.
504+
gc.collect()
492505

493506

494507
def _unused_port(socket_type: int) -> int:

0 commit comments

Comments
 (0)