# Integration tests for agent tools that run code: fixtures, cleanup, labels and budgets

> Unit tests with a mocked sandbox miss the bugs that matter: timeouts, output limits, missing tools in the image, network refusals. How to write a small integration suite against real sandboxes that is fast enough to run in CI and never leaves boxes behind.

Unit tests with a mocked sandbox miss the bugs that matter: timeouts, output limits, missing tools in the image, network refusals. How to write a small integration suite against real sandboxes that is fast enough to run in CI and never leaves boxes behind.

November 26, 2026 · 4 min read · The Sandscale team

Your agent’s `run_code` tool is probably tested with a mock: call the tool, assert the mock was called with the right command, return a canned result. That test proves your code calls a function. It does not prove that `pytest` exists in the template, that a 200 KB output is truncated the way you think, that a timed-out command is reported as a timeout, or that the sandbox really cannot reach the internet. Those are the bugs that show up in production, as confused model behaviour that nobody can reproduce.

A small integration suite against real sandboxes catches them. This post shows how to structure one with Vitest and the Sandscale TypeScript SDK; the approach carries over to any provider and test runner.

## What to test

Test the contract between your tool and the model, not the provider:

1. **The happy path:** a command runs and the result has the exit code and output you expect.
2. **Failures the model must understand:** non-zero exit, timeout, out of memory.
3. **Output handling:** long output is truncated with head and tail kept; known secret values are masked.
4. **The environment:** the tools your prompts assume (Python version, `git`, `rg`) are really there.
5. **Policy:** the network is closed when it should be; a file written in one run is not visible in the next.

## One sandbox per test file

Starting a box per test is slow and costs more; one box for the whole suite lets tests leak state into each other. One box per test file, created in `beforeAll` and stopped in `afterAll`, is a good middle.

```ts
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { Sandscale, type Sandbox } from '@sandscale/sdk';
import { runCodeTool } from '../src/tools/run-code';

const sandscale = new Sandscale();
let box: Sandbox;

beforeAll(async () => {
  box = await sandscale.sandboxes.create({
    template: 'builtin:python',
    timeoutSeconds: 10 * 60, // the backstop if the test process dies
    labels: { purpose: 'integration-test', suite: 'run-code', ci_run: process.env.GITHUB_RUN_ID ?? 'local' },
  });
}, 120_000);

afterAll(async () => {
  if (box) await sandscale.sandboxes.stop(box.id, { region: box.region });
});
```

The lifetime and the labels are what make this safe. If CI kills the job before `afterAll`, the box stops itself after ten minutes, and the labels let a cleanup script find anything left over.

## The tests

```ts
describe('run_code tool', () => {
  it('returns exit code and output', async () => {
    const r = await runCodeTool(sandscale, box, { code: 'print(2 + 2)' });
    expect(r.exitCode).toBe(0);
    expect(r.stdout.trim()).toBe('4');
  });

  it('reports a timeout as a timeout', async () => {
    const r = await runCodeTool(sandscale, box, { code: 'while True: pass', limit: 'quick' });
    expect(r.status).toBe('timeout');
  });

  it('truncates long output and keeps the tail', async () => {
    const r = await runCodeTool(sandscale, box, { code: 'for i in range(200000): print(i)' });
    expect(r.truncated).toBe(true);
    expect(r.stdout).toContain('199999');
  });

  it('has no network', async () => {
    const r = await runCodeTool(sandscale, box, {
      code: 'import urllib.request; urllib.request.urlopen("https://example.com", timeout=5)',
    });
    expect(r.exitCode).not.toBe(0);
  });
});
```

`runCodeTool` is your own wrapper, the code the model actually calls. The tests assert on its output shape (`status`, `truncated`), which is what the model sees. If you change how timeouts are reported, these tests tell you.

The no-network test relies on the sandbox’s default network mode, `none`. It is worth keeping even though it “obviously” passes: if someone changes the tool to create boxes with `network: 'allowlist'`, this is the test that notices.

## Isolation between runs

If your tool promises a fresh environment per call, test it with two boxes:

```ts
it('does not carry files between runs', async () => {
  const a = await sandscale.sandboxes.create({ template: 'builtin:python', timeoutSeconds: 300, labels: { purpose: 'integration-test' } });
  const b = await sandscale.sandboxes.create({ template: 'builtin:python', timeoutSeconds: 300, labels: { purpose: 'integration-test' } });
  try {
    await sandscale.sandboxes.run(a.id, ['sh', '-c', 'echo secret > /workspace/marker'], { region: a.region });
    const r = await sandscale.sandboxes.run(b.id, ['test', '-e', '/workspace/marker'], { region: b.region });
    expect(r.exitCode).not.toBe(0);
  } finally {
    await Promise.all([a, b].map((x) => sandscale.sandboxes.stop(x.id, { region: x.region })));
  }
}, 120_000);
```

## Keep it cheap and fast

- **Run it on a schedule and on changes to the tool,** not on every commit to every service.
- **Use the smallest size** that runs your tests.
- **Use a dedicated API key** with only the scopes the suite needs and its own project, so its usage is visible on its own. See [scoping API keys](https://sandscale.dev/blog/scoping-api-keys-for-agents-and-ci).
- **Sweep leftovers.** A nightly job that lists sandboxes labelled `purpose=integration-test` older than an hour and stops them costs nothing and catches the rare leak.

```ts
const { data } = await sandscale.sandboxes.list({ status: 'running' });
for (const s of data.filter((s) => s.labels?.purpose === 'integration-test')) {
  if (s.createdAt && Date.now() - s.createdAt.getTime() > 60 * 60 * 1000) {
    await sandscale.sandboxes.stop(s.id, { region: s.region });
  }
}
```

## What the suite buys you

A first run tends to surface problems such as a tool missing from the template, a timeout that throws instead of returning, output that is cut in the middle of a UTF-8 character. Each of those, in production, is a model getting a confusing result and doing something odd with it. Ten integration tests are a cheap way to make your agent’s tool behave the way its description says it does.

**On this page**

1. What to test
2. One sandbox per test file
3. The tests
4. Isolation between runs
5. Keep it cheap and fast
6. What the suite buys you

**Run your agents in a box of their own**

Each sandbox is a Firecracker microVM. Free includes 100 awake vCPU-hours a month.

[Start free](https://cloud.sandscale.dev/auth/signup)

## Keep reading

- [November 26, 2026 · **30 questions to ask any agent sandbox provider before you sign up** · A vendor-neutral checklist for choosing where your agents run code: isolation, network, secrets, lifecycle, billing for waiting time, governance, data location, reliability and leaving. With where to find each answer for Sandscale.](https://sandscale.dev/blog/questions-to-ask-an-agent-sandbox-provider)
- [November 26, 2026 · **Agent sandbox glossary: 41 terms in plain English** · Plain definitions for the words that come up when you run AI agent code in isolation: microVM, VMM, KVM, jailer, gVisor, seccomp, namespaces, egress allowlist, lease, snapshot, warm pool, awake vCPU-hour and more.](https://sandscale.dev/blog/agent-sandbox-glossary)

---
Source: https://sandscale.dev/blog/testing-agent-tools-against-real-sandboxes
