Skip to content

Commit 0d4b8f5

Browse files
committed
Add cleanup code to event_loop that mimics the behavior of asyncio.run
1 parent 133d8a8 commit 0d4b8f5

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
@@ -484,7 +485,19 @@ def event_loop(request: "pytest.FixtureRequest") -> Iterator[asyncio.AbstractEve
484485
"""Create an instance of the default event loop for each test case."""
485486
loop = asyncio.get_event_loop_policy().new_event_loop()
486487
yield loop
487-
loop.close()
488+
# Cleanup code copied from the implementation of asyncio.run()
489+
try:
490+
asyncio.runners._cancel_all_tasks(loop)
491+
loop.run_until_complete(loop.shutdown_asyncgens())
492+
if sys.version_info >= (3, 9):
493+
loop.run_until_complete(loop.shutdown_default_executor())
494+
finally:
495+
loop.close()
496+
# Call the garbage collector to trigger ResourceWarning's as soon
497+
# as possible (these are triggered in various __del__ methods).
498+
# Without this, resources opened in one test can fail other tests
499+
# when the warning is generated.
500+
gc.collect()
488501

489502

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

0 commit comments

Comments
 (0)