Skip to content

Commit 157eb30

Browse files
committed
WIP: Improve test cleanup process to handle event loop closing
1 parent bfa2a6e commit 157eb30

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

tests/conftest.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1+
"""Test configuration and fixtures."""
2+
3+
import asyncio
4+
import functools
15
import os
6+
from typing import AsyncGenerator
7+
8+
import pytest_asyncio
29

310

411
# Configure pytest-asyncio
@@ -10,3 +17,34 @@ def pytest_configure(config):
1017
os.environ["ALLOWED_COMMANDS"] = (
1118
"echo,sleep,cat,ls,pwd,touch,mkdir,rm,mv,cp,grep,awk,sed"
1219
)
20+
21+
22+
@pytest_asyncio.fixture()
23+
async def cleanup_processes() -> AsyncGenerator[None, None]:
24+
"""Ensure all subprocess are cleaned up after each test."""
25+
yield
26+
loop = asyncio.get_running_loop()
27+
28+
# Patch the close method to avoid errors during cleanup
29+
def quiet_close(self):
30+
try:
31+
self.close()
32+
except RuntimeError:
33+
pass
34+
35+
for transport in getattr(loop, "_transports", set()).copy():
36+
if hasattr(transport, "_proc"):
37+
transport.close = functools.partial(quiet_close, transport)
38+
39+
try:
40+
# Get all tasks and wait for them to complete
41+
tasks = [t for t in asyncio.all_tasks(loop) if not t.done()]
42+
if tasks:
43+
# Cancel all tasks and wait for them to complete
44+
for task in tasks:
45+
task.cancel()
46+
await asyncio.gather(*tasks, return_exceptions=True)
47+
# Shutdown async generators
48+
await loop.shutdown_asyncgens()
49+
except Exception as e:
50+
print(f"Error during cleanup: {e}")

0 commit comments

Comments
 (0)