Isolated Filesystem Sandbox For Tests
A test sandbox that creates a private temporary directory tree, exposes path helpers, and removes everything even when assertions fail.
Code
import tempfile
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Iterator, Optional
class SandboxEscapeError(ValueError):
"""Raised when a requested path would leave the sandbox root."""
@dataclass(frozen=True)
class Sandbox:
root: Path
def resolve(self, *parts: str) -> Path:
target = self.root.joinpath(*parts).resolve()
if target != self.root and self.root not in target.parents:
raise SandboxEscapeError("path escapes the sandbox: " + str(target))
return target
def write(self, relative_path: str, content: str) -> Path:
target = self.resolve(relative_path)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
return target
def read(self, relative_path: str) -> str:
return self.resolve(relative_path).read_text(encoding="utf-8")
def exists(self, relative_path: str) -> bool:
return self.resolve(relative_path).exists()
@contextmanager
def sandbox(prefix: Optional[str] = None) -> Iterator[Sandbox]:
"""Yield a private temporary sandbox and always remove it afterwards."""
with tempfile.TemporaryDirectory(prefix=prefix or "devfactory-") as raw:
yield Sandbox(root=Path(raw).resolve())Tests that write into the working directory leave artefacts behind, collide with parallel runs, and can delete real files when a path is wrong.
Use case: engineers writing tests that read and write files
Inputs / outputs
- Input: an optional prefix for the sandbox directory name
- Output: a context manager yielding a sandbox object with create, write, read and path helpers
Error conditions
- path escapes the sandbox root
- file not found on read
- cleanup after a failure
Approach
TemporaryDirectory context manager; a helper joins and validates paths against the root; cleanup is guaranteed by the context manager protocol.
Implementation
import tempfile
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Iterator, Optional
class SandboxEscapeError(ValueError):
"""Raised when a requested path would leave the sandbox root."""
@dataclass(frozen=True)
class Sandbox:
root: Path
def resolve(self, *parts: str) -> Path:
target = self.root.joinpath(*parts).resolve()
if target != self.root and self.root not in target.parents:
raise SandboxEscapeError("path escapes the sandbox: " + str(target))
return target
def write(self, relative_path: str, content: str) -> Path:
target = self.resolve(relative_path)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
return target
def read(self, relative_path: str) -> str:
return self.resolve(relative_path).read_text(encoding="utf-8")
def exists(self, relative_path: str) -> bool:
return self.resolve(relative_path).exists()
@contextmanager
def sandbox(prefix: Optional[str] = None) -> Iterator[Sandbox]:
"""Yield a private temporary sandbox and always remove it afterwards."""
with tempfile.TemporaryDirectory(prefix=prefix or "devfactory-") as raw:
yield Sandbox(root=Path(raw).resolve())
Verification tests
import unittest
from contextlib import contextmanager
from pathlib import Path
from example import SandboxEscapeError, sandbox
class SandboxTests(unittest.TestCase):
def test_writes_and_reads_files_inside_the_sandbox(self):
with sandbox() as sb:
sb.write("nested/data.txt", "hello")
self.assertEqual(sb.read("nested/data.txt"), "hello")
self.assertTrue(sb.exists("nested/data.txt"))
def test_rejects_a_path_escaping_the_root(self):
with sandbox() as sb:
with self.assertRaises(SandboxEscapeError):
sb.write("../escape.txt", "nope")
def test_cleans_up_after_a_failure(self):
captured = {}
@contextmanager
def tracked():
with sandbox() as sb:
captured["root"] = sb.root
try:
yield sb
finally:
pass
with self.assertRaises(AssertionError):
with tracked() as sb:
sb.write("a.txt", "x")
self.assertEqual(sb.read("a.txt"), "different")
# 目录由 TemporaryDirectory 在 sandbox() 退出后清理,因此在 with 之后再断言
self.assertFalse(Path(captured["root"]).exists())
def test_read_of_a_missing_file_raises(self):
with sandbox() as sb:
with self.assertRaises(FileNotFoundError):
sb.read("missing.txt")
if __name__ == "__main__":
unittest.main()
Dependencies and running
No external dependencies (standard library only).
Runtime: python >= 3.9 Entry point: python example.py
Limitations and error handling
no permission or ownership simulation; no symlink following checks.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.