Skip to content

Build and run agents you can see, understand and trust.

test(workspace): install checkout wheels in sandbox integration tests (#3368)

qbcbdad647d2fee
diff --git a/tests/backend_daytona_test.py b/tests/backend_daytona_test.py
index 9dc8c0463..072b94ebd 100644
--- a/tests/backend_daytona_test.py
+++ b/tests/backend_daytona_test.py
@@ -9,7 +9,6 @@ A live smoke suite exercises the real SDK mapping and is skipped unless
import unittest
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
-from unittest.async_case import IsolatedAsyncioTestCase
from _daytona_live_utils import (
DAYTONA_API_KEY,
@@ -19,13 +18,17 @@ from _daytona_live_utils import (
live_daytona_workspace_id,
)
+from sandbox_test_support import CheckoutWheelTestCase
+
from agentscope.workspace import DaytonaBackend, DaytonaWorkspace
@unittest.skipUnless(DAYTONA_API_KEY, SKIP_REASON)
-class TestDaytonaBackendLive(IsolatedAsyncioTestCase):
+class TestDaytonaBackendLive(CheckoutWheelTestCase):
"""Live Daytona backend parity, skipped without credentials."""
+ workspace_type = DaytonaWorkspace
+
@asynccontextmanager
async def _live_backend(
self,
diff --git a/tests/backend_docker_test.py b/tests/backend_docker_test.py
index 62473740c..0d0d00b1b 100644
--- a/tests/backend_docker_test.py
+++ b/tests/backend_docker_test.py
@@ -24,7 +24,8 @@ import sys
import tempfile
import unittest
import uuid
-from unittest.async_case import IsolatedAsyncioTestCase
+
+from sandbox_test_support import CheckoutWheelTestCase
from agentscope.tool import ExecResult
from agentscope.workspace import DockerWorkspace, DockerBackend
@@ -60,9 +61,11 @@ _SKIP_REASON = "Docker backend is only tested on Linux with a live daemon"
@unittest.skipUnless(_DOCKER_OK, _SKIP_REASON)
-class TestDockerBackend(IsolatedAsyncioTestCase):
+class TestDockerBackend(CheckoutWheelTestCase):
"""Test cases for ``DockerBackend`` against a live container."""
+ workspace_type = DockerWorkspace
+
async def asyncSetUp(self) -> None:
"""Start a workspace and reuse its wired backend.
diff --git a/tests/backend_e2b_test.py b/tests/backend_e2b_test.py
index 7da141242..8cd357113 100644
--- a/tests/backend_e2b_test.py
+++ b/tests/backend_e2b_test.py
@@ -18,7 +18,8 @@ avoids duplicating the sandbox bring-up logic here.
import os
import unittest
-from unittest.async_case import IsolatedAsyncioTestCase
+
+from sandbox_test_support import CheckoutWheelTestCase
from agentscope.tool import ExecResult
from agentscope.workspace import E2BWorkspace
@@ -33,13 +34,15 @@ _SKIP_REASON = "E2B_API_KEY environment variable is not set"
@unittest.skipUnless(_E2B_API_KEY, _SKIP_REASON)
-class TestE2BBackend(IsolatedAsyncioTestCase):
+class TestE2BBackend(CheckoutWheelTestCase):
"""Test cases for ``E2BBackend`` against a live sandbox.
Each test creates a real E2B cloud sandbox via ``E2BWorkspace`` and
tears it down (``close`` → sandbox pause) afterwards.
"""
+ workspace_type = E2BWorkspace
+
async def asyncSetUp(self) -> None:
"""Start a workspace and reuse its wired backend."""
self.workspace = E2BWorkspace(api_key=_E2B_API_KEY)
diff --git a/tests/backend_opensandbox_test.py b/tests/backend_opensandbox_test.py
index 6f655325a..3c01ab9d1 100644
--- a/tests/backend_opensandbox_test.py
+++ b/tests/backend_opensandbox_test.py
@@ -23,6 +23,8 @@ from types import SimpleNamespace
from unittest.async_case import IsolatedAsyncioTestCase
from unittest.mock import AsyncMock
+from sandbox_test_support import CheckoutWheelTestCase
+
from agentscope.tool import ExecResult
from agentscope.workspace import OpenSandboxWorkspace
from agentscope.workspace import OpenSandboxBackend
@@ -37,7 +39,7 @@ _SKIP_REASON = "OPENSANDBOX_DOMAIN environment variable is not set"
@unittest.skipUnless(_DOMAIN, _SKIP_REASON)
-class TestOpenSandboxBackend(IsolatedAsyncioTestCase):
+class TestOpenSandboxBackend(CheckoutWheelTestCase):
"""Test cases for ``OpenSandboxBackend`` against a live sandbox.
Each test creates a real OpenSandbox sandbox via
@@ -45,6 +47,8 @@ class TestOpenSandboxBackend(IsolatedAsyncioTestCase):
pause) afterwards.
"""
+ workspace_type = OpenSandboxWorkspace
+
async def asyncSetUp(self) -> None:
"""Start a workspace and reuse its wired backend."""
self.workspace = OpenSandboxWorkspace(
diff --git a/tests/sandbox_checkout_wheel_test.py b/tests/sandbox_checkout_wheel_test.py
new file mode 100644
index 000000000..6e346c4f2
--- /dev/null
+++ b/tests/sandbox_checkout_wheel_test.py
@@ -0,0 +1,738 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Regression tests for checkout wheel installation in live sandboxes."""
+
+import posixpath
+import shutil
+import subprocess
+import tempfile
+import unittest
+from functools import cache
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock, patch
+from zipfile import ZipFile
+
+import sandbox_test_support as support
+from sandbox_test_support._verify_wheel import verify_wheel
+
+from agentscope.workspace import (
+ AppleContainerWorkspace,
+ BubblewrapWorkspace,
+ DaytonaWorkspace,
+ DockerWorkspace,
+ E2BWorkspace,
+ OpenSandboxWorkspace,
+)
+from agentscope.workspace._docker._make_dockerfile import prepare_build_context
+
+
+class TestCheckoutWheelBuild(unittest.TestCase):
+ """Build caching, failure handling, and skip behavior."""
+
+ def setUp(self) -> None:
+ """Use an isolated cache without invalidating real live-test wheels."""
+ self.enterContext(patch.object(support, "_WHEEL_BUILD_ERROR", None))
+ self.enterContext(
+ patch.object(support.shutil, "which", return_value="/tools/uv"),
+ )
+ self.uv_version = self.enterContext(
+ patch.object(
+ support.subprocess,
+ "check_output",
+ return_value=f"uv {support.UV_VERSION} (test build)\n",
+ ),
+ )
+ self.enterContext(
+ patch.object(
+ support,
+ "checkout_wheel",
+ cache(support.checkout_wheel.__wrapped__),
+ ),
+ )
+
+ def test_build_once_from_worktree(self) -> None:
+ """Stage actual checkout files and reuse the same wheel path."""
+ cleanups = []
+
+ def build(args: list[str], **kwargs: object) -> None:
+ """Produce one fake wheel after checking the staged source."""
+ self.assertEqual(
+ kwargs["env"],
+ {
+ "BUILD_SENTINEL": "retained",
+ "SOURCE_DATE_EPOCH": "315532800",
+ },
+ )
+ source = Path(args[-1])
+ repo = Path(support.__file__).resolve().parents[2]
+ self.assertEqual(
+ (source / "src/agentscope/_version.py").read_bytes(),
+ (repo / "src/agentscope/_version.py").read_bytes(),
+ )
+ self.assertEqual(args[0], "/tools/uv")
+ self.assertEqual(
+ {
+ name: (source / name).read_bytes()
+ for name in ("pyproject.toml", "README.md", "LICENSE")
+ },
+ {
+ name: (repo / name).read_bytes()
+ for name in ("pyproject.toml", "README.md", "LICENSE")
+ },
+ )
+ output = Path(args[args.index("--out-dir") + 1])
+ output.mkdir()
+ with ZipFile(
+ output / "agentscope-1.0-py3-none-any.whl",
+ "w",
+ ) as archive:
+ archive.write(
+ source / "LICENSE",
+ "agentscope-1.0.dist-info/licenses/LICENSE",
+ )
+
+ major, minor, patch_version = map(int, support.UV_VERSION.split("."))
+ versions = (
+ support.UV_VERSION,
+ f"{major}.{minor}.{patch_version + 10}",
+ )
+ with (
+ patch.dict(
+ support.os.environ,
+ {"BUILD_SENTINEL": "retained", "SOURCE_DATE_EPOCH": "123"},
+ clear=True,
+ ),
+ patch.object(support.subprocess, "run", side_effect=build) as run,
+ patch.object(
+ support.atexit,
+ "register",
+ side_effect=cleanups.append,
+ ),
+ ):
+ for version in versions:
+ with self.subTest(uv_version=version):
+ support.checkout_wheel.cache_clear()
+ run.reset_mock()
+ self.uv_version.reset_mock()
+ self.uv_version.return_value = f"uv {version} (test build)"
+ cleanups.clear()
+ try:
+ first = support.checkout_wheel()
+ self.assertEqual(support.checkout_wheel(), first)
+ self.assertEqual(run.call_count, 1)
+ self.uv_version.assert_called_once_with(
+ ["/tools/uv", "--version"],
+ text=True,
+ timeout=10,
+ )
+ with ZipFile(first) as archive:
+ self.assertEqual(
+ archive.namelist(),
+ ["agentscope-1.0.dist-info/licenses/LICENSE"],
+ )
+ finally:
+ for cleanup in cleanups:
+ cleanup()
+ self.assertFalse(first.exists())
+
+ def test_old_uv_is_rejected_before_build(self) -> None:
+ """Reject outdated or unrecognized uv versions before any build."""
+ for output in ("uv 0.0.1", f"uv {support.UV_VERSION}-rc.1", "unknown"):
+ with self.subTest(output=output):
+ support._WHEEL_BUILD_ERROR = None
+ self.uv_version.reset_mock()
+ self.uv_version.return_value = output
+ with (
+ patch.object(support.subprocess, "run") as run,
+ patch.object(
+ support.tempfile,
+ "TemporaryDirectory",
+ ) as directory,
+ self.assertRaises(RuntimeError) as raised,
+ ):
+ support.checkout_wheel()
+ self.assertEqual(
+ str(raised.exception),
+ f"Checkout wheel tests require uv>={support.UV_VERSION}; "
+ f"found {output!r}. Upgrade uv on the host PATH.",
+ )
+ with self.assertRaises(RuntimeError) as repeated:
+ support.checkout_wheel()
+ self.assertIs(repeated.exception, raised.exception)
+ self.uv_version.assert_called_once()
+ directory.assert_not_called()
+ run.assert_not_called()
+
+ def test_uv_version_query_failure_is_cached(self) -> None:
+ """Explain failed host checks and avoid retrying them per class."""
+ for error in (
+ subprocess.CalledProcessError(1, ["uv", "--version"]),
+ subprocess.TimeoutExpired(["uv", "--version"], 10),
+ OSError("cannot execute uv"),
+ ):
+ with self.subTest(error=type(error).__name__):
+ support._WHEEL_BUILD_ERROR = None
+ self.uv_version.reset_mock()
+ self.uv_version.side_effect = error
+ with patch.object(support.subprocess, "run") as run:
+ for _ in range(2):
+ with self.assertRaises(RuntimeError) as raised:
+ support.checkout_wheel()
+ self.assertEqual(
+ str(raised.exception),
+ "Could not check host uv version. Check or "
+ "upgrade uv on the host PATH "
+ f"(requires uv>={support.UV_VERSION}): {error}",
+ )
+ self.assertIs(raised.exception.__cause__, error)
+ run.assert_not_called()
+ self.uv_version.assert_called_once()
+
+ def test_missing_uv_skips_live_class_before_build(self) -> None:
+ """A reachable Docker daemon alone is insufficient to build wheels."""
+
+ class LiveDocker(support.CheckoutWheelTestCase):
+ """An enabled Docker class with no host build tool."""
+
+ workspace_type = DockerWorkspace
+
+ async def test_live(self) -> None:
+ """Never start a workspace without the build prerequisite."""
+ self.fail("Missing uv should skip this class")
+
+ with (
+ patch.object(support.shutil, "which", return_value=None),
+ patch.object(support.subprocess, "run") as run,
+ patch.object(support.tempfile, "TemporaryDirectory") as directory,
+ ):
+ result = unittest.TestResult()
+ unittest.defaultTestLoader.loadTestsFromTestCase(LiveDocker).run(
+ result,
+ )
+ self.assertEqual(
+ {
+ "run": result.testsRun,
+ "errors": result.errors,
+ "failures": result.failures,
+ "skip_reasons": [reason for _, reason in result.skipped],
+ },
+ {
+ "run": 0,
+ "errors": [],
+ "failures": [],
+ "skip_reasons": [
+ "Checkout wheel tests require uv on the host PATH. "
+ "Install it with: python -m pip install "
+ f'"uv>={support.UV_VERSION}"',
+ ],
+ },
+ )
+ directory.assert_not_called()
+ run.assert_not_called()
+
+ def test_missing_or_changed_wheel_license_fails_build(self) -> None:
+ """Reject incomplete artifacts even if the build command succeeded."""
+ for content in (None, b"truncated license"):
+ with self.subTest(content=content):
+ support._WHEEL_BUILD_ERROR = None
+
+ def build(
+ args: list[str],
+ license_content: bytes | None = content,
+ **_kwargs: object,
+ ) -> None:
+ """Produce an invalid wheel to exercise artifact checks."""
+ output = Path(args[args.index("--out-dir") + 1])
+ output.mkdir()
+ with ZipFile(
+ output / "agentscope-1.0-py3-none-any.whl",
+ "w",
+ ) as archive:
+ if license_content is not None:
+ archive.writestr(
+ "agentscope-1.0.dist-info/licenses/LICENSE",
+ license_content,
+ )
+
+ with (
+ patch.object(support.subprocess, "run", side_effect=build),
+ patch.object(support.atexit, "register") as register,
+ self.assertRaisesRegex(RuntimeError, "complete LICENSE"),
+ ):
+ support.checkout_wheel()
+ register.assert_not_called()
+
+ def test_build_failure_is_cached(self) -> None:
+ """Build errors retain diagnostics without repeating the build."""
+ error = subprocess.CalledProcessError(
+ 1,
+ "uv",
+ output="build output",
+ stderr="build error",
+ )
+ with patch.object(
+ support.subprocess,
+ "run",
+ side_effect=error,
+ ) as run:
+ for _ in range(2):
+ with self.assertRaises(RuntimeError) as raised:
+ support.checkout_wheel()
+ self.assertEqual(
+ str(raised.exception),
+ "Checkout wheel build failed:\nbuild output\nbuild error",
+ )
+ self.assertIs(raised.exception.__cause__, error)
+ self.assertEqual(run.call_count, 1)
+
+ def test_process_control_exceptions_are_not_cached(self) -> None:
+ """Interrupting a build must not poison the process cache."""
+ for error in (KeyboardInterrupt(), SystemExit()):
+ with self.subTest(error=type(error).__name__):
+ with patch.object(
+ support.subprocess,
+ "run",
+ side_effect=error,
+ ) as run:
+ for _ in range(2):
+ with self.assertRaises(type(error)):
+ support.checkout_wheel()
+ self.assertEqual(run.call_count, 2)
+ self.assertIsNone(support._WHEEL_BUILD_ERROR)
+
+ def test_missing_workspace_type_fails_before_build(self) -> None:
+ """Report missing configuration before spending time building."""
+
+ class MissingWorkspace(support.CheckoutWheelTestCase):
+ """A live test that omitted its workspace class."""
+
+ with patch.object(support, "checkout_wheel") as build:
+ with self.assertRaises(TypeError) as raised:
+ MissingWorkspace.setUpClass()
+ self.assertEqual(
+ str(raised.exception),
+ "MissingWorkspace must set workspace_type "
+ "to the workspace class under test",
+ )
+ build.assert_not_called()
+
+ def test_skipped_class_does_not_build(self) -> None:
+ """Unavailable live environments never pay the build cost."""
+
+ @unittest.skip("No sandbox")
+ class Skipped(support.CheckoutWheelTestCase):
+ """A disabled live test."""
+
+ async def test_live(self) -> None:
+ """Never run."""
+
+ with patch.object(support, "checkout_wheel") as build:
+ result = unittest.TestResult()
+ unittest.defaultTestLoader.loadTestsFromTestCase(Skipped).run(
+ result,
+ )
+ self.assertEqual((result.testsRun, len(result.skipped)), (1, 1))
+ build.assert_not_called()
+
+ def test_docker_payload_changes_image_tag(self) -> None:
+ """Same wheel filename with different bytes invalidates the image."""
+ with tempfile.TemporaryDirectory() as directory:
+ wheel = Path(directory) / "agentscope-1.0-py3-none-any.whl"
+ tags = []
+ for data in (b"first", b"second", b"second"):
+ wheel.write_bytes(data)
+ context, tag, payloads = support.wheel_build_context(
+ prepare_build_context,
+ wheel,
+ )
+ self.addCleanup(support.shutil.rmtree, context)
+ tags.append(tag)
+ dockerfile = (context / "Dockerfile").read_text()
+ self.assertEqual(payloads[wheel.name], data)
+ self.assertEqual((context / wheel.name).read_bytes(), data)
+ self.assertIn(
+ f"--no-deps --reinstall /tmp/{wheel.name}",
+ dockerfile,
+ )
+ self.assertNotIn('--no-deps "agentscope"', dockerfile)
+ self.assertIn("python -I /tmp/_verify_wheel.py", dockerfile)
+ self.assertNotEqual(tags[0], tags[1])
+ self.assertEqual(tags[1], tags[2])
+
+ def test_installed_bytes_must_match(self) -> None:
+ """A same-version package with stale files fails verification."""
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ wheel = root / "agentscope.whl"
+ source = root / "agentscope/_version.py"
+ source.parent.mkdir()
+ source.write_bytes(b"checkout")
+ with ZipFile(wheel, "w") as archive:
+ archive.writestr("agentscope/_version.py", b"checkout")
+ installed = Mock(locate_file=lambda name: root / name)
+ with patch(
+ "sandbox_test_support._verify_wheel.distribution",
+ return_value=installed,
+ ):
+ verify_wheel(str(wheel))
+ source.write_bytes(b"published")
+ with self.assertRaisesRegex(RuntimeError, "_version.py"):
+ verify_wheel(str(wheel))
+
+ def test_class_patches_are_restored(self) -> None:
+ """Live-class adapters do not alter later production unit tests."""
+
+ class CustomDocker(DockerWorkspace):
+ """A Docker subclass must keep using the image build adapter."""
+
+ for workspace_type in (DockerWorkspace, CustomDocker, E2BWorkspace):
+ with self.subTest(workspace_type=workspace_type):
+ original = workspace_type._setup_mcp_gateway
+ prepare = support.docker_module.prepare_build_context
+
+ class Live(support.CheckoutWheelTestCase):
+ """A live class whose patch scope is exercised directly."""
+
+ Live.workspace_type = workspace_type
+ with patch.object(
+ support,
+ "checkout_wheel",
+ return_value=Path("test.whl"),
+ ):
+ try:
+ Live.setUpClass()
+ if issubclass(workspace_type, DockerWorkspace):
+ self.assertIsNot(
+ support.docker_module.prepare_build_context,
+ prepare,
+ )
+ else:
+ self.assertIsNot(
+ workspace_type._setup_mcp_gateway,
+ original,
+ )
+ finally:
+ Live.doClassCleanups()
+ self.assertIs(workspace_type._setup_mcp_gateway, original)
+ self.assertIs(
+ support.docker_module.prepare_build_context,
+ prepare,
+ )
+
+
+class TestCheckoutGateway(unittest.IsolatedAsyncioTestCase):
+ """Fresh and resumed gateways verify the checkout before starting."""
+
+ async def asyncSetUp(self) -> None:
+ """Create a fake backend and a wheel artifact."""
+ self.enterContext(
+ patch.object(
+ support,
+ "uuid4",
+ return_value=SimpleNamespace(hex="test"),
+ ),
+ )
+ temporary = tempfile.TemporaryDirectory()
+ self.addCleanup(temporary.cleanup)
+ self.wheel = Path(temporary.name) / "agentscope-1.0-py3-none-any.whl"
+ self.wheel.write_bytes(b"checkout")
+ self.events = []
+ self.success = SimpleNamespace(
+ ok=lambda: True,
+ exit_code=0,
+ stdout=b"",
+ stderr=b"",
+ )
+
+ async def execute(args: list[str], **_kwargs: object) -> object:
+ """Record execution order."""
+ self.events.append(args)
+ return self.success
+
+ self.backend = SimpleNamespace(
+ join_path=posixpath.join,
+ exec_shell=AsyncMock(side_effect=execute),
+ write_file=AsyncMock(),
+ file_exists=AsyncMock(return_value=False),
+ )
+ self.workspace = E2BWorkspace()
+ self.workspace._backend = self.backend
+
+ async def test_fresh_and_resumed_verify_before_launch(self) -> None:
+ """Only fresh bootstrap installs; resume verifies without repair."""
+ original = self.workspace._bootstrap_commands()
+ for ready in (False, True):
+ with self.subTest(ready=ready):
+ self.events.clear()
+ self.backend.file_exists.return_value = ready
+
+ async def launch(workspace: object) -> None:
+ """Assert bootstrap will not execute twice."""
+ self.assertEqual(workspace._bootstrap_commands(), [])
+ self.events.append("launch")
+
+ await support.setup_checkout_gateway(
+ self.workspace,
+ self.wheel,
+ launch,
+ )
+ commands = [
+ entry[2]
+ for entry in self.events
+ if isinstance(entry, list) and entry[0] == "sh"
+ ]
+ self.assertEqual(
+ commands[:-1],
+ [] if ready else original[:-1],
+ )
+ wheel_path = (
+ f"{self.workspace.workdir}/.checkout-wheel-test/"
+ f"{self.wheel.name}"
+ )
+ verify = [
+ self.workspace._gateway_python,
+ "-I",
+ f"{self.workspace.workdir}/.checkout-wheel-test/"
+ "_verify_wheel.py",
+ wheel_path,
+ ]
+ expected = (
+ verify
+ if ready
+ else [
+ "uv",
+ "pip",
+ "install",
+ "--python",
+ self.workspace._gateway_python,
+ "--no-deps",
+ "--reinstall",
+ wheel_path,
+ "&&",
+ *verify,
+ ]
+ )
+ self.assertEqual(
+ support.shlex.split(commands[-1]),
+ expected,
+ )
+ self.assertEqual(self.events[-1], "launch")
+ self.assertEqual(
+ self.workspace._bootstrap_commands(),
+ original,
+ )
+
+ async def test_resume_verification_failure_prevents_gateway_launch(
+ self,
+ ) -> None:
+ """Resume detects corruption without silently repairing the venv."""
+ self.backend.file_exists.return_value = True
+ failure = SimpleNamespace(
+ ok=lambda: False,
+ exit_code=1,
+ stdout=b"",
+ stderr=b"checkout mismatch",
+ )
+ self.backend.exec_shell.side_effect = [self.success, failure, failure]
+ launch = AsyncMock()
+ with self.assertRaisesRegex(RuntimeError, "checkout mismatch"):
+ await support.setup_checkout_gateway(
+ self.workspace,
+ self.wheel,
+ launch,
+ )
+ launch.assert_not_awaited()
+ self.assertEqual(
+ support.shlex.split(
+ self.backend.exec_shell.await_args_list[1].args[0][2],
+ ),
+ [
+ self.workspace._gateway_python,
+ "-I",
+ f"{self.workspace.workdir}/.checkout-wheel-test/"
+ "_verify_wheel.py",
+ f"{self.workspace.workdir}/.checkout-wheel-test/"
+ f"{self.wheel.name}",
+ ],
+ )
+ self.backend.exec_shell.assert_awaited_with(
+ [
+ "rm",
+ "-rf",
+ f"{self.workspace.workdir}/.checkout-wheel-test",
+ ],
+ )
+
+ async def test_upload_failure_prevents_gateway_launch(self) -> None:
+ """Cleanup after a partial upload preserves the original failure."""
+ self.backend.write_file.side_effect = [None, OSError("upload failed")]
+ self.backend.exec_shell.side_effect = [
+ self.success,
+ OSError("cleanup failed"),
+ ]
+ launch = AsyncMock()
+ with self.assertRaisesRegex(OSError, "upload failed"):
+ await support.setup_checkout_gateway(
+ self.workspace,
+ self.wheel,
+ launch,
+ )
+ launch.assert_not_awaited()
+ self.backend.exec_shell.assert_awaited_with(
+ [
+ "rm",
+ "-rf",
+ f"{self.workspace.workdir}/.checkout-wheel-test",
+ ],
+ )
+
+ async def test_upload_directory_creation_failure_stops_without_cleanup(
+ self,
+ ) -> None:
+ """Never reuse or delete a directory that could not be created."""
+ self.backend.exec_shell.side_effect = None
+ self.backend.exec_shell.return_value = SimpleNamespace(
+ ok=lambda: False,
+ )
+ launch = AsyncMock()
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "create checkout upload dir",
+ ):
+ await support.setup_checkout_gateway(
+ self.workspace,
+ self.wheel,
+ launch,
+ )
+ self.backend.write_file.assert_not_awaited()
+ self.backend.exec_shell.assert_awaited_once_with(
+ ["mkdir", f"{self.workspace.workdir}/.checkout-wheel-test"],
+ )
+ launch.assert_not_awaited()
+
+ async def test_same_named_user_files_survive_success_and_failure(
+ self,
+ ) -> None:
+ """Only files in the exclusively created directory may be removed."""
+ root = self.wheel.parent / "workspace"
+ root.mkdir()
+ expected = {
+ self.wheel.name: b"user wheel",
+ "_verify_wheel.py": b"user script",
+ }
+ for name, data in expected.items():
+ (root / name).write_bytes(data)
+ self.workspace.workdir = str(root)
+ self.backend.file_exists.return_value = True
+ self.backend.write_file.side_effect = lambda path, data: Path(
+ path,
+ ).write_bytes(data)
+
+ async def execute(args: list[str], **_kwargs: object) -> object:
+ """Use real file operations but keep package installation fake."""
+ if args[0] == "mkdir":
+ Path(args[1]).mkdir()
+ elif args[0] == "rm":
+ shutil.rmtree(args[-1])
+ else:
+ return self.backend.exec_shell.return_value
+ return self.success
+
+ self.backend.exec_shell.side_effect = execute
+ failure = SimpleNamespace(
+ ok=lambda: False,
+ exit_code=1,
+ stdout=b"",
+ stderr=b"install failed",
+ )
+ for result in (self.success, failure):
+ with self.subTest(install_ok=result.ok()):
+ self.backend.exec_shell.return_value = result
+ launch = AsyncMock()
+ if result.ok():
+ await support.setup_checkout_gateway(
+ self.workspace,
+ self.wheel,
+ launch,
+ )
+ launch.assert_awaited_once()
+ else:
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "install failed",
+ ):
+ await support.setup_checkout_gateway(
+ self.workspace,
+ self.wheel,
+ launch,
+ )
+ launch.assert_not_awaited()
+ self.assertEqual(
+ {path.name: path.read_bytes() for path in root.iterdir()},
+ expected,
+ )
+
+ async def test_bubblewrap_uses_readiness_probe(self) -> None:
+ """Persisted Bubblewrap environments verify without reinstalling."""
+ workspace = BubblewrapWorkspace()
+ workspace._backend = self.backend
+ with patch.object(
+ workspace,
+ "_bootstrap_is_ready",
+ AsyncMock(return_value=True),
+ ) as ready:
+ await support.setup_checkout_gateway(
+ workspace,
+ self.wheel,
+ AsyncMock(),
+ )
+ ready.assert_awaited_once()
+ self.backend.file_exists.assert_not_awaited()
+ self.assertEqual(len(self.events), 3)
+ self.assertEqual(
+ support.shlex.split(self.events[1][2]),
+ [
+ workspace._gateway_python,
+ "-I",
+ f"{workspace.workdir}/.checkout-wheel-test/_verify_wheel.py",
+ f"{workspace.workdir}/.checkout-wheel-test/{self.wheel.name}",
+ ],
+ )
+
+ async def test_provider_commands_preserve_paths_and_dependencies(
+ self,
+ ) -> None:
+ """All remote providers keep their uv path and dependency commands."""
+ for workspace in (
+ OpenSandboxWorkspace(),
+ AppleContainerWorkspace(),
+ DaytonaWorkspace(),
+ ):
+ with self.subTest(provider=type(workspace).__name__):
+ workspace._backend = self.backend
+ if isinstance(workspace, DaytonaWorkspace):
+ workspace._user_home = "/home/test user"
+ workspace._gateway_home = "/home/test user/.agentscope"
+ workspace._uv_bin = "/home/test user/.local/bin/uv"
+ workspace.workdir = "/home/test user/workspace"
+ original = workspace._bootstrap_commands()
+ self.events.clear()
+ await support.setup_checkout_gateway(
+ workspace,
+ self.wheel,
+ AsyncMock(),
+ )
+ commands = [
+ entry[2] for entry in self.events if entry[0] == "sh"
+ ]
+ self.assertEqual(commands[:-1], original[:-1])
+ self.assertEqual(
+ support.shlex.split(commands[-1].split(" && ")[0]),
+ [
+ *support.shlex.split(original[-1])[:-1],
+ "--reinstall",
+ f"{workspace.workdir}/.checkout-wheel-test/"
+ f"{self.wheel.name}",
+ ],
+ )
diff --git a/tests/sandbox_test_support/__init__.py b/tests/sandbox_test_support/__init__.py
new file mode 100644
index 000000000..212349a3d
--- /dev/null
+++ b/tests/sandbox_test_support/__init__.py
@@ -0,0 +1,282 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Install the current checkout only in opted-in live workspace tests."""
+
+import atexit
+import os
+import re
+import shlex
+import shutil
+import subprocess
+import sys
+import tempfile
+from contextlib import ExitStack, suppress
+from functools import cache
+from pathlib import Path
+from typing import Any
+from unittest import IsolatedAsyncioTestCase, SkipTest
+from unittest.mock import patch
+from uuid import uuid4
+from zipfile import ZipFile
+
+from agentscope.workspace import BubblewrapWorkspace, DockerWorkspace
+from agentscope.workspace._docker import _docker_workspace as docker_module
+from agentscope.workspace._docker._make_dockerfile import compute_image_tag
+from agentscope.workspace._utils import UV_VERSION
+
+_VERIFY_SCRIPT = Path(__file__).with_name("_verify_wheel.py")
+_WHEEL_BUILD_ERROR: Exception | None = None
+
+
+@cache
+def checkout_wheel() -> Path:
+ """Build once per process without leaving build artifacts in the repo."""
+ global _WHEEL_BUILD_ERROR
+ if _WHEEL_BUILD_ERROR is not None:
+ raise _WHEEL_BUILD_ERROR
+ try:
+ return _build_checkout_wheel()
+ except Exception as exc:
+ _WHEEL_BUILD_ERROR = exc
+ raise
+
+
+def _build_checkout_wheel() -> Path:
+ """Build the checkout with the host toolchain and retain the artifact."""
+ uv = shutil.which("uv")
+ if uv is None:
+ raise SkipTest(
+ "Checkout wheel tests require uv on the host PATH. "
+ f'Install it with: python -m pip install "uv>={UV_VERSION}"',
+ )
+ # Use the sandbox CA baseline: uv fetches build backends with bundled CAs.
+ try:
+ output = subprocess.check_output(
+ [uv, "--version"],
+ text=True,
+ timeout=10,
+ ).strip()
+ except (
+ OSError,
+ subprocess.CalledProcessError,
+ subprocess.TimeoutExpired,
+ ) as exc:
+ raise RuntimeError(
+ "Could not check host uv version. Check or upgrade uv on the "
+ f"host PATH (requires uv>={UV_VERSION}): {exc}",
+ ) from exc
+ version = re.match(r"uv (\d+)\.(\d+)\.(\d+)(?:\s|$)", output)
+ if version is None or tuple(map(int, version.groups())) < tuple(
+ map(int, UV_VERSION.split(".")),
+ ):
+ raise RuntimeError(
+ f"Checkout wheel tests require uv>={UV_VERSION}; "
+ f"found {output!r}. Upgrade uv on the host PATH.",
+ )
+ repo = Path(__file__).resolve().parents[2]
+ # Keep the wheel alive across test classes until the process exits.
+ # pylint: disable=consider-using-with
+ temporary = tempfile.TemporaryDirectory(prefix="as-test-wheel-")
+ root = Path(temporary.name)
+ source = root / "source"
+ source.mkdir()
+ try:
+ # Keep these root inputs in sync with the packaging configuration.
+ for name in ("pyproject.toml", "README.md", "LICENSE"):
+ shutil.copy2(repo / name, source / name)
+ # Include uncommitted and untracked source files in the working tree.
+ shutil.copytree(
+ repo / "src",
+ source / "src",
+ ignore=shutil.ignore_patterns("__pycache__", "*.egg-info"),
+ )
+ subprocess.run(
+ [
+ uv,
+ "build",
+ "--wheel",
+ "--python",
+ sys.executable,
+ "--out-dir",
+ str(root / "wheels"),
+ str(source),
+ ],
+ check=True,
+ capture_output=True,
+ text=True,
+ timeout=600,
+ # Fix ZIP timestamps so unchanged wheels reuse Docker image tags.
+ env={**os.environ, "SOURCE_DATE_EPOCH": "315532800"},
+ )
+ wheels = list((root / "wheels").glob("*.whl"))
+ if len(wheels) != 1:
+ raise RuntimeError(f"Expected one checkout wheel, got {wheels}")
+ with ZipFile(wheels[0]) as archive:
+ licenses = [
+ name
+ for name in archive.namelist()
+ if name.endswith(".dist-info/licenses/LICENSE")
+ ]
+ if (
+ len(licenses) != 1
+ or archive.read(licenses[0])
+ != (source / "LICENSE").read_bytes()
+ ):
+ raise RuntimeError(
+ "Checkout wheel must contain the complete LICENSE",
+ )
+ except subprocess.TimeoutExpired as exc:
+ temporary.cleanup()
+ raise RuntimeError(
+ f"Checkout wheel build timed out after {exc.timeout} seconds",
+ ) from exc
+ except subprocess.CalledProcessError as exc:
+ temporary.cleanup()
+ raise RuntimeError(
+ f"Checkout wheel build failed:\n{exc.stdout}\n{exc.stderr}",
+ ) from exc
+ except BaseException:
+ temporary.cleanup()
+ raise
+ atexit.register(temporary.cleanup)
+ return wheels[0]
+
+
+def wheel_build_context(
+ prepare: Any,
+ wheel: Path,
+ **kwargs: Any,
+) -> tuple[Path, str, dict[str, bytes]]:
+ """Replace the index install and include wheel bytes in the image tag."""
+ context, _, payloads = prepare(**kwargs)
+ try:
+ dockerfile = (context / "Dockerfile").read_text(encoding="utf-8")
+ original = 'RUN uv pip install --no-deps "agentscope"'
+ if dockerfile.count(original) != 1:
+ raise RuntimeError("Expected one Docker AgentScope install")
+ payloads[wheel.name] = wheel.read_bytes()
+ payloads[_VERIFY_SCRIPT.name] = _VERIFY_SCRIPT.read_bytes()
+ install = (
+ f"COPY {wheel.name} /tmp/{wheel.name}\n"
+ f"COPY {_VERIFY_SCRIPT.name} /tmp/{_VERIFY_SCRIPT.name}\n"
+ f"RUN uv pip install --no-deps --reinstall /tmp/{wheel.name}"
+ f" && python -I /tmp/{_VERIFY_SCRIPT.name} /tmp/{wheel.name}"
+ f" && rm /tmp/{wheel.name} /tmp/{_VERIFY_SCRIPT.name}"
+ )
+ dockerfile = dockerfile.replace(original, install)
+ (context / "Dockerfile").write_text(dockerfile, encoding="utf-8")
+ for name, data in payloads.items():
+ (context / name).write_bytes(data)
+ return context, compute_image_tag(dockerfile, payloads), payloads
+ except BaseException:
+ shutil.rmtree(context)
+ raise
+
+
+async def setup_checkout_gateway(
+ workspace: Any,
+ wheel: Path,
+ setup_gateway: Any,
+) -> None:
+ """Install and verify before delegating to the normal gateway launch."""
+ backend = workspace.get_backend()
+ upload_dir = f"{workspace.workdir}/.checkout-wheel-{uuid4().hex}"
+ wheel_path = f"{upload_dir}/{wheel.name}"
+ verify_path = f"{upload_dir}/{_VERIFY_SCRIPT.name}"
+ commands = workspace._bootstrap_commands()
+ installs = [
+ index
+ for index, command in enumerate(commands)
+ if shlex.split(command)[-1:] == ["agentscope"]
+ ]
+ if len(installs) != 1:
+ raise RuntimeError("Expected one bootstrap AgentScope install")
+ index = installs[0]
+ install_args = shlex.split(commands[index])
+ install_args[-1:] = ["--reinstall", wheel_path]
+ verify = (
+ f"{shlex.quote(workspace._gateway_python)} -I "
+ f"{shlex.quote(verify_path)} {shlex.quote(wheel_path)}"
+ )
+ commands[index] = f"{shlex.join(install_args)} && {verify}"
+ if isinstance(workspace, BubblewrapWorkspace):
+ ready = await workspace._bootstrap_is_ready()
+ else:
+ ready = await backend.file_exists(workspace._gateway_script)
+ if ready:
+ # Preserve resume failures instead of repairing a damaged package.
+ commands = [verify]
+ result = await backend.exec_shell(["mkdir", upload_dir])
+ if not result.ok():
+ raise RuntimeError(
+ f"Could not create checkout upload dir: {upload_dir}",
+ )
+ try:
+ await backend.write_file(wheel_path, wheel.read_bytes())
+ await backend.write_file(verify_path, _VERIFY_SCRIPT.read_bytes())
+ for command in commands:
+ result = await backend.exec_shell(
+ ["sh", "-c", command],
+ timeout=workspace._bootstrap_cmd_timeout,
+ )
+ if not result.ok():
+ raise RuntimeError(
+ f"Checkout bootstrap failed for {command!r}: "
+ f"{result.exit_code}\n"
+ f"{result.stdout.decode(errors='replace')}\n"
+ f"{result.stderr.decode(errors='replace')}",
+ )
+ except BaseException:
+ # Cleanup is best effort here so the original failure stays visible.
+ with suppress(Exception):
+ await backend.exec_shell(["rm", "-rf", upload_dir])
+ raise
+ result = await backend.exec_shell(["rm", "-rf", upload_dir])
+ if not result.ok():
+ raise RuntimeError("Could not remove uploaded checkout artifacts")
+ # Dependencies and wheel are ready; retain normal script upload and launch.
+ with patch.object(workspace, "_bootstrap_commands", return_value=[]):
+ await setup_gateway(workspace)
+
+
+class CheckoutWheelTestCase(IsolatedAsyncioTestCase):
+ """Scope checkout installation patches to a live integration test class."""
+
+ workspace_type: type
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ """Skipped classes never build; all enabled classes share one wheel."""
+ super().setUpClass()
+ if getattr(cls, "workspace_type", None) is None:
+ raise TypeError(
+ f"{cls.__name__} must set workspace_type "
+ f"to the workspace class under test",
+ )
+ wheel = checkout_wheel()
+ stack = ExitStack()
+ cls.addClassCleanup(stack.close)
+ if issubclass(cls.workspace_type, DockerWorkspace):
+ prepare = docker_module.prepare_build_context
+
+ def prepare_checkout(**kwargs: Any) -> Any:
+ """Adapt only live Docker builds."""
+ return wheel_build_context(prepare, wheel, **kwargs)
+
+ stack.enter_context(
+ patch.object(
+ docker_module,
+ "prepare_build_context",
+ prepare_checkout,
+ ),
+ )
+ else:
+ original = cls.workspace_type._setup_mcp_gateway
+
+ async def setup(workspace: Any) -> None:
+ """Install the wheel before the production gateway starts."""
+ await setup_checkout_gateway(workspace, wheel, original)
+
+ stack.enter_context(
+ patch.object(cls.workspace_type, "_setup_mcp_gateway", setup),
+ )
diff --git a/tests/sandbox_test_support/_verify_wheel.py b/tests/sandbox_test_support/_verify_wheel.py
new file mode 100644
index 000000000..2385e78eb
--- /dev/null
+++ b/tests/sandbox_test_support/_verify_wheel.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+"""Verify installed package bytes using only the gateway standard library."""
+
+import sys
+from importlib.metadata import distribution
+from pathlib import Path
+from zipfile import ZipFile
+
+
+def verify_wheel(wheel: str) -> None:
+ """Fail if any installed AgentScope file differs from the wheel."""
+ installed = distribution("agentscope")
+ with ZipFile(wheel) as archive:
+ names = [
+ name
+ for name in archive.namelist()
+ if name.startswith("agentscope/") and not name.endswith("/")
+ ]
+ if not names:
+ raise RuntimeError(f"Wheel contains no AgentScope files: {wheel}")
+ for name in names:
+ path = Path(installed.locate_file(name))
+ if path.read_bytes() != archive.read(name):
+ raise RuntimeError(
+ f"Installed file differs from wheel: {name}",
+ )
+
+
+if __name__ == "__main__":
+ verify_wheel(sys.argv[1])
diff --git a/tests/test_e2e_docker_mcp.py b/tests/test_e2e_docker_mcp.py
index 8b4f05b14..b87349711 100644
--- a/tests/test_e2e_docker_mcp.py
+++ b/tests/test_e2e_docker_mcp.py
@@ -12,6 +12,8 @@ import sys
import tempfile
import unittest
+from sandbox_test_support import CheckoutWheelTestCase
+
from agentscope.workspace import DockerWorkspace
from agentscope.mcp import MCPClient, StdioMCPConfig
@@ -68,9 +70,11 @@ _SKIP_REASON = "Docker daemon not available"
"Docker on Windows CI uses Windows container mode, "
"Linux images unavailable",
)
-class TestDockerPerScopeMCP(unittest.IsolatedAsyncioTestCase):
+class TestDockerPerScopeMCP(CheckoutWheelTestCase):
"""Per-``(agent_id, session_id)`` MCP isolation for DockerWorkspace."""
+ workspace_type = DockerWorkspace
+
def setUp(self) -> None:
self.tmpdir = tempfile.mkdtemp()
diff --git a/tests/test_e2e_e2b_mcp.py b/tests/test_e2e_e2b_mcp.py
index f2816d3e0..44975db44 100644
--- a/tests/test_e2e_e2b_mcp.py
+++ b/tests/test_e2e_e2b_mcp.py
@@ -7,6 +7,8 @@ Requires: ``E2B_API_KEY`` environment variable.
import os
import unittest
+from sandbox_test_support import CheckoutWheelTestCase
+
from agentscope.workspace import E2BWorkspace
from agentscope.mcp import MCPClient, StdioMCPConfig
@@ -41,9 +43,11 @@ _SKIP_REASON = "E2B_API_KEY environment variable is not set"
@unittest.skipUnless(_E2B_API_KEY, _SKIP_REASON)
-class TestE2BPerScopeMCP(unittest.IsolatedAsyncioTestCase):
+class TestE2BPerScopeMCP(CheckoutWheelTestCase):
"""Per-``(agent_id, session_id)`` MCP isolation for E2BWorkspace."""
+ workspace_type = E2BWorkspace
+
@staticmethod
def _make_mcp(name: str) -> MCPClient:
"""Build a real MCP client backed by a minimal stdio MCP server
diff --git a/tests/workspace_applecontainer_test.py b/tests/workspace_applecontainer_test.py
index 8749b2837..1e8263416 100644
--- a/tests/workspace_applecontainer_test.py
+++ b/tests/workspace_applecontainer_test.py
@@ -15,6 +15,8 @@ import unittest
from unittest.async_case import IsolatedAsyncioTestCase
from unittest.mock import AsyncMock, patch
+from sandbox_test_support import CheckoutWheelTestCase
+
from agentscope.mcp import MCPClient, StdioMCPConfig
from agentscope.workspace import AppleContainerBackend, AppleContainerWorkspace
from agentscope.workspace._applecontainer._constants import (
@@ -229,9 +231,11 @@ class TestAppleContainerWorkspaceInternals(IsolatedAsyncioTestCase):
sys.platform == "darwin",
"Apple Container requires macOS",
)
-class TestAppleContainerWorkspaceLifecycle(IsolatedAsyncioTestCase):
+class TestAppleContainerWorkspaceLifecycle(CheckoutWheelTestCase):
"""Lifecycle tests against a real Apple Container."""
+ workspace_type = AppleContainerWorkspace
+
async def test_initialize_and_close(self) -> None:
"""Workspace can be initialized and closed."""
ws = AppleContainerWorkspace()
@@ -321,7 +325,7 @@ if __name__ == "__main__":
sys.platform == "darwin",
"Apple Container requires macOS",
)
-class TestAppleContainerWorkspaceLive(IsolatedAsyncioTestCase):
+class TestAppleContainerWorkspaceLive(CheckoutWheelTestCase):
"""Live integration tests — full bootstrap + gateway lifecycle.
Set ``APPLE_CONTAINER_LIVE=1`` to run. This test pulls an image,
@@ -335,6 +339,8 @@ class TestAppleContainerWorkspaceLive(IsolatedAsyncioTestCase):
5. File read/write roundtrip works inside the container.
"""
+ workspace_type = AppleContainerWorkspace
+
async def test_bootstrap_dependencies(self) -> None:
"""Bootstrap installed ``rg``, ``uv``, and ``python3``."""
ws = AppleContainerWorkspace()
diff --git a/tests/workspace_bubblewrap_test.py b/tests/workspace_bubblewrap_test.py
index b304f04c2..76f5d9762 100644
--- a/tests/workspace_bubblewrap_test.py
+++ b/tests/workspace_bubblewrap_test.py
@@ -24,6 +24,8 @@ import aiofiles
from fastapi.testclient import TestClient
from mcp.types import Tool, ToolAnnotations
+from sandbox_test_support import CheckoutWheelTestCase
+
from agentscope.app.workspace_manager import BubblewrapWorkspaceManager
from agentscope.mcp import MCPClient, StdioMCPConfig
from agentscope.message import Base64Source, DataBlock, UserMsg
@@ -800,9 +802,11 @@ class TestGatewayAuth(unittest.TestCase):
_BWRAP_OK and _BWRAP_INTEGRATION_ENABLED,
_INTEGRATION_SKIP_REASON,
)
-class TestBubblewrapWorkspace(IsolatedAsyncioTestCase):
+class TestBubblewrapWorkspace(CheckoutWheelTestCase):
"""Integration tests against live Bubblewrap."""
+ workspace_type = BubblewrapWorkspace
+
_shared_workdir: tempfile.TemporaryDirectory[str]
_shared_cache: tempfile.TemporaryDirectory[str]
@@ -1056,9 +1060,11 @@ class TestBubblewrapWorkspace(IsolatedAsyncioTestCase):
_BWRAP_OK and _BWRAP_INTEGRATION_ENABLED,
_INTEGRATION_SKIP_REASON,
)
-class TestBubblewrapWorkspaceConcurrency(IsolatedAsyncioTestCase):
+class TestBubblewrapWorkspaceConcurrency(CheckoutWheelTestCase):
"""Concurrency scenarios that need multiple live workspaces."""
+ workspace_type = BubblewrapWorkspace
+
async def asyncSetUp(self) -> None:
"""Create a shared bootstrap cache for live concurrency tests."""
# pylint: disable=consider-using-with
diff --git a/tests/workspace_daytona_test.py b/tests/workspace_daytona_test.py
index 3970ce616..eed3bbe22 100644
--- a/tests/workspace_daytona_test.py
+++ b/tests/workspace_daytona_test.py
@@ -31,6 +31,8 @@ from _daytona_live_utils import (
live_daytona_workspace_id,
)
+from sandbox_test_support import CheckoutWheelTestCase
+
from agentscope.agent import ContextConfig, ReActConfig
from agentscope.app._manager import BackgroundTaskManager, SchedulerManager
from agentscope.app._service import ResourceAccessService, get_toolkit
@@ -1404,9 +1406,11 @@ def _response_text(response: ToolResponse) -> str:
@unittest.skipUnless(DAYTONA_API_KEY, SKIP_REASON)
-class TestDaytonaWorkspaceLive(IsolatedAsyncioTestCase):
+class TestDaytonaWorkspaceLive(CheckoutWheelTestCase):
"""Live Daytona workspace coverage, skipped without credentials."""
+ workspace_type = DaytonaWorkspace
+
@asynccontextmanager
async def _live_workspace(
self,
diff --git a/tests/workspace_docker_test.py b/tests/workspace_docker_test.py
index eec2613b7..a21b833bc 100644
--- a/tests/workspace_docker_test.py
+++ b/tests/workspace_docker_test.py
@@ -36,11 +36,12 @@ import tempfile
import unittest
import uuid
from typing import Any
-from unittest.async_case import IsolatedAsyncioTestCase
from urllib.parse import urlparse
import aiofiles
+from sandbox_test_support import CheckoutWheelTestCase
+
from agentscope.message import (
AssistantMsg,
Base64Source,
@@ -143,9 +144,11 @@ class _LongResultTool(ToolBase):
@unittest.skipUnless(_DOCKER_OK, _SKIP_REASON)
-class TestDockerWorkspaceOffload(IsolatedAsyncioTestCase):
+class TestDockerWorkspaceOffload(CheckoutWheelTestCase):
"""Test cases for DockerWorkspace offload functionality."""
+ workspace_type = DockerWorkspace
+
async def asyncSetUp(self) -> None:
"""Build a fresh workspace bound to a temp host dir.
@@ -460,9 +463,11 @@ class TestDockerWorkspaceOffload(IsolatedAsyncioTestCase):
@unittest.skipUnless(_DOCKER_OK, _SKIP_REASON)
-class TestDockerWorkspaceSkills(IsolatedAsyncioTestCase):
+class TestDockerWorkspaceSkills(CheckoutWheelTestCase):
"""Test cases for DockerWorkspace skill management."""
+ workspace_type = DockerWorkspace
+
async def asyncSetUp(self) -> None:
"""Build separate temp dirs for the workspace and the skill source."""
# pylint: disable=consider-using-with
@@ -660,9 +665,11 @@ class TestDockerWorkspaceSkills(IsolatedAsyncioTestCase):
@unittest.skipUnless(_DOCKER_OK, _SKIP_REASON)
-class TestDockerWorkspaceLifecycle(IsolatedAsyncioTestCase):
+class TestDockerWorkspaceLifecycle(CheckoutWheelTestCase):
"""Test cases for DockerWorkspace lifecycle (init / close / restart)."""
+ workspace_type = DockerWorkspace
+
async def asyncSetUp(self) -> None:
"""Per-test temp workdir; workspace built lazily inside each test."""
# pylint: disable=consider-using-with
diff --git a/tests/workspace_e2b_test.py b/tests/workspace_e2b_test.py
index b28094d26..d721232d9 100644
--- a/tests/workspace_e2b_test.py
+++ b/tests/workspace_e2b_test.py
@@ -4,14 +4,15 @@
The whole module is skipped when the ``E2B_API_KEY`` environment variable is
not set, because every test requires a live E2B cloud sandbox.
"""
+
import os
import unittest
-from unittest.async_case import IsolatedAsyncioTestCase
+
+from sandbox_test_support import CheckoutWheelTestCase
from agentscope.mcp import MCPClient, StdioMCPConfig
from agentscope.workspace import E2BWorkspace
-
# ── E2B availability check ─────────────────────────────────────────
_E2B_API_KEY = os.getenv("E2B_API_KEY", "")
@@ -22,7 +23,7 @@ _SKIP_REASON = "E2B_API_KEY environment variable is not set"
@unittest.skipUnless(_E2B_API_KEY, _SKIP_REASON)
-class TestE2BWorkspaceLifecycle(IsolatedAsyncioTestCase):
+class TestE2BWorkspaceLifecycle(CheckoutWheelTestCase):
"""Test cases for E2BWorkspace lifecycle and MCP integration.
Each test creates a real E2B cloud sandbox and tears it down
@@ -31,6 +32,8 @@ class TestE2BWorkspaceLifecycle(IsolatedAsyncioTestCase):
are unaffected.
"""
+ workspace_type = E2BWorkspace
+
async def asyncSetUp(self) -> None:
"""No shared setup — each test manages its own workspace."""
diff --git a/tests/workspace_opensandbox_test.py b/tests/workspace_opensandbox_test.py
index 5020358d3..74bff7518 100644
--- a/tests/workspace_opensandbox_test.py
+++ b/tests/workspace_opensandbox_test.py
@@ -5,14 +5,15 @@ The whole module is skipped when the ``OPENSANDBOX_DOMAIN`` environment
variable is not set, because every test requires a live OpenSandbox
service.
"""
+
import os
import unittest
-from unittest.async_case import IsolatedAsyncioTestCase
+
+from sandbox_test_support import CheckoutWheelTestCase
from agentscope.mcp import MCPClient, StdioMCPConfig
from agentscope.workspace import OpenSandboxWorkspace
-
# ── OpenSandbox availability check ─────────────────────────────────
_DOMAIN = os.getenv("OPENSANDBOX_DOMAIN", "")
@@ -24,7 +25,7 @@ _SKIP_REASON = "OPENSANDBOX_DOMAIN environment variable is not set"
@unittest.skipUnless(_DOMAIN, _SKIP_REASON)
-class TestOpenSandboxWorkspaceLifecycle(IsolatedAsyncioTestCase):
+class TestOpenSandboxWorkspaceLifecycle(CheckoutWheelTestCase):
"""Test cases for OpenSandboxWorkspace lifecycle and MCP integration.
Each test creates a real OpenSandbox sandbox and tears it down
@@ -33,6 +34,8 @@ class TestOpenSandboxWorkspaceLifecycle(IsolatedAsyncioTestCase):
access are unaffected.
"""
+ workspace_type = OpenSandboxWorkspace
+
async def test_initialize_and_list_mcps(self) -> None:
"""``initialize`` starts the sandbox and ``list_mcps`` enumerates MCPs.