Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

test: move create-payload tests to their request-boundary owners (#1915)

devin-ai-integration[bot]c05a6421d76a
diff --git a/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
index 7964b0361..823a3abaf 100644
--- a/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
+++ b/packages/js-sdk/tests/sandbox/lifecyclePayload.test.ts
@@ -1,6 +1,6 @@
-import { assert, expect, test, vi } from 'vitest'
+import { assert, test, vi } from 'vitest'
-import { InvalidArgumentError, Sandbox } from '../../src'
+import { Sandbox } from '../../src'
import {
corsHttpServerCmd,
isDebug,
@@ -29,41 +29,6 @@ function withRequestSource(url: string): string {
return source ? `${url}?source=${encodeURIComponent(source)}` : url
}
-test.skipIf(isDebug)(
- 'filesystem-only auto-pause cannot be combined with auto-resume',
- async () => {
- // A filesystem-only auto-pause snapshot can only be resumed explicitly, so
- // keepMemory:false with autoResume is rejected client-side.
- await expect(
- Sandbox.create(template, {
- timeoutMs: 3_000,
- lifecycle: {
- onTimeout: { action: 'pause', keepMemory: false },
- autoResume: true,
- },
- })
- ).rejects.toThrowError(InvalidArgumentError)
- }
-)
-
-test.skipIf(isDebug)(
- 'keepMemory is not allowed when onTimeout action is kill',
- async () => {
- // The discriminated union forbids keepMemory on `action: 'kill'` at compile
- // time (asserted by @ts-expect-error). The runtime guard below additionally
- // rejects it for untyped (JS) callers that bypass the type.
- await expect(
- Sandbox.create(template, {
- timeoutMs: 3_000,
- lifecycle: {
- // @ts-expect-error keepMemory is not allowed with action: 'kill'
- onTimeout: { action: 'kill', keepMemory: false },
- },
- })
- ).rejects.toThrowError(InvalidArgumentError)
- }
-)
-
test.skipIf(isDebug)(
'auto-pause without auto-resume requires connect to wake',
async () => {
diff --git a/packages/python-sdk/tests/async/sandbox_async/test_create.py b/packages/python-sdk/tests/async/sandbox_async/test_create.py
index 476d41680..8ab73e804 100644
--- a/packages/python-sdk/tests/async/sandbox_async/test_create.py
+++ b/packages/python-sdk/tests/async/sandbox_async/test_create.py
@@ -5,14 +5,7 @@ from uuid import uuid4
import httpx
import pytest
-from e2b import AsyncSandbox, SandboxException, SandboxQuery, SandboxState, Secret
-from e2b.api.client.models import (
- NewSandboxV2,
- SandboxAutoResumeConfig,
-)
-from e2b.api.client.types import UNSET
-from e2b.exceptions import InvalidArgumentException
-from e2b.sandbox.sandbox_api import build_iam_config
+from e2b import AsyncSandbox, SandboxException, SandboxQuery, SandboxState
async def wait_for_state(
@@ -101,136 +94,6 @@ async def test_mcp_gateway_start_failure_kills_created_sandbox(template):
await AsyncSandbox.kill(sandbox.sandbox_id)
-def test_create_payload_serializes_auto_resume_enabled():
- body = NewSandboxV2(
- template_id="template-id",
- auto_pause=True,
- auto_resume=SandboxAutoResumeConfig(enabled=True),
- )
-
- assert body.to_dict()["autoPause"] is True
- assert body.to_dict()["autoResume"] == {"enabled": True}
-
-
-def test_create_payload_deserializes_auto_resume_enabled():
- body = NewSandboxV2.from_dict(
- {
- "templateID": "template-id",
- "autoPause": False,
- "autoResume": {"enabled": False},
- }
- )
-
- assert isinstance(body.auto_resume, SandboxAutoResumeConfig)
- assert body.auto_resume.to_dict() == {"enabled": False}
-
-
-def test_create_payload_serializes_iam_tokens():
- iam = build_iam_config(
- {
- "tokens": {
- "aws": {"audience": "sts.amazonaws.com", "token_type": "JWT-SVID"},
- },
- }
- )
- assert iam is not None
-
- body = NewSandboxV2(template_id="template-id", iam=iam)
-
- assert body.to_dict()["iam"] == {
- "tokens": {
- "aws": {"audience": "sts.amazonaws.com", "tokenType": "JWT-SVID"},
- },
- }
-
-
-def test_create_payload_serializes_secret_iam_token():
- iam = build_iam_config(
- {
- "tokens": {
- "aws": Secret.iam_token(
- audience="sts.amazonaws.com", token_type="JWT-SVID"
- ),
- },
- }
- )
- assert iam is not None
-
- body = NewSandboxV2(template_id="template-id", iam=iam)
-
- assert body.to_dict()["iam"] == {
- "tokens": {
- "aws": {"audience": "sts.amazonaws.com", "tokenType": "JWT-SVID"},
- },
- }
-
-
-def test_create_payload_omits_iam_when_not_provided_or_empty():
- assert build_iam_config(None) is None
- assert build_iam_config({}) is None
- assert build_iam_config({"tokens": {}}) is None
-
- body = NewSandboxV2(template_id="template-id", iam=UNSET)
-
- assert "iam" not in body.to_dict()
-
-
-def test_create_payload_rejects_malformed_iam_tokens():
- # The wire-format casing a user might copy from the JS example or a
- # serialized payload must fail with an actionable error, not a KeyError.
- with pytest.raises(InvalidArgumentException, match="token_type"):
- build_iam_config(
- cast(
- Any,
- {
- "tokens": {
- "aws": {
- "audience": "sts.amazonaws.com",
- "tokenType": "JWT-SVID",
- },
- },
- },
- )
- )
-
- with pytest.raises(InvalidArgumentException):
- build_iam_config(cast(Any, {"tokens": {"aws": None}}))
-
- # Non-string values must be rejected too, not serialized as null.
- with pytest.raises(InvalidArgumentException):
- build_iam_config(
- cast(Any, {"tokens": {"aws": {"audience": None, "token_type": "JWT-SVID"}}})
- )
-
-
-async def test_filesystem_only_auto_pause_rejects_auto_resume():
- # A filesystem-only auto-pause snapshot can only be resumed explicitly, so
- # combining keep_memory=False with auto_resume is rejected client-side.
- with pytest.raises(InvalidArgumentException):
- await AsyncSandbox.create(
- timeout=3,
- lifecycle={
- "on_timeout": {"action": "pause", "keep_memory": False},
- "auto_resume": True,
- },
- )
-
-
-async def test_keep_memory_not_allowed_with_kill():
- # The discriminated union forbids keep_memory on action="kill" at type-check
- # time; the runtime guard rejects it for callers that bypass the type
- # (cast(Any, ...) feeds the deliberately type-invalid input).
- with pytest.raises(InvalidArgumentException):
- await AsyncSandbox.create(
- timeout=3,
- lifecycle=cast(
- Any, {"on_timeout": {"action": "kill", "keep_memory": False}}
- ),
- )
-
-
@pytest.mark.skip_debug()
async def test_invalid_on_timeout_type_does_not_crash(async_sandbox_factory):
# An untyped/invalid on_timeout (e.g. None) must not crash create; it falls
diff --git a/packages/python-sdk/tests/shared/sandbox/test_iam_request.py b/packages/python-sdk/tests/shared/sandbox/test_iam_request.py
new file mode 100644
index 000000000..936c8f6b8
--- /dev/null
+++ b/packages/python-sdk/tests/shared/sandbox/test_iam_request.py
@@ -0,0 +1,127 @@
+from types import SimpleNamespace
+from typing import Any, Dict, cast
+from unittest.mock import AsyncMock, Mock
+
+import pytest
+
+from e2b import AsyncSandbox, Sandbox, Secret
+from e2b.api.client.api.sandboxes import post_v2_sandboxes
+from e2b.api.client.models import Sandbox as SandboxModel
+from e2b.exceptions import InvalidArgumentException
+
+AWS_TOKEN_BODY = {
+ "tokens": {
+ "aws": {"audience": "sts.amazonaws.com", "tokenType": "JWT-SVID"},
+ },
+}
+
+
+def _created_sandbox():
+ return SimpleNamespace(
+ status_code=200,
+ parsed=SandboxModel(
+ client_id="client-id",
+ envd_version="0.2.4",
+ sandbox_id="sbx-test",
+ template_id="template-id",
+ ),
+ )
+
+
+def _sync_create_body(monkeypatch, api_key: str, iam) -> Dict[str, Any]:
+ request = Mock(return_value=_created_sandbox())
+ monkeypatch.setattr(post_v2_sandboxes, "sync_detailed", request)
+
+ Sandbox.create(api_key=api_key, iam=iam)
+
+ return request.call_args.kwargs["body"].to_dict()
+
+
+IAM_TOKENS = [
+ pytest.param(
+ {"audience": "sts.amazonaws.com", "token_type": "JWT-SVID"}, id="dict"
+ ),
+ pytest.param(
+ Secret.iam_token(audience="sts.amazonaws.com", token_type="JWT-SVID"),
+ id="secret-iam-token",
+ ),
+]
+
+
[email protected]("token", IAM_TOKENS)
+def test_create_sends_iam_tokens(monkeypatch, test_api_key, token):
+ body = _sync_create_body(monkeypatch, test_api_key, {"tokens": {"aws": token}})
+
+ assert body["iam"] == AWS_TOKEN_BODY
+
+
[email protected]("token", IAM_TOKENS)
+async def test_async_create_sends_iam_tokens(monkeypatch, test_api_key, token):
+ request = AsyncMock(return_value=_created_sandbox())
+ monkeypatch.setattr(post_v2_sandboxes, "asyncio_detailed", request)
+
+ await AsyncSandbox.create(api_key=test_api_key, iam={"tokens": {"aws": token}})
+
+ assert request.call_args.kwargs["body"].to_dict()["iam"] == AWS_TOKEN_BODY
+
+
+EMPTY_IAM_CONFIGS = [
+ pytest.param(None, id="not-provided"),
+ pytest.param({}, id="empty"),
+ pytest.param({"tokens": {}}, id="empty-tokens"),
+]
+
+MALFORMED_IAM_TOKENS = [
+ # The wire-format casing a user might copy from the JS example or a
+ # serialized payload must fail with an actionable error, not a KeyError.
+ pytest.param(
+ {"audience": "sts.amazonaws.com", "tokenType": "JWT-SVID"},
+ id="camel-case-token-type",
+ ),
+ pytest.param(None, id="none"),
+ # Non-string values must be rejected too, not serialized as null.
+ pytest.param({"audience": None, "token_type": "JWT-SVID"}, id="none-audience"),
+]
+
+
[email protected]("iam", EMPTY_IAM_CONFIGS)
+def test_create_omits_an_empty_iam_config(monkeypatch, test_api_key, iam):
+ body = _sync_create_body(monkeypatch, test_api_key, iam)
+
+ assert "iam" not in body
+
+
[email protected]("iam", EMPTY_IAM_CONFIGS)
+async def test_async_create_omits_an_empty_iam_config(monkeypatch, test_api_key, iam):
+ request = AsyncMock(return_value=_created_sandbox())
+ monkeypatch.setattr(post_v2_sandboxes, "asyncio_detailed", request)
+
+ await AsyncSandbox.create(api_key=test_api_key, iam=iam)
+
+ assert "iam" not in request.call_args.kwargs["body"].to_dict()
+
+
[email protected]("token", MALFORMED_IAM_TOKENS)
+def test_create_rejects_a_malformed_iam_token(monkeypatch, test_api_key, token):
+ request = Mock(return_value=_created_sandbox())
+ monkeypatch.setattr(post_v2_sandboxes, "sync_detailed", request)
+
+ with pytest.raises(InvalidArgumentException, match="token_type"):
+ Sandbox.create(api_key=test_api_key, iam=cast(Any, {"tokens": {"aws": token}}))
+
+ request.assert_not_called()
+
+
[email protected]("token", MALFORMED_IAM_TOKENS)
+async def test_async_create_rejects_a_malformed_iam_token(
+ monkeypatch, test_api_key, token
+):
+ request = AsyncMock(return_value=_created_sandbox())
+ monkeypatch.setattr(post_v2_sandboxes, "asyncio_detailed", request)
+
+ with pytest.raises(InvalidArgumentException, match="token_type"):
+ await AsyncSandbox.create(
+ api_key=test_api_key, iam=cast(Any, {"tokens": {"aws": token}})
+ )
+
+ request.assert_not_called()
diff --git a/packages/python-sdk/tests/shared/sandbox/test_lifecycle_request.py b/packages/python-sdk/tests/shared/sandbox/test_lifecycle_request.py
index 84f74949e..d208edcaf 100644
--- a/packages/python-sdk/tests/shared/sandbox/test_lifecycle_request.py
+++ b/packages/python-sdk/tests/shared/sandbox/test_lifecycle_request.py
@@ -147,6 +147,45 @@ async def test_async_create_rejects_auto_resume_without_a_timeout_action(
await AsyncSandbox.create(api_key=test_api_key, lifecycle=lifecycle)
+INVALID_LIFECYCLES = [
+ # A filesystem-only auto-pause snapshot can only be resumed explicitly.
+ pytest.param(
+ {"on_timeout": {"action": "pause", "keep_memory": False}, "auto_resume": True},
+ id="filesystem-only-pause-with-auto-resume",
+ ),
+ # The discriminated union forbids this at type-check time; the runtime
+ # guard covers callers that bypass the type.
+ pytest.param(
+ cast(Any, {"on_timeout": {"action": "kill", "keep_memory": False}}),
+ id="keep-memory-with-kill",
+ ),
+]
+
+
[email protected]("lifecycle", INVALID_LIFECYCLES)
+def test_create_rejects_an_invalid_lifecycle(monkeypatch, test_api_key, lifecycle):
+ request = Mock(return_value=_created_sandbox())
+ monkeypatch.setattr(post_v2_sandboxes, "sync_detailed", request)
+
+ with pytest.raises(InvalidArgumentException):
+ Sandbox.create(api_key=test_api_key, lifecycle=lifecycle)
+
+ request.assert_not_called()
+
+
[email protected]("lifecycle", INVALID_LIFECYCLES)
+async def test_async_create_rejects_an_invalid_lifecycle(
+ monkeypatch, test_api_key, lifecycle
+):
+ request = AsyncMock(return_value=_created_sandbox())
+ monkeypatch.setattr(post_v2_sandboxes, "asyncio_detailed", request)
+
+ with pytest.raises(InvalidArgumentException):
+ await AsyncSandbox.create(api_key=test_api_key, lifecycle=lifecycle)
+
+ request.assert_not_called()
+
+
# `None` expects autoResume to be absent from the payload: an unconfigured
# preference is not an explicit opt-out, so the API keeps ownership of the
# default instead of receiving {"enabled": False}.
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/test_create.py b/packages/python-sdk/tests/sync/sandbox_sync/test_create.py
index 56bb7300f..36843b0e5 100644
--- a/packages/python-sdk/tests/sync/sandbox_sync/test_create.py
+++ b/packages/python-sdk/tests/sync/sandbox_sync/test_create.py
@@ -5,14 +5,8 @@ from uuid import uuid4
import httpx
import pytest
-from e2b import Sandbox, SandboxException, SandboxState, Secret
-from e2b.api.client.models import (
- NewSandboxV2,
- SandboxAutoResumeConfig,
-)
-from e2b.api.client.types import UNSET
-from e2b.exceptions import InvalidArgumentException
-from e2b.sandbox.sandbox_api import SandboxQuery, build_iam_config
+from e2b import Sandbox, SandboxException, SandboxState
+from e2b.sandbox.sandbox_api import SandboxQuery
def wait_for_state(sandbox: Sandbox, state: SandboxState, timeout: float = 30) -> None:
@@ -97,136 +91,6 @@ def test_mcp_gateway_start_failure_kills_created_sandbox(template):
Sandbox.kill(sandbox.sandbox_id)
-def test_create_payload_serializes_auto_resume_enabled():
- body = NewSandboxV2(
- template_id="template-id",
- auto_pause=True,
- auto_resume=SandboxAutoResumeConfig(enabled=True),
- )
-
- assert body.to_dict()["autoPause"] is True
- assert body.to_dict()["autoResume"] == {"enabled": True}
-
-
-def test_create_payload_deserializes_auto_resume_enabled():
- body = NewSandboxV2.from_dict(
- {
- "templateID": "template-id",
- "autoPause": False,
- "autoResume": {"enabled": False},
- }
- )
-
- assert isinstance(body.auto_resume, SandboxAutoResumeConfig)
- assert body.auto_resume.to_dict() == {"enabled": False}
-
-
-def test_create_payload_serializes_iam_tokens():
- iam = build_iam_config(
- {
- "tokens": {
- "aws": {"audience": "sts.amazonaws.com", "token_type": "JWT-SVID"},
- },
- }
- )
- assert iam is not None
-
- body = NewSandboxV2(template_id="template-id", iam=iam)
-
- assert body.to_dict()["iam"] == {
- "tokens": {
- "aws": {"audience": "sts.amazonaws.com", "tokenType": "JWT-SVID"},
- },
- }
-
-
-def test_create_payload_serializes_secret_iam_token():
- iam = build_iam_config(
- {
- "tokens": {
- "aws": Secret.iam_token(
- audience="sts.amazonaws.com", token_type="JWT-SVID"
- ),
- },
- }
- )
- assert iam is not None
-
- body = NewSandboxV2(template_id="template-id", iam=iam)
-
- assert body.to_dict()["iam"] == {
- "tokens": {
- "aws": {"audience": "sts.amazonaws.com", "tokenType": "JWT-SVID"},
- },
- }
-
-
-def test_create_payload_omits_iam_when_not_provided_or_empty():
- assert build_iam_config(None) is None
- assert build_iam_config({}) is None
- assert build_iam_config({"tokens": {}}) is None
-
- body = NewSandboxV2(template_id="template-id", iam=UNSET)
-
- assert "iam" not in body.to_dict()
-
-
-def test_create_payload_rejects_malformed_iam_tokens():
- # The wire-format casing a user might copy from the JS example or a
- # serialized payload must fail with an actionable error, not a KeyError.
- with pytest.raises(InvalidArgumentException, match="token_type"):
- build_iam_config(
- cast(
- Any,
- {
- "tokens": {
- "aws": {
- "audience": "sts.amazonaws.com",
- "tokenType": "JWT-SVID",
- },
- },
- },
- )
- )
-
- with pytest.raises(InvalidArgumentException):
- build_iam_config(cast(Any, {"tokens": {"aws": None}}))
-
- # Non-string values must be rejected too, not serialized as null.
- with pytest.raises(InvalidArgumentException):
- build_iam_config(
- cast(Any, {"tokens": {"aws": {"audience": None, "token_type": "JWT-SVID"}}})
- )
-
-
-def test_filesystem_only_auto_pause_rejects_auto_resume():
- # A filesystem-only auto-pause snapshot can only be resumed explicitly, so
- # combining keep_memory=False with auto_resume is rejected client-side.
- with pytest.raises(InvalidArgumentException):
- Sandbox.create(
- timeout=3,
- lifecycle={
- "on_timeout": {"action": "pause", "keep_memory": False},
- "auto_resume": True,
- },
- )
-
-
-def test_keep_memory_not_allowed_with_kill():
- # The discriminated union forbids keep_memory on action="kill" at type-check
- # time; the runtime guard rejects it for callers that bypass the type
- # (cast(Any, ...) feeds the deliberately type-invalid input).
- with pytest.raises(InvalidArgumentException):
- Sandbox.create(
- timeout=3,
- lifecycle=cast(
- Any, {"on_timeout": {"action": "kill", "keep_memory": False}}
- ),
- )
-
-
@pytest.mark.skip_debug()
def test_invalid_on_timeout_type_does_not_crash(sandbox_factory):
# An untyped/invalid on_timeout (e.g. None) must not crash create; it falls