Testing¶
Code that creates sandboxes needs a daemon; its tests should not.
fastsandbox.testing has a fake daemon,
FakeDaemon, which serves the socket API in
memory, and fake_package(), which writes
kit packages that need neither the sbx CLI nor an image. This page shows how
to test an application with them, how to run code written for the real daemon
against the fake one unchanged, and what the fake cannot do.
The examples are async test functions: run them with
pytest-asyncio in its auto mode,
or mark them with @pytest.mark.asyncio.
Testing an application¶
from pathlib import Path
from fastsandbox import Context, FastSandbox
from fastsandbox.models import ExecOutput
from fastsandbox.testing import FakeDaemon, fake_package
async def test_word_count(tmp_path: Path) -> None:
async with FakeDaemon() as daemon:
daemon.on_exec(lambda sandbox, cmd: ExecOutput(exit_code=0, stdout="3\n"))
app = FastSandbox(socket=str(daemon.socket_path), kit=fake_package(tmp_path / "kit"))
@app.task
async def count_words(ctx: Context, text: str) -> int:
output = await ctx.sandbox.exec(f"echo {text!r} | wc -w", check=True)
return int(output.stdout)
assert await app.run("count_words", text="one two three") == 3
assert daemon.sandboxes == {}
async with FakeDaemon() as daemon:listens on a Unix socket of a temporary directory,daemon.socket_path, until the block ends.daemon.on_exec(handler)decides what commands print and exit with: the handler, plain or async, receives the name of the sandbox and the command as a list (a string command arrives as["sh", "-c", script]), and returns anExecOutput. Without one, every command exits with 0 and prints nothing.FastSandbox(socket=..., kit=fake_package(...))points the application at the fake daemon, with a kit package it can create sandboxes from.daemon.sandboxesholds the sandboxes that exist: empty again after the run, since the run deleted its sandbox.
What the fake daemon records¶
The state of the fake daemon is plain data, for the assertions of a test:
| Attribute | Holds |
|---|---|
sandboxes |
The sandboxes, by name, in the shape of GET /sandbox/{name}; sandboxes[name]["request"] is the creation request |
rules |
The network rules applied through it: those of a client, and the HTTP rules of a launch. The host rules of a task or a spec are a mixin of its kit, /kits/docker-sandbox-network in the kits of the creation request |
files |
The files written into sandboxes, by (sandbox, path) |
requests |
Every request it received, in order |
daemon.requests_to(method, pattern)
selects requests by route, with the parameters of the route in braces:
create = daemon.requests_to("POST", "/sandbox")[0].json()
commands = [r.json()["cmd"] for r in daemon.requests_to("POST", "/sandbox/{name}/exec")]
Each is a Request: its method, path, query,
headers and body, and json() to decode the body.
Code written for the real daemon¶
An application declared as it is used in production, FastSandbox("ci") with
the kits of sbx, runs against the fake daemon when the environment points it
there:
from pathlib import Path
import pytest
import fastsandbox
from fastsandbox import Context, FastSandbox
from fastsandbox.models import ExecOutput
from fastsandbox.testing import FakeDaemon
app = FastSandbox("ci")
@app.task(kit="shell")
async def python_version(ctx: Context) -> str:
output = await ctx.sandbox.exec(["python3", "--version"], check=True)
return output.stdout.strip()
async def test_python_version(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
async with FakeDaemon() as daemon:
monkeypatch.setenv(fastsandbox.SOCKET_ENV, str(daemon.socket_path))
monkeypatch.setenv("FASTSANDBOX_KIT_CACHE", str(tmp_path / "kits"))
daemon.on_exec(lambda sandbox, cmd: ExecOutput(exit_code=0, stdout="Python 3.12.3\n"))
assert await app.run("python_version") == "Python 3.12.3"
assert daemon.sandboxes == {}
DOCKER_SANDBOXES_API(fastsandbox.SOCKET_ENV) names the socketconnect()uses when it is given none.- The kits are forged against the fake daemon, as against the daemon: it
serves the published kits
shellandclaude(FakeDaemon.kits, aPublishedKiteach), which a test extends with a kit of its own.FASTSANDBOX_KIT_CACHEgives the kit cache of the process a directory of the test, so that the packages of one test are not those of another.
A package written by fake_package is not one the cache makes: it is given to
the application or to the task itself, kit=fake_package(tmp_path / "kit"),
and each run launches its sandbox on it as it is. So does a package held in
memory, forged with KitForge or assembled with
KitPackage.in_memory: it is the kit of a
task without being saved first.
The tests of this repository make that environment a fixture,
fake_environment: every snippet of this documentation is tested against the
fake daemon, and against the real one too for what only it shows (see
Routes and limits).
Agents¶
A task declared with @app.agent("claude") runs against the fake daemon as it
does against the daemon: its kit is forged from the published claude kit the
fake serves, which declares the program of the agent, its run options, and the
service anthropic with its host.
from pathlib import Path
import pytest
import fastsandbox
from fastsandbox import AgentRunner, FastSandbox
from fastsandbox.testing import FakeDaemon
app = FastSandbox("agents")
@app.agent("claude", timeout="15m")
async def show_command(agent: AgentRunner, prompt: str) -> list[str]:
return agent.command(prompt)
async def test_show_command(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
async with FakeDaemon() as daemon:
monkeypatch.setenv(fastsandbox.SOCKET_ENV, str(daemon.socket_path))
monkeypatch.setenv("FASTSANDBOX_KIT_CACHE", str(tmp_path / "kits"))
monkeypatch.setenv("ANTHROPIC_API_KEY", "dummy-key")
command = await app.run("show_command", prompt="Explain this project")
assert command[:3] == ["claude", "--dangerously-skip-permissions", "-p"]
# The key goes to the proxy, for the host the kit declares for its service.
[pushed] = [
update.json()
for update in daemon.requests_to("POST", "/sandbox/{name}/credentials")
if update.json().get("custom_secrets")
]
[secret] = pushed["custom_secrets"]
assert secret["targets"] == ["api.anthropic.com"]
# The sandbox holds a placeholder in its place.
create = daemon.requests_to("POST", "/sandbox")[0].json()
assert create["environment"]["ANTHROPIC_API_KEY"] != "dummy-key"
assert daemon.sandboxes == {}
- The key of the agent is read from the environment, as against the daemon: set a dummy value. The run gives it to the proxy as a custom secret for the host the kit declares, and the sandbox holds its placeholder.
agent.command(prompt)gives the command a prompt would run, without running it. The agent itself runs on the fake daemon too, withprompt,streamorsession: itson_exechandler answers the command of the agent as it answers every command, so that what a test asserts about the agent is what the handler answered (see the next section).
fake_package(directory, agent="claude", artifact=...) writes the package of an
agent kit without an image, for client code that creates sandboxes from a
package; the artifact describes the program of the agent, its run options and
the hosts it needs, {"manifest": {"name": "claude", "binary": "claude"},
"caps": {"network": {"allow": ["api.anthropic.com:443"]}}}. It declares no
service: the key of an agent task whose kit it is has nowhere to go, and is
left out (see Agents).
Routes and limits¶
The fake daemon serves what the client and the framework need for most tasks:
the health of the daemon, the list and the life cycle of sandboxes, sessions,
commands, files, network rules, credentials, the ports of a sandbox, the list
and the loading of images, and what the forge asks for: the pull and the
export of its published kits, and the kit settings of the daemon
(daemon.settings: kit.allowLocalKits and kit.requireSignature, which a
test changes to see the kit policy refuse a forge). A route it does not serve
answers 404, until a test adds it: the event and prompt streams, the
activity log of the policy, the MCP gateway and the other settings of the
daemon among them. It withholds
no credential, at creation or on a push. As the daemon does, it deletes a
sandbox asked by its identifier (expected_id) only if it is that sandbox, and
answers 409 otherwise, which is how a lease never removes another sandbox
given the same name since. FakeDaemon(version=..., api_version=...)
sets the sbx version and the API version it reports, to test what a client
does with a daemon it does not support.
daemon.route(method, pattern) adds a
route, or replaces a built-in one, with a handler that returns a
Response:
@daemon.route("GET", "/sandbox/{name}/ports")
def ports(request: Request) -> Response:
return Response(200, [{"host_port": 8080, "sandbox_port": 80, "protocol": "tcp"}])
A test of a program that reads the credentials the daemon withholds answers the push itself:
@daemon.route("POST", "/sandbox/{name}/credentials")
def withheld(request: Request) -> Response:
return Response(200, {"message": "Credentials updated", "withheld": ["anthropic"]})
A Response carries a status and a JSON body, or instead lines, JSON values
sent as an NDJSON stream, or raw bytes with their content_type, a tar
archive for instance; hold=True keeps a streamed body open until the client
leaves, as the daemon does for a session. The event stream a program reads is
answered that way, events in the shape of the daemon:
@daemon.route("GET", "/events")
def events(request: Request) -> Response:
synced = {"id": "sync", "type": "sync", "action": "complete"}
created = {"id": "e1", "type": "sandbox.lifecycle", "action": "created", "sandbox_name": "job"}
return Response(200, lines=[synced, created], hold=True)
Interactive sessions, agent runs and SSH tunnels upgrade the HTTP connection of
the socket into a raw stream. The fake daemon does it for commands and agent
sessions: Sandbox.attach,
Sandbox.agent_session, and what
AgentRunner.prompt and
stream run with them, are answered by its
on_exec handler, as exec is; an agent session gives it [agent, *args],
the agent of the sandbox and the arguments of the session. The output comes in
the shape of the daemon, multiplexed without a terminal and raw with one, and
the execution has ended once it is sent: a resize then answers 409, as the
daemon does once a command has ended. The standard input a command is given is
read and left aside. SSH tunnels are not faked: the fake answers ssh_tunnel
with 501, unless a test adds the route, whose Response(101, raw=...) gives
the bytes the tunnel reads, the greeting of an SSH server for instance; no SSH
server answers behind it.
@daemon.route("POST", "/sandbox/{name}/ssh")
def tunnel(request: Request) -> Response:
return Response(101, raw=b"SSH-2.0-OpenSSH_9.6\r\n")
The fake daemon does not run commands either: what a test asserts about one is
what its on_exec handler answered. What only the real daemon shows is
checked against it: the input piped through an attached command, the events a
real creation publishes, an SSH session with a real server, the install
commands of a mixin.