Skip to content

armgit / E2B

Public Imported from GitHub
0

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

test: mock all volume tests and remove ENABLE_VOLUME_TESTS skip flag (#1734)

devin-ai-integration[bot]d000bbd2dbea
diff --git a/.changeset/mock-volume-exists-fix.md b/.changeset/mock-volume-exists-fix.md
new file mode 100644
index 000000000..a3b726f2c
--- /dev/null
+++ b/.changeset/mock-volume-exists-fix.md
@@ -0,0 +1,5 @@
+---
+'e2b': patch
+---
+
+Fix `Volume.exists()` to return `false` for missing paths again — `getInfo()` now throws `VolumePathNotFoundError` (which no longer subclasses the deprecated `NotFoundError`), so the 404 catch is updated accordingly.
diff --git a/packages/js-sdk/src/volume/index.ts b/packages/js-sdk/src/volume/index.ts
index 93c307168..4563d0f9d 100644
--- a/packages/js-sdk/src/volume/index.ts
+++ b/packages/js-sdk/src/volume/index.ts
@@ -15,7 +15,6 @@ import {
} from '../connectionConfig'
import { isArrayBufferLike, isBlobLike } from '../is'
import {
- NotFoundError,
VolumeError,
VolumeNotFoundError,
VolumePathNotFoundError,
@@ -432,7 +431,7 @@ export class Volume extends ClientFactory {
await this.getInfo(path, opts)
return true
} catch (err) {
- if (err instanceof NotFoundError) {
+ if (err instanceof VolumePathNotFoundError) {
return false
}
throw err
diff --git a/packages/js-sdk/tests/setup.ts b/packages/js-sdk/tests/setup.ts
index e29c20eba..91d427c3c 100644
--- a/packages/js-sdk/tests/setup.ts
+++ b/packages/js-sdk/tests/setup.ts
@@ -115,29 +115,33 @@ export const buildTemplateTest = base.extend<BuildTemplateFixture>({
],
})
-export const volumeTest = base
- .extend<VolumeFixture>({
- volume: [
- // eslint-disable-next-line no-empty-pattern
- async ({}, use) => {
- const volume = await Volume.create(`test-vol-${generateRandomString()}`)
- onTestFailed(() => {
- console.error(`\n[TEST FAILED] Volume ID: ${volume.volumeId}`)
- })
+export const volumeTest = base.extend<VolumeFixture>({
+ volume: [
+ // eslint-disable-next-line no-empty-pattern
+ async ({}, use) => {
+ // The placeholder key keeps the mocked volume tests independent of
+ // E2B_API_KEY being set in the environment.
+ const volume = await Volume.create(`test-vol-${generateRandomString()}`, {
+ apiKey: process.env.E2B_API_KEY ?? TEST_API_KEY,
+ })
+ onTestFailed(() => {
+ console.error(`\n[TEST FAILED] Volume ID: ${volume.volumeId}`)
+ })
+ try {
+ await use(volume)
+ } finally {
try {
- await use(volume)
- } finally {
- try {
- await Volume.destroy(volume.volumeId)
- } catch {
- // Ignore cleanup errors
- }
+ await Volume.destroy(volume.volumeId, {
+ apiKey: process.env.E2B_API_KEY ?? TEST_API_KEY,
+ })
+ } catch {
+ // Ignore cleanup errors
}
- },
- { auto: false },
- ],
- })
- .skipIf(process.env.ENABLE_VOLUME_TESTS === undefined)
+ }
+ },
+ { auto: false },
+ ],
+})
export const isDebug = process.env.E2B_DEBUG !== undefined
diff --git a/packages/js-sdk/tests/volume/file.test.ts b/packages/js-sdk/tests/volume/file.test.ts
index 5819b332b..3b350f5f7 100644
--- a/packages/js-sdk/tests/volume/file.test.ts
+++ b/packages/js-sdk/tests/volume/file.test.ts
@@ -1,6 +1,17 @@
-import { describe, expect } from 'vitest'
-import { NotFoundError, VolumeError, VolumeFileType } from '../../src'
+import { afterAll, beforeAll, beforeEach, describe, expect } from 'vitest'
+import { setupServer } from 'msw/node'
+
+import { VolumeError, VolumeFileType, VolumePathNotFoundError } from '../../src'
import { volumeTest } from '../setup'
+import { createMockVolumeApi } from './mockVolumeContent'
+
+const server = setupServer()
+
+beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
+afterAll(() => server.close())
+// A fresh mock per test gives isolated state (same as the per-fixture
+// MockVolumeContentAPI in the Python SDK tests).
+beforeEach(() => server.resetHandlers(...createMockVolumeApi()))
describe('Volume File Operations', () => {
describe('writeFile and readFile', () => {
@@ -221,11 +232,11 @@ describe('Volume File Operations', () => {
})
volumeTest(
- 'should throw NotFoundError when updating non-existent file',
+ 'should throw VolumePathNotFoundError when updating non-existent file',
async ({ volume }) => {
await expect(
volume.updateMetadata('/non-existent.txt', { mode: 0o644 })
- ).rejects.toThrow(NotFoundError)
+ ).rejects.toThrow(VolumePathNotFoundError)
}
)
})
@@ -317,10 +328,10 @@ describe('Volume File Operations', () => {
})
volumeTest(
- 'should throw NotFoundError for non-existent directory',
+ 'should throw VolumePathNotFoundError for non-existent directory',
async ({ volume }) => {
await expect(volume.list('/non-existent')).rejects.toThrow(
- NotFoundError
+ VolumePathNotFoundError
)
}
)
@@ -356,10 +367,10 @@ describe('Volume File Operations', () => {
})
volumeTest(
- 'should throw NotFoundError when removing non-existent file',
+ 'should throw VolumePathNotFoundError when removing non-existent file',
async ({ volume }) => {
await expect(volume.remove('/non-existent.txt')).rejects.toThrow(
- NotFoundError
+ VolumePathNotFoundError
)
}
)
diff --git a/packages/js-sdk/tests/volume/mockVolumeContent.ts b/packages/js-sdk/tests/volume/mockVolumeContent.ts
new file mode 100644
index 000000000..e19ad1293
--- /dev/null
+++ b/packages/js-sdk/tests/volume/mockVolumeContent.ts
@@ -0,0 +1,319 @@
+import { http, HttpResponse } from 'msw'
+import { randomUUID } from 'node:crypto'
+
+import { VolumeFileType } from '../../src'
+import { apiUrl } from '../setup'
+
+/**
+ * In-memory mock of the volume control-plane CRUD plus the volume content API
+ * (spec/openapi-volumecontent.yml), backing the `volumeTest` file-operation
+ * tests with a stateful in-process filesystem.
+ */
+
+const DEFAULT_FILE_MODE = 0o644
+const DEFAULT_DIR_MODE = 0o755
+
+interface Entry {
+ name: string
+ type: VolumeFileType
+ path: string
+ uid: number
+ gid: number
+ mode: number
+ content: Uint8Array
+ timestamp: string
+}
+
+function normalize(path: string): string {
+ let normalized = path.trim()
+ if (!normalized.startsWith('/')) {
+ normalized = `/${normalized}`
+ }
+ // Collapse repeated slashes and strip a trailing slash (except for root).
+ normalized = normalized.replace(/\/+/g, '/')
+ if (normalized.length > 1 && normalized.endsWith('/')) {
+ normalized = normalized.slice(0, -1)
+ }
+ return normalized
+}
+
+function dirname(path: string): string {
+ const idx = path.lastIndexOf('/')
+ return idx <= 0 ? '/' : path.slice(0, idx)
+}
+
+function basename(path: string): string {
+ return path.slice(path.lastIndexOf('/') + 1)
+}
+
+function makeEntry(
+ path: string,
+ type: Entry['type'],
+ params: URLSearchParams,
+ content: Uint8Array = new Uint8Array()
+): Entry {
+ const mode = params.get('mode')
+ return {
+ name: basename(path),
+ type,
+ path,
+ uid: Number(params.get('uid') ?? 0),
+ gid: Number(params.get('gid') ?? 0),
+ mode:
+ mode !== null
+ ? Number(mode)
+ : type === VolumeFileType.FILE
+ ? DEFAULT_FILE_MODE
+ : DEFAULT_DIR_MODE,
+ content,
+ timestamp: new Date().toISOString(),
+ }
+}
+
+function stat(entry: Entry) {
+ return {
+ name: entry.name,
+ type: entry.type,
+ path: entry.path,
+ size: entry.content.length,
+ mode: entry.mode,
+ uid: entry.uid,
+ gid: entry.gid,
+ atime: entry.timestamp,
+ mtime: entry.timestamp,
+ ctime: entry.timestamp,
+ }
+}
+
+function error(status: number, message: string) {
+ return HttpResponse.json({ code: String(status), message }, { status })
+}
+
+function makeDir(
+ fs: Map<string, Entry>,
+ path: string,
+ params: URLSearchParams
+) {
+ const force = params.get('force') === 'true'
+ const existing = fs.get(path)
+ if (existing) {
+ if (!force || existing.type !== VolumeFileType.DIRECTORY) {
+ return error(409, `Path ${path} already exists`)
+ }
+ return HttpResponse.json(stat(existing), { status: 201 })
+ }
+
+ const parentPath = dirname(path)
+ const parent = fs.get(parentPath)
+ if (!parent) {
+ if (!force) {
+ return error(404, `Path ${parentPath} not found`)
+ }
+ const res = makeDir(fs, parentPath, params)
+ if (res.status >= 400) {
+ return res
+ }
+ } else if (parent.type !== VolumeFileType.DIRECTORY) {
+ return error(409, `Path ${parentPath} is not a directory`)
+ }
+
+ const entry = makeEntry(path, VolumeFileType.DIRECTORY, params)
+ fs.set(path, entry)
+ return HttpResponse.json(stat(entry), { status: 201 })
+}
+
+/**
+ * Per-instance mock of the volume control-plane CRUD plus the volume content
+ * API. Create a fresh instance per test to get isolated state, mirroring the
+ * per-fixture `MockVolumeContentAPI` in the Python SDK tests.
+ */
+export function createMockVolumeApi() {
+ // Volumes created via the control-plane mock, keyed by volume ID.
+ const volumes = new Map<
+ string,
+ { volumeID: string; name: string; token: string }
+ >()
+
+ // One in-memory filesystem per volume, keyed by volume ID.
+ const filesystems = new Map<string, Map<string, Entry>>()
+
+ function getFs(volumeID: string): Map<string, Entry> {
+ let fs = filesystems.get(volumeID)
+ if (!fs) {
+ fs = new Map([
+ ['/', makeEntry('/', VolumeFileType.DIRECTORY, new URLSearchParams())],
+ ])
+ filesystems.set(volumeID, fs)
+ }
+ return fs
+ }
+
+ return [
+ // Control-plane volume CRUD used by the `volumeTest` fixture.
+ http.post(apiUrl('/volumes'), async ({ request }) => {
+ const { name } = (await request.clone().json()) as { name: string }
+ const volumeID = randomUUID()
+ const token = `vol-token-${randomUUID()}`
+ volumes.set(volumeID, { volumeID, name, token })
+ return HttpResponse.json({ volumeID, name, token }, { status: 201 })
+ }),
+
+ http.delete<{ volumeID: string }>(
+ apiUrl('/volumes/:volumeID'),
+ ({ params }) => {
+ const existed = volumes.delete(params.volumeID)
+ filesystems.delete(params.volumeID)
+ if (!existed) {
+ return error(404, 'Not found')
+ }
+ return new HttpResponse(null, { status: 204 })
+ }
+ ),
+
+ // Volume content API.
+ http.put<{ volumeID: string }>(
+ apiUrl('/volumecontent/:volumeID/file'),
+ async ({ params, request }) => {
+ const fs = getFs(params.volumeID)
+ const query = new URL(request.url).searchParams
+ const path = normalize(query.get('path') ?? '')
+
+ const existing = fs.get(path)
+ if (existing) {
+ if (existing.type !== VolumeFileType.FILE) {
+ return error(409, `Path ${path} is a directory`)
+ }
+ if (query.get('force') !== 'true') {
+ return error(409, `Path ${path} already exists`)
+ }
+ }
+
+ const parent = fs.get(dirname(path))
+ if (!parent || parent.type !== VolumeFileType.DIRECTORY) {
+ return error(404, `Path ${path} not found`)
+ }
+
+ const content = new Uint8Array(await request.arrayBuffer())
+ const entry = makeEntry(path, VolumeFileType.FILE, query, content)
+ fs.set(path, entry)
+ return HttpResponse.json(stat(entry), { status: 201 })
+ }
+ ),
+
+ http.get<{ volumeID: string }>(
+ apiUrl('/volumecontent/:volumeID/file'),
+ ({ params, request }) => {
+ const fs = getFs(params.volumeID)
+ const path = normalize(
+ new URL(request.url).searchParams.get('path') ?? ''
+ )
+ const entry = fs.get(path)
+ if (!entry || entry.type !== VolumeFileType.FILE) {
+ return error(404, `Path ${path} not found`)
+ }
+ return new HttpResponse(
+ entry.content.length > 0 ? entry.content.slice().buffer : null,
+ {
+ status: 200,
+ headers: {
+ 'Content-Type': 'application/octet-stream',
+ 'Content-Length': String(entry.content.length),
+ },
+ }
+ )
+ }
+ ),
+
+ http.get<{ volumeID: string }>(
+ apiUrl('/volumecontent/:volumeID/dir'),
+ ({ params, request }) => {
+ const fs = getFs(params.volumeID)
+ const path = normalize(
+ new URL(request.url).searchParams.get('path') ?? ''
+ )
+ const entry = fs.get(path)
+ if (!entry || entry.type !== VolumeFileType.DIRECTORY) {
+ return error(404, `Path ${path} not found`)
+ }
+ const prefix = path === '/' ? '/' : `${path}/`
+ const children = Array.from(fs.entries())
+ .filter(
+ ([p]) =>
+ p !== path &&
+ p.startsWith(prefix) &&
+ !p.slice(prefix.length).includes('/')
+ )
+ .map(([, e]) => stat(e))
+ return HttpResponse.json(children)
+ }
+ ),
+
+ http.post<{ volumeID: string }>(
+ apiUrl('/volumecontent/:volumeID/dir'),
+ ({ params, request }) => {
+ const fs = getFs(params.volumeID)
+ const query = new URL(request.url).searchParams
+ const path = normalize(query.get('path') ?? '')
+ return makeDir(fs, path, query)
+ }
+ ),
+
+ http.get<{ volumeID: string }>(
+ apiUrl('/volumecontent/:volumeID/path'),
+ ({ params, request }) => {
+ const fs = getFs(params.volumeID)
+ const path = normalize(
+ new URL(request.url).searchParams.get('path') ?? ''
+ )
+ const entry = fs.get(path)
+ if (!entry) {
+ return error(404, `Path ${path} not found`)
+ }
+ return HttpResponse.json(stat(entry))
+ }
+ ),
+
+ http.patch<{ volumeID: string }>(
+ apiUrl('/volumecontent/:volumeID/path'),
+ async ({ params, request }) => {
+ const fs = getFs(params.volumeID)
+ const path = normalize(
+ new URL(request.url).searchParams.get('path') ?? ''
+ )
+ const entry = fs.get(path)
+ if (!entry) {
+ return error(404, `Path ${path} not found`)
+ }
+ const body = (await request.clone().json()) as {
+ uid?: number
+ gid?: number
+ mode?: number
+ }
+ if (body.uid !== undefined) entry.uid = body.uid
+ if (body.gid !== undefined) entry.gid = body.gid
+ if (body.mode !== undefined) entry.mode = body.mode
+ return HttpResponse.json(stat(entry))
+ }
+ ),
+
+ http.delete<{ volumeID: string }>(
+ apiUrl('/volumecontent/:volumeID/path'),
+ ({ params, request }) => {
+ const fs = getFs(params.volumeID)
+ const path = normalize(
+ new URL(request.url).searchParams.get('path') ?? ''
+ )
+ if (path === '/' || !fs.has(path)) {
+ return error(404, `Path ${path} not found`)
+ }
+ const prefix = `${path}/`
+ for (const p of Array.from(fs.keys())) {
+ if (p === path || p.startsWith(prefix)) {
+ fs.delete(p)
+ }
+ }
+ return new HttpResponse(null, { status: 204 })
+ }
+ ),
+ ]
+}
diff --git a/packages/python-sdk/tests/conftest.py b/packages/python-sdk/tests/conftest.py
index 0df3b14ee..fa8f4a094 100644
--- a/packages/python-sdk/tests/conftest.py
+++ b/packages/python-sdk/tests/conftest.py
@@ -2,11 +2,23 @@ import asyncio
import os
import random
import string
+from http import HTTPStatus
from typing import Callable, Dict, Optional
+from uuid import uuid4
+import attrs
+import httpx
import pytest
import pytest_asyncio
+import e2b.api.client.api.volumes.delete_volumes_volume_id as delete_volume_mod
+import e2b.api.client.api.volumes.post_volumes as post_volumes_mod
+import e2b.volume.volume_async as volume_async_mod
+import e2b.volume.volume_sync as volume_sync_mod
+from e2b.api.client.models.volume_and_token import VolumeAndToken
+from e2b.api.client.types import Response
+from mock_volume_content import MockVolumeContentAPI
+
from e2b import (
AsyncCommandHandle,
AsyncSandbox,
@@ -252,38 +264,72 @@ def _generate_random_string(length: int = 8) -> str:
return "".join(random.choices(string.ascii_lowercase + string.digits, k=length))
-def _skip_unless_volume_tests_enabled():
- if os.getenv("ENABLE_VOLUME_TESTS") is None:
- pytest.skip("skipped because ENABLE_VOLUME_TESTS is not set")
+def _mock_volume_transport(monkeypatch, module, transport: httpx.MockTransport):
+ # The mock transport rides in `httpx_args` (an init field, rebuilt with
+ # `attrs.evolve` rather than mutated) so it survives `with_timeout`.
+ def wrap(real_factory):
+ def factory(config, **kwargs):
+ client = real_factory(config, **kwargs)
+ return attrs.evolve(client, httpx_args={"transport": transport})
+ return factory
-def volume(request):
- _skip_unless_volume_tests_enabled()
- vol = Volume.create(f"test-vol-{_generate_random_string()}")
+ # Streamed reads run on their own client (the streaming transport), so
+ # both factories need the mock transport.
+ for name in ("get_volume_api_client", "get_streaming_volume_api_client"):
+ monkeypatch.setattr(module, name, wrap(getattr(module, name)))
- 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)
+def _mock_volume_crud(monkeypatch, detailed_attr: str):
+ """Mock the control-plane create/destroy calls the volume fixtures use."""
+
+ def post_volumes(*, client, body):
+ vol = VolumeAndToken(
+ volume_id=str(uuid4()), name=body.name, token=f"vol-token-{uuid4()}"
+ )
+ return Response(
+ status_code=HTTPStatus(201), content=b"", headers={}, parsed=vol
+ )
+
+ def delete_volume(volume_id, *, client):
+ return Response(
+ status_code=HTTPStatus(204), content=b"", headers={}, parsed=None
+ )
+
+ if detailed_attr == "asyncio_detailed":
+
+ async def async_post_volumes(*, client, body):
+ return post_volumes(client=client, body=body)
+
+ async def async_delete_volume(volume_id, *, client):
+ return delete_volume(volume_id, client=client)
+
+ monkeypatch.setattr(post_volumes_mod, detailed_attr, async_post_volumes)
+ monkeypatch.setattr(delete_volume_mod, detailed_attr, async_delete_volume)
+ else:
+ monkeypatch.setattr(post_volumes_mod, detailed_attr, post_volumes)
+ monkeypatch.setattr(delete_volume_mod, detailed_attr, delete_volume)
+
+
+def volume(request, monkeypatch, test_api_key) -> Volume:
+ monkeypatch.setenv("E2B_API_KEY", test_api_key)
+ mock = MockVolumeContentAPI()
+ _mock_volume_transport(
+ monkeypatch, volume_sync_mod, httpx.MockTransport(mock.handler)
+ )
+ _mock_volume_crud(monkeypatch, "sync_detailed")
+ vol = Volume.create(f"test-vol-{_generate_random_string()}")
+ request.addfinalizer(lambda: Volume.destroy(vol.volume_id))
return vol
@pytest_asyncio.fixture
-async def async_volume(request):
- _skip_unless_volume_tests_enabled()
- vol = await AsyncVolume.create(f"test-vol-{_generate_random_string()}")
- try:
- yield vol
- finally:
- if getattr(request.node, "_test_failed", False):
- print(f"\n[TEST FAILED] Volume ID: {vol.volume_id}")
- try:
- await AsyncVolume.destroy(vol.volume_id)
- except Exception:
- pass
+async def async_volume(request, monkeypatch, test_api_key) -> AsyncVolume:
+ monkeypatch.setenv("E2B_API_KEY", test_api_key)
+ mock = MockVolumeContentAPI()
+ _mock_volume_transport(
+ monkeypatch, volume_async_mod, httpx.MockTransport(mock.async_handler)
+ )
+ _mock_volume_crud(monkeypatch, "asyncio_detailed")
+ return await AsyncVolume.create(f"test-vol-{_generate_random_string()}")
diff --git a/packages/python-sdk/tests/mock_volume_content.py b/packages/python-sdk/tests/mock_volume_content.py
new file mode 100644
index 000000000..7d4931ee1
--- /dev/null
+++ b/packages/python-sdk/tests/mock_volume_content.py
@@ -0,0 +1,231 @@
+"""In-memory mock of the volume content API (spec/openapi-volumecontent.yml).
+
+Backs the `volume`/`async_volume` fixtures so volume file-operation tests run
+against a stateful in-process filesystem instead of a live volume server.
+"""
+
+import json
+import posixpath
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from typing import Dict, Optional
+
+import httpx
+
+from e2b.volume.types import VolumeFileType
+
+DEFAULT_FILE_MODE = 0o644
+DEFAULT_DIR_MODE = 0o755
+
+
+@dataclass
+class _Entry:
+ name: str
+ type: VolumeFileType
+ path: str
+ uid: int = 0
+ gid: int = 0
+ mode: int = 0
+ content: bytes = b""
+ timestamp: str = field(
+ default_factory=lambda: datetime.now(timezone.utc).isoformat()
+ )
+
+ def stat(self) -> dict:
+ return {
+ "name": self.name,
+ "type": self.type,
+ "path": self.path,
+ "size": len(self.content),
+ "mode": self.mode,
+ "uid": self.uid,
+ "gid": self.gid,
+ "atime": self.timestamp,
+ "mtime": self.timestamp,
+ "ctime": self.timestamp,
+ }
+
+
+def _normalize(path: str) -> str:
+ path = path.strip()
+ if not path.startswith("/"):
+ path = "/" + path
+ return posixpath.normpath(path)
+
+
+def _error(status: int, message: str) -> httpx.Response:
+ return httpx.Response(
+ status,
+ content=json.dumps({"code": str(status), "message": message}).encode(),
+ headers={"Content-Type": "application/json"},
+ )
+
+
+class MockVolumeContentAPI:
+ """A per-test, in-memory volume filesystem behind an httpx.MockTransport."""
+
+ def __init__(self):
+ self.entries: Dict[str, _Entry] = {
+ "/": _Entry(
+ name="/",
+ type=VolumeFileType.DIRECTORY,
+ path="/",
+ mode=DEFAULT_DIR_MODE,
+ )
+ }
+
+ def handler(self, request: httpx.Request) -> httpx.Response:
+ request.read()
+ return self._handle(request)
+
+ async def async_handler(self, request: httpx.Request) -> httpx.Response:
+ await request.aread()
+ return self._handle(request)
+
+ def _handle(self, request: httpx.Request) -> httpx.Response:
+ segments = request.url.path.strip("/").split("/")
+ if len(segments) != 3 or segments[0] != "volumecontent":
+ return _error(404, "Not found")
+ resource = segments[2]
+ params = request.url.params
+ path = _normalize(params.get("path") or "")
+
+ if resource == "file":
+ if request.method == "GET":
+ return self._read_file(path)
+ if request.method == "PUT":
+ return self._write_file(path, params, request.content)
+ elif resource == "dir":
+ if request.method == "GET":
+ return self._list_dir(path)
+ if request.method == "POST":
+ return self._make_dir(path, params)
+ elif resource == "path":
+ if request.method == "GET":
+ return self._stat(path)
+ if request.method == "PATCH":
+ return self._update_metadata(path, request.content)
+ if request.method == "DELETE":
+ return self._remove(path)
+
+ return _error(404, "Not found")
+
+ @staticmethod
+ def _int_param(params: httpx.QueryParams, name: str) -> Optional[int]:
+ value = params.get(name)
+ return int(value) if value is not None else None
+
+ @classmethod
+ def _mode_param(cls, params: httpx.QueryParams, default: int) -> int:
+ mode = cls._int_param(params, "mode")
+ return mode if mode is not None else default
+
+ @staticmethod
+ def _bool_param(params: httpx.QueryParams, name: str) -> bool:
+ return (params.get(name) or "").lower() == "true"
+
+ def _read_file(self, path: str) -> httpx.Response:
+ entry = self.entries.get(path)
+ if entry is None or entry.type != VolumeFileType.FILE:
+ return _error(404, f"Path {path} not found")
+ return httpx.Response(
+ 200,
+ content=entry.content,
+ headers={"Content-Type": "application/octet-stream"},
+ )
+
+ def _write_file(
+ self, path: str, params: httpx.QueryParams, content: bytes
+ ) -> httpx.Response:
+ existing = self.entries.get(path)
+ if existing is not None:
+ if existing.type != VolumeFileType.FILE:
+ return _error(409, f"Path {path} is a directory")
+ if not self._bool_param(params, "force"):
+ return _error(409, f"Path {path} already exists")
+
+ parent = self.entries.get(posixpath.dirname(path))
+ if parent is None or parent.type != VolumeFileType.DIRECTORY:
+ return _error(404, f"Path {path} not found")
+
+ entry = _Entry(
+ name=posixpath.basename(path),
+ type=VolumeFileType.FILE,
+ path=path,
+ uid=self._int_param(params, "uid") or 0,
+ gid=self._int_param(params, "gid") or 0,
+ mode=self._mode_param(params, DEFAULT_FILE_MODE),
+ content=content,
+ )
+ self.entries[path] = entry
+ return httpx.Response(201, json=entry.stat())
+
+ def _make_dir(self, path: str, params: httpx.QueryParams) -> httpx.Response:
+ force = self._bool_param(params, "force")
+ existing = self.entries.get(path)
+ if existing is not None:
+ if not force or existing.type != VolumeFileType.DIRECTORY:
+ return _error(409, f"Path {path} already exists")
+ return httpx.Response(201, json=existing.stat())
+
+ parent_path = posixpath.dirname(path)
+ parent = self.entries.get(parent_path)
+ if parent is None:
+ if not force:
+ return _error(404, f"Path {parent_path} not found")
+ res = self._make_dir(parent_path, params)
+ if res.status_code >= 400:
+ return res
+ elif parent.type != VolumeFileType.DIRECTORY:
+ return _error(409, f"Path {parent_path} is not a directory")
+
+ entry = _Entry(
+ name=posixpath.basename(path),
+ type=VolumeFileType.DIRECTORY,
+ path=path,
+ uid=self._int_param(params, "uid") or 0,
+ gid=self._int_param(params, "gid") or 0,
+ mode=self._mode_param(params, DEFAULT_DIR_MODE),
+ )
+ self.entries[path] = entry
+ return httpx.Response(201, json=entry.stat())
+
+ def _list_dir(self, path: str) -> httpx.Response:
+ entry = self.entries.get(path)
+ if entry is None or entry.type != VolumeFileType.DIRECTORY:
+ return _error(404, f"Path {path} not found")
+ prefix = "/" if path == "/" else path + "/"
+ children = [
+ e.stat()
+ for p, e in self.entries.items()
+ if p != path and p.startswith(prefix) and "/" not in p[len(prefix) :]
+ ]
+ return httpx.Response(200, json=children)
+
+ def _stat(self, path: str) -> httpx.Response:
+ entry = self.entries.get(path)
+ if entry is None:
+ return _error(404, f"Path {path} not found")
+ return httpx.Response(200, json=entry.stat())
+
+ def _update_metadata(self, path: str, content: bytes) -> httpx.Response:
+ entry = self.entries.get(path)
+ if entry is None:
+ return _error(404, f"Path {path} not found")
+ body = json.loads(content or b"{}")
+ if body.get("uid") is not None:
+ entry.uid = body["uid"]
+ if body.get("gid") is not None:
+ entry.gid = body["gid"]
+ if body.get("mode") is not None:
+ entry.mode = body["mode"]
+ return httpx.Response(200, json=entry.stat())
+
+ def _remove(self, path: str) -> httpx.Response:
+ if path == "/" or path not in self.entries:
+ return _error(404, f"Path {path} not found")
+ prefix = path + "/"
+ for p in list(self.entries):
+ if p == path or p.startswith(prefix):
+ del self.entries[p]
+ return httpx.Response(204)