Skip to content

Commit 5f7df48

Browse files
cursoragentdobrac
andcommitted
Refactor: Use function-scoped event loop for tests
Co-authored-by: jakub.dobry <[email protected]>
1 parent d3499e9 commit 5f7df48

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

python/pytest.ini

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,5 @@
33
markers =
44
skip_debug: skip test if E2B_DEBUG is set.
55
asyncio_mode=auto
6-
asyncio_default_fixture_loop_scope=function
76

87
addopts = "--import-mode=importlib" "--numprocesses=2"

python/tests/conftest.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import pytest
22
import pytest_asyncio
33
import os
4+
import asyncio
45

56
from logging import warning
67

@@ -10,6 +11,28 @@
1011
timeout = 60
1112

1213

14+
@pytest_asyncio.fixture(scope="function")
15+
def event_loop():
16+
"""Create an instance of the default event loop for each test case."""
17+
policy = asyncio.get_event_loop_policy()
18+
loop = policy.new_event_loop()
19+
yield loop
20+
# Clean up any remaining tasks
21+
try:
22+
pending = asyncio.all_tasks(loop)
23+
for task in pending:
24+
task.cancel()
25+
if pending:
26+
loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
27+
except Exception:
28+
pass
29+
# Close the loop gracefully
30+
try:
31+
loop.close()
32+
except Exception:
33+
pass
34+
35+
1336
@pytest.fixture()
1437
def template():
1538
return os.getenv("E2B_TESTS_TEMPLATE") or "code-interpreter-v1"
@@ -31,7 +54,7 @@ def sandbox(template, debug):
3154
)
3255

3356

34-
@pytest_asyncio.fixture
57+
@pytest_asyncio.fixture(loop_scope="function")
3558
async def async_sandbox(template, debug):
3659
async_sandbox = await AsyncSandbox.create(template, timeout=timeout, debug=debug)
3760

@@ -40,6 +63,10 @@ async def async_sandbox(template, debug):
4063
finally:
4164
try:
4265
await async_sandbox.kill()
66+
except RuntimeError as e:
67+
# Ignore "Event loop is closed" errors during cleanup in pytest-xdist
68+
if "Event loop is closed" not in str(e):
69+
raise
4370
except: # noqa: E722
4471
if not debug:
4572
warning(

0 commit comments

Comments
 (0)