執行程式碼的 Agent 工具整合測試:測試環境、清理、標籤與預算
Integration tests for agent tools that run code: fixtures, cleanup, labels and budgets
Sandscale 説明如何用真實沙箱測試執行程式碼的 Agent 工具,驗證輸出、錯誤狀態、網絡限制及執行環境隔離。示例使用 Vitest 和 Sandscale TypeScript SDK,每個測試檔共用一個沙箱,並以標籤識別遺留環境、在測試結束後停止沙箱。文章亦建議在工具變更時或定期執行測試,並清理運行超過一小時的整合測試沙箱。
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:
- The happy path: a command runs and the result has the exit code and output you expect.
- Failures the model must understand: non-zero exit, timeout, out of memory.
- Output handling: long output is truncated with head and tail kept; known secret values are masked.
-
The environment: the tools your prompts assume (Python version,
git,rg) are really there. - 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.
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
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:
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.
-
Sweep leftovers. A nightly job that lists sandboxes labelled
purpose=integration-testolder than an hour and stops them costs nothing and catches the rare leak.
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.
Originally published on the Sandscale blog.
來源:DEV Community · dev.to