> ## Documentation Index
> Fetch the complete documentation index at: https://docs.fibre.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Tests and CI

> Run a test suite in a fresh sandbox from any CI or script: send the code, stream the output live, fail the build on the exit code, and keep the sandbox around to debug a failure.

Some tests are better kept off your CI runner and off your laptop. They might install software, start servers,
reach the network, or run code that an agent has just written. **Running them in a sandbox** instead gives you
several advantages:

* **A clean machine for every run**, with nothing left over from the previous one.
* **More power than the CI runner** when you need it (the `large` and `xlarge` sizes), and Docker on the `vm`
  runtime.
* **The test output streamed live** into your CI log, as the tests run.
* **A way to investigate failures**: when a run fails, you can keep its sandbox and look inside to see why.

## The script

A single script does all of this. It packs up the project, sends it to a sandbox, runs the tests, streams their
output into the log, and finally exits with the same code as the tests, so your CI marks the build as passed or
failed. You can run it from GitHub Actions, GitLab, Jenkins, or your own terminal.

**1. A project to test**

To keep the example self-contained, we create a tiny project with one module and its tests. In your pipeline, this
would be your own repository.

```bash title="CLI" run theme={null}
mkdir -p project
cat > project/slugify.py <<'PY'
import re
def slugify(text):
    return re.sub(r'[^a-z0-9]+', '-', text.lower()).strip('-')
PY
cat > project/test_slugify.py <<'PY'
import unittest
from slugify import slugify
class T(unittest.TestCase):
    def test_spaces(self): self.assertEqual(slugify('Hello World'), 'hello-world')
    def test_symbols(self): self.assertEqual(slugify('fibre: sandboxes!'), 'fibre-sandboxes')
    def test_trim(self): self.assertEqual(slugify('  padded  '), 'padded')
PY
```

```typescript title="TypeScript" run theme={null}
import { mkdirSync, writeFileSync } from "node:fs";

mkdirSync("project", { recursive: true });
writeFileSync("project/slugify.py", [
  "import re",
  "def slugify(text):",
  "    return re.sub(r'[^a-z0-9]+', '-', text.lower()).strip('-')",
].join("\n") + "\n");
writeFileSync("project/test_slugify.py", [
  "import unittest",
  "from slugify import slugify",
  "class T(unittest.TestCase):",
  "    def test_spaces(self): self.assertEqual(slugify('Hello World'), 'hello-world')",
  "    def test_symbols(self): self.assertEqual(slugify('fibre: sandboxes!'), 'fibre-sandboxes')",
  "    def test_trim(self): self.assertEqual(slugify('  padded  '), 'padded')",
].join("\n") + "\n");
```

```python title="Python" run theme={null}
from pathlib import Path

Path("project").mkdir(exist_ok=True)
Path("project/slugify.py").write_text("\n".join([
    "import re",
    "def slugify(text):",
    "    return re.sub(r'[^a-z0-9]+', '-', text.lower()).strip('-')",
]) + "\n")
Path("project/test_slugify.py").write_text("\n".join([
    "import unittest",
    "from slugify import slugify",
    "class T(unittest.TestCase):",
    "    def test_spaces(self): self.assertEqual(slugify('Hello World'), 'hello-world')",
    "    def test_symbols(self): self.assertEqual(slugify('fibre: sandboxes!'), 'fibre-sandboxes')",
    "    def test_trim(self): self.assertEqual(slugify('  padded  '), 'padded')",
]) + "\n")
```

**2. Send it and run the tests**

```bash title="CLI" run theme={null}
RUN_ID=${GITHUB_RUN_ID:-local}
SBX=$(fibre create --size medium --lifetime 1h --label ci=tests --label run=$RUN_ID --json | jq -r .id)

# send the project folder, then run the tests: their output streams into this job's log as it is written
fibre cp project "$SBX:/work/app"
if fibre exec "$SBX" --cwd /work/app -- python3 -m unittest -v; then EXIT_CODE=0; else EXIT_CODE=$?; fi

echo "tests exited with $EXIT_CODE"   # tests exited with 0
```

```typescript title="TypeScript" run theme={null}
import { execFileSync } from "node:child_process";
import { Sandbox } from "@fibre-dev/sdk";

const runId = process.env.GITHUB_RUN_ID ?? "local";
const sbx = await Sandbox.create({ size: "medium", lifetime: 3600, labels: { ci: "tests", run: runId } });

// send the project as one archive, unpack it inside
await sbx.files.write("/work/project.tgz", execFileSync("tar", ["-C", "project", "-czf", "-", "."]));
await sbx.run("mkdir -p /work/app && tar -xzf /work/project.tgz -C /work/app");

// run the tests, streaming the output into this job's log as it is written
const tests = await sbx.spawn(["python3", "-m", "unittest", "-v"], { cwd: "/work/app" });
for await (const chunk of tests.output()) process.stdout.write(chunk.data);
const { exitCode } = await tests.wait();

console.log(`\ntests exited with ${exitCode}`); // tests exited with 0
```

```python title="Python" run theme={null}
import os
import subprocess
import sys

from fibre import Sandbox

run_id = os.environ.get("GITHUB_RUN_ID", "local")
sbx = Sandbox.create(size="medium", lifetime=3600, labels={"ci": "tests", "run": run_id})

# send the project as one archive, unpack it inside
sbx.files.write("/work/project.tgz", subprocess.run(["tar", "-C", "project", "-czf", "-", "."], capture_output=True, check=True).stdout)
sbx.run("mkdir -p /work/app && tar -xzf /work/project.tgz -C /work/app")

# run the tests, streaming the output into this job's log as it is written
tests = sbx.spawn(["python3", "-m", "unittest", "-v"], cwd="/work/app")
for chunk in tests.output():
    sys.stdout.write(chunk.data)
exit_code = tests.wait().exit_code

print(f"\ntests exited with {exit_code}")  # tests exited with 0
```

**3. Pass or fail the build**

```bash title="CLI" run theme={null}
if [ "$EXIT_CODE" -eq 0 ]; then
  fibre delete "$SBX"
else
  # keep the sandbox to debug: it sleeps (no compute cost) until its lifetime ends
  echo "Tests failed. Debug in sandbox $SBX (label run=$RUN_ID)."
  exit 1
fi
```

```typescript title="TypeScript" run theme={null}
if (exitCode === 0) {
  await sbx.delete();
} else {
  // keep the sandbox to debug: it sleeps (no compute cost) until its lifetime ends
  console.log(`Tests failed. Debug in sandbox ${sbx.id} (label run=${runId}).`);
  process.exitCode = 1;
}
```

```python title="Python" run theme={null}
if exit_code == 0:
    sbx.delete()
else:
    # keep the sandbox to debug: it sleeps (no compute cost) until its lifetime ends
    print(f"Tests failed. Debug in sandbox {sbx.id} (label run={run_id}).")
    sys.exit(1)
```

## In GitHub Actions

```yaml title=".github/workflows/tests.yml" theme={null}
name: tests
on: [push, pull_request]

jobs:
  tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: 22 }
      - run: npm install @fibre-dev/sdk
      - run: node scripts/test-in-sandbox.mjs
        env:
          FIBRE_API_KEY: ${{ secrets.FIBRE_API_KEY }}
```

Give your CI its own API key, limited to the `sandboxes.*` scope and set to expire. That way it can only manage
sandboxes, and only for a limited time. See [API keys](https://docs.fibre.dev/get-started/api-keys.md).

## Debug a failure

When a run fails, the script keeps its sandbox instead of deleting it. That lets you look **inside the exact
machine where the tests failed**: its files, its installed packages and its logs. You can find it by its labels
and run commands in it from your terminal:

```bash title="Terminal" norun reason="debugs a sandbox from a failed run" theme={null}
SBX=$(curl -sS "$FIBRE_API_URL/v1/sandboxes?label.ci=tests&label.run=$RUN_ID" -H "Authorization: Bearer $FIBRE_API_KEY" | jq -r '.sandboxes[0].id')

curl -sS -X POST "$FIBRE_API_URL/v1/sandboxes/$SBX/exec" \
  -H "Authorization: Bearer $FIBRE_API_KEY" -H "Content-Type: application/json" \
  -d '{"command": ["sh", "-c", "cd /work/app && python3 -m unittest -v 2>&1 | tail -n 30"]}'
```

## Faster runs

Once the basic setup works, these changes make each run faster:

| Do | Gain |
| - | - |
| A [snapshot](https://docs.fibre.dev/setup/snapshots.md) with your dependencies installed | No install step in each run |
| Copy the snapshot per shard, [in parallel](https://docs.fibre.dev/use-cases/parallel.md) | Wall time divided by the number of shards |
| A bigger `size` for compile-heavy suites | More cores, same per-second billing |
| `needs: ["docker"]` | Tests that start databases in containers |

## Clean up

```bash title="CLI" run theme={null}
rm -rf project
```

```typescript title="TypeScript" run theme={null}
import { rmSync } from "node:fs";
rmSync("project", { recursive: true, force: true });
```

```python title="Python" run theme={null}
import shutil

shutil.rmtree("project", ignore_errors=True)
```

## Related

> [card] [Run commands](https://docs.fibre.dev/sandboxes/running-commands.md)
>
> How streaming output and exit codes work.

> [card] [Docker Compose](https://docs.fibre.dev/use-cases/docker.md)
>
> Run integration tests against real databases and services.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.