286 lines
7.6 KiB
Python
Raw Permalink Normal View History

import asyncio
import os
import random
import string
from typing import Callable, Dict, Optional
import pytest
2024-07-09 00:20:46 -07:00
import pytest_asyncio
from e2b import (
AsyncCommandHandle,
AsyncSandbox,
AsyncTemplate,
AsyncVolume,
CommandExitException,
CommandHandle,
LogEntry,
Sandbox,
Template,
TemplateClass,
Volume,
)
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
if rep.when == "call":
item._test_failed = rep.failed
@pytest.fixture()
def sandbox_test_id():
return f"test_{_generate_random_string()}"
@pytest.fixture()
def template():
return "base"
@pytest.fixture()
Ensure that httpx transport is reused across calls by default (#997) This takes some shortcuts in order to keep backwards compatibility. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Reuses a singleton httpx transport/client across the SDK, introduces a generic retry decorator for connect calls, and refactors code/tests to use the shared clients and fixtures. > > - **SDK (transport/client reuse)** > - Add global `limits` (configurable via `E2B_*` env vars) and switch `ApiClient` to accept `transport` instead of `limits`. > - Introduce `e2b.api.client_async/client_sync` with `get_transport()` (singleton) and `get_api_client()`; update `Sandbox`/`AsyncSandbox`, paginators, and sandbox APIs to use them. > - Remove per-class `_limits` from `SandboxBase`/`TemplateBase`; merge extra headers correctly; pass `E2b-Sandbox-Port` as string. > - Template build flows (sync/async) now reuse the API client's underlying httpx client for file uploads. > - **Connect client** (`e2b_connect/client.py`) > - Add `_retry` decorator and apply to unary/server-stream methods; simplify reconnection logic; minor typing/headers cleanups. > - **Tests** > - Add retry unit tests; introduce `sandbox_factory`/`async_sandbox_factory` and a session `event_loop`; refactor tests to use factories and shared transports; adjust tar archive expectations. > - **Misc** > - Add `.editorconfig`, CLI `.envrc`, and changeset entries. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 1d359231b63dc21b6c8d797886f7d6a77c9ed6b7. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Tomas Valenta <valenta.and.thomas@gmail.com> Co-authored-by: Mish <10400064+mishushakov@users.noreply.github.com>
2025-11-14 16:48:29 -08:00
def sandbox_factory(request, template, sandbox_test_id):
def factory(*, template_name: str = template, **kwargs):
metadata = kwargs.setdefault("metadata", dict())
metadata.setdefault("sandbox_test_id", sandbox_test_id)
sandbox = Sandbox.create(template_name, **kwargs)
def finalizer():
if getattr(request.node, "_test_failed", False):
print(f"\n[TEST FAILED] Sandbox ID: {sandbox.sandbox_id}")
sandbox.kill()
request.addfinalizer(finalizer)
Ensure that httpx transport is reused across calls by default (#997) This takes some shortcuts in order to keep backwards compatibility. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Reuses a singleton httpx transport/client across the SDK, introduces a generic retry decorator for connect calls, and refactors code/tests to use the shared clients and fixtures. > > - **SDK (transport/client reuse)** > - Add global `limits` (configurable via `E2B_*` env vars) and switch `ApiClient` to accept `transport` instead of `limits`. > - Introduce `e2b.api.client_async/client_sync` with `get_transport()` (singleton) and `get_api_client()`; update `Sandbox`/`AsyncSandbox`, paginators, and sandbox APIs to use them. > - Remove per-class `_limits` from `SandboxBase`/`TemplateBase`; merge extra headers correctly; pass `E2b-Sandbox-Port` as string. > - Template build flows (sync/async) now reuse the API client's underlying httpx client for file uploads. > - **Connect client** (`e2b_connect/client.py`) > - Add `_retry` decorator and apply to unary/server-stream methods; simplify reconnection logic; minor typing/headers cleanups. > - **Tests** > - Add retry unit tests; introduce `sandbox_factory`/`async_sandbox_factory` and a session `event_loop`; refactor tests to use factories and shared transports; adjust tar archive expectations. > - **Misc** > - Add `.editorconfig`, CLI `.envrc`, and changeset entries. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 1d359231b63dc21b6c8d797886f7d6a77c9ed6b7. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Tomas Valenta <valenta.and.thomas@gmail.com> Co-authored-by: Mish <10400064+mishushakov@users.noreply.github.com>
2025-11-14 16:48:29 -08:00
return sandbox
return factory
Ensure that httpx transport is reused across calls by default (#997) This takes some shortcuts in order to keep backwards compatibility. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Reuses a singleton httpx transport/client across the SDK, introduces a generic retry decorator for connect calls, and refactors code/tests to use the shared clients and fixtures. > > - **SDK (transport/client reuse)** > - Add global `limits` (configurable via `E2B_*` env vars) and switch `ApiClient` to accept `transport` instead of `limits`. > - Introduce `e2b.api.client_async/client_sync` with `get_transport()` (singleton) and `get_api_client()`; update `Sandbox`/`AsyncSandbox`, paginators, and sandbox APIs to use them. > - Remove per-class `_limits` from `SandboxBase`/`TemplateBase`; merge extra headers correctly; pass `E2b-Sandbox-Port` as string. > - Template build flows (sync/async) now reuse the API client's underlying httpx client for file uploads. > - **Connect client** (`e2b_connect/client.py`) > - Add `_retry` decorator and apply to unary/server-stream methods; simplify reconnection logic; minor typing/headers cleanups. > - **Tests** > - Add retry unit tests; introduce `sandbox_factory`/`async_sandbox_factory` and a session `event_loop`; refactor tests to use factories and shared transports; adjust tar archive expectations. > - **Misc** > - Add `.editorconfig`, CLI `.envrc`, and changeset entries. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 1d359231b63dc21b6c8d797886f7d6a77c9ed6b7. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Tomas Valenta <valenta.and.thomas@gmail.com> Co-authored-by: Mish <10400064+mishushakov@users.noreply.github.com>
2025-11-14 16:48:29 -08:00
@pytest.fixture()
def sandbox(sandbox_factory):
return sandbox_factory()
# override the event loop so it never closes
# this helps us with the global-scoped async http transport
@pytest.fixture(scope="session")
def event_loop():
try:
Ensure that httpx transport is reused across calls by default (#997) This takes some shortcuts in order to keep backwards compatibility. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Reuses a singleton httpx transport/client across the SDK, introduces a generic retry decorator for connect calls, and refactors code/tests to use the shared clients and fixtures. > > - **SDK (transport/client reuse)** > - Add global `limits` (configurable via `E2B_*` env vars) and switch `ApiClient` to accept `transport` instead of `limits`. > - Introduce `e2b.api.client_async/client_sync` with `get_transport()` (singleton) and `get_api_client()`; update `Sandbox`/`AsyncSandbox`, paginators, and sandbox APIs to use them. > - Remove per-class `_limits` from `SandboxBase`/`TemplateBase`; merge extra headers correctly; pass `E2b-Sandbox-Port` as string. > - Template build flows (sync/async) now reuse the API client's underlying httpx client for file uploads. > - **Connect client** (`e2b_connect/client.py`) > - Add `_retry` decorator and apply to unary/server-stream methods; simplify reconnection logic; minor typing/headers cleanups. > - **Tests** > - Add retry unit tests; introduce `sandbox_factory`/`async_sandbox_factory` and a session `event_loop`; refactor tests to use factories and shared transports; adjust tar archive expectations. > - **Misc** > - Add `.editorconfig`, CLI `.envrc`, and changeset entries. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 1d359231b63dc21b6c8d797886f7d6a77c9ed6b7. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Tomas Valenta <valenta.and.thomas@gmail.com> Co-authored-by: Mish <10400064+mishushakov@users.noreply.github.com>
2025-11-14 16:48:29 -08:00
loop = asyncio.get_running_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
yield loop
loop.close()
@pytest.fixture
def async_sandbox_factory(request, template, sandbox_test_id, event_loop):
async def factory(*, template_name: str = template, **kwargs):
metadata = kwargs.setdefault("metadata", dict())
metadata.setdefault("sandbox_test_id", sandbox_test_id)
sandbox = await AsyncSandbox.create(template_name, **kwargs)
def finalizer():
if getattr(request.node, "_test_failed", False):
print(f"\n[TEST FAILED] Sandbox ID: {sandbox.sandbox_id}")
Ensure that httpx transport is reused across calls by default (#997) This takes some shortcuts in order to keep backwards compatibility. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Reuses a singleton httpx transport/client across the SDK, introduces a generic retry decorator for connect calls, and refactors code/tests to use the shared clients and fixtures. > > - **SDK (transport/client reuse)** > - Add global `limits` (configurable via `E2B_*` env vars) and switch `ApiClient` to accept `transport` instead of `limits`. > - Introduce `e2b.api.client_async/client_sync` with `get_transport()` (singleton) and `get_api_client()`; update `Sandbox`/`AsyncSandbox`, paginators, and sandbox APIs to use them. > - Remove per-class `_limits` from `SandboxBase`/`TemplateBase`; merge extra headers correctly; pass `E2b-Sandbox-Port` as string. > - Template build flows (sync/async) now reuse the API client's underlying httpx client for file uploads. > - **Connect client** (`e2b_connect/client.py`) > - Add `_retry` decorator and apply to unary/server-stream methods; simplify reconnection logic; minor typing/headers cleanups. > - **Tests** > - Add retry unit tests; introduce `sandbox_factory`/`async_sandbox_factory` and a session `event_loop`; refactor tests to use factories and shared transports; adjust tar archive expectations. > - **Misc** > - Add `.editorconfig`, CLI `.envrc`, and changeset entries. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 1d359231b63dc21b6c8d797886f7d6a77c9ed6b7. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Tomas Valenta <valenta.and.thomas@gmail.com> Co-authored-by: Mish <10400064+mishushakov@users.noreply.github.com>
2025-11-14 16:48:29 -08:00
async def _kill():
await sandbox.kill()
event_loop.run_until_complete(_kill())
request.addfinalizer(finalizer)
Ensure that httpx transport is reused across calls by default (#997) This takes some shortcuts in order to keep backwards compatibility. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > Reuses a singleton httpx transport/client across the SDK, introduces a generic retry decorator for connect calls, and refactors code/tests to use the shared clients and fixtures. > > - **SDK (transport/client reuse)** > - Add global `limits` (configurable via `E2B_*` env vars) and switch `ApiClient` to accept `transport` instead of `limits`. > - Introduce `e2b.api.client_async/client_sync` with `get_transport()` (singleton) and `get_api_client()`; update `Sandbox`/`AsyncSandbox`, paginators, and sandbox APIs to use them. > - Remove per-class `_limits` from `SandboxBase`/`TemplateBase`; merge extra headers correctly; pass `E2b-Sandbox-Port` as string. > - Template build flows (sync/async) now reuse the API client's underlying httpx client for file uploads. > - **Connect client** (`e2b_connect/client.py`) > - Add `_retry` decorator and apply to unary/server-stream methods; simplify reconnection logic; minor typing/headers cleanups. > - **Tests** > - Add retry unit tests; introduce `sandbox_factory`/`async_sandbox_factory` and a session `event_loop`; refactor tests to use factories and shared transports; adjust tar archive expectations. > - **Misc** > - Add `.editorconfig`, CLI `.envrc`, and changeset entries. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 1d359231b63dc21b6c8d797886f7d6a77c9ed6b7. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Tomas Valenta <valenta.and.thomas@gmail.com> Co-authored-by: Mish <10400064+mishushakov@users.noreply.github.com>
2025-11-14 16:48:29 -08:00
return sandbox
return factory
@pytest.fixture
async def async_sandbox(async_sandbox_factory):
return await async_sandbox_factory()
@pytest.fixture
def build():
def _build(
template: TemplateClass,
name: Optional[str] = None,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
):
build_name = name or f"e2b-test-{_generate_random_string()}"
build_info: Dict[str, Optional[str]] = {"template_id": None, "build_id": None}
def capture_logs(log: LogEntry):
import re
if "Template created with ID:" in log.message:
match = re.search(
r"Template created with ID: ([^,]+), Build ID: (.+)", log.message
)
if match:
build_info["template_id"] = match.group(1)
build_info["build_id"] = match.group(2)
if on_build_logs:
on_build_logs(log)
try:
return Template.build(
template,
build_name,
cpu_count=1,
memory_mb=1024,
skip_cache=skip_cache,
on_build_logs=capture_logs,
)
except Exception as e:
print(
f"\n[BUILD FAILED] name={build_name}, "
f"template_id={build_info['template_id']}, "
f"build_id={build_info['build_id']}, error={e}"
)
raise
return _build
@pytest_asyncio.fixture
def async_build():
async def _async_build(
template: TemplateClass,
name: Optional[str] = None,
skip_cache: bool = False,
on_build_logs: Optional[Callable[[LogEntry], None]] = None,
):
build_name = name or f"e2b-test-{_generate_random_string()}"
build_info: Dict[str, Optional[str]] = {"template_id": None, "build_id": None}
def capture_logs(log: LogEntry):
import re
if "Template created with ID:" in log.message:
match = re.search(
r"Template created with ID: ([^,]+), Build ID: (.+)", log.message
)
if match:
build_info["template_id"] = match.group(1)
build_info["build_id"] = match.group(2)
if on_build_logs:
on_build_logs(log)
try:
return await AsyncTemplate.build(
template,
build_name,
cpu_count=1,
memory_mb=1024,
skip_cache=skip_cache,
on_build_logs=capture_logs,
)
except Exception as e:
print(
f"\n[BUILD FAILED] name={build_name}, "
f"template_id={build_info['template_id']}, "
f"build_id={build_info['build_id']}, error={e}"
)
raise
return _async_build
2024-06-25 20:12:44 -07:00
@pytest.fixture
def debug():
return os.getenv("E2B_DEBUG") is not None
@pytest.fixture(autouse=True)
def skip_by_debug(request, debug):
if request.node.get_closest_marker("skip_debug"):
if debug:
Fix Python SDK type issues with ty type checker (#1122) ## Summary - Resolved 43 type diagnostics reported by ty (Astral's Python type checker) - Fixed Self type issues on class singletons - Added explicit type annotations for shadowed attributes - Replaced None with UNSET for auto-generated API parameters - Fixed method signature alignment for protocol matching - Added targeted type: ignore suppressions for pattern-based limitations All checks pass: ty check, ruff format, ruff check. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Mostly typing/CI changes, but some adjustments affect sandbox connect/pause overload dispatch and API response/parameter handling (`UNSET` vs `None`), which could alter edge-case runtime behavior. > > **Overview** > Fixes Python SDK static typing issues for Astral’s `ty` checker and wires typechecking into CI. > > Adds a new `Typecheck` GitHub Action plus workspace `typecheck` scripts (TS packages via `tsc`, Python SDK via `make typecheck` running `ty`), and publishes a patch changeset for `@e2b/python-sdk`. > > Across the Python SDK, adjusts type annotations and overloads (e.g., `Self`/singleton typing, `connect` overloads, optional `user`/token/domain handling), tightens API model parsing with `cast`/`Optional` checks and `UNSET` usage, and adds a few targeted `ty` ignore comments in tests/protocols to silence checker limitations. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit f66402847c40cee7e44e1aaa7caa97e271ba9978. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com> Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
2026-02-12 17:23:39 +01:00
pytest.skip(
"skipped because E2B_DEBUG is set" # ty: ignore[too-many-positional-arguments]
) # ty: ignore[invalid-argument-type]
class Helpers:
@staticmethod
def catch_cmd_exit_error_in_background(cmd: AsyncCommandHandle):
disabled = False
async def wait_for_exit():
try:
await cmd.wait()
except CommandExitException as e:
if not disabled:
assert False, (
f"command failed with exit code {e.exit_code}: {e.stderr}"
)
asyncio.create_task(wait_for_exit())
def disable():
nonlocal disabled
disabled = True
return disable
@staticmethod
def check_cmd_exit_error(cmd: CommandHandle):
try:
cmd.wait()
except CommandExitException as e:
assert False, f"command failed with exit code {e.exit_code}: {e.stderr}"
except Exception as e:
raise e
@pytest.fixture
def helpers():
return Helpers
def _generate_random_string(length: int = 8) -> str:
return "".join(random.choices(string.ascii_lowercase + string.digits, k=length))
@pytest.fixture
def volume(request):
vol = Volume.create(f"test-vol-{_generate_random_string()}")
def finalizer():
if getattr(request.node, "_test_failed", False):
print(f"\n[TEST FAILED] Volume ID: {vol.volume_id}")
try:
Volume.destroy(vol.volume_id)
except Exception:
pass
request.addfinalizer(finalizer)
return vol
@pytest.fixture
async def async_volume(request, event_loop):
vol = await AsyncVolume.create(f"test-vol-{_generate_random_string()}")
def finalizer():
if getattr(request.node, "_test_failed", False):
print(f"\n[TEST FAILED] Volume ID: {vol.volume_id}")
async def _destroy():
try:
await AsyncVolume.destroy(vol.volume_id)
except Exception:
pass
event_loop.run_until_complete(_destroy())
request.addfinalizer(finalizer)
return vol