WBX Sandbox
Tutorials

Repository tests in CI

Run your test suite in a clean WBX sandbox from any CI system: the CI step submits a background job, the job checks out the exact commit and runs the tests, and you get a short test summary in the CI log – plus, if you want, a signed webhook to your own server when the job ends.

What you'll build

  • A CI script (Python, TypeScript or plain curl) that submits the job, waits, prints the recognised test results and fails the CI step when the tests fail.
  • A GitHub Actions workflow that runs it on every push and pull request (any other CI works the same way).
  • Optionally, a small webhook receiver that checks the HMAC signature of the job.finished event – for chat notifications, commit statuses or dashboards.

What you need

  • A WBX Sandbox API key, stored as a CI secret WBXSANDBOX_API_KEY.
  • A repository with Python tests (requirements.txt and pytest). For other languages change the install and test commands – the log digest also recognises go test, Jest, Vitest, cargo, PHPUnit, JUnit and mocha.
  • For the webhook: a server with a public https:// address. About 20 minutes.

The quickest way on GitHub: the WBX Sandbox Run action

On GitHub you do not need a script: the WBX Sandbox Run action submits the job, downloads the repository at the workflow's commit into the sandbox, streams the log into the step, downloads the result files and the signed receipt and fails the step when the tests fail.

# .github/workflows/tests.yml
name: tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: WBX-Sandbox/run@v1
        id: wbx
        with:
          api-key: ${{ secrets.WBXSANDBOX_API_KEY }}
          template: base
          command: pip install -r requirements.txt && pytest --junitxml=report.xml
          artifacts: report.xml
          timeout: "900"
          max-cost: "0.20"   # for CZK use "1.50"
      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: wbx-results
          path: ${{ steps.wbx.outputs.artifacts-path }}

All inputs (network allowlist, compute class, environment variables, working directory) are described in the action's README. The steps below do the same from any CI system with a short script.

Steps

  1. The command the job runs

    The job starts in a fresh sandbox in /home/user, fetches exactly the commit CI is testing and runs the tests. Only output/ is kept as result files (here the JUnit report); everything else is deleted with the sandbox. Values passed in env are masked in the log and not stored after the job ends.

    set -e
    mkdir -p output
    git init -q repo && cd repo
    git remote add origin "$REPO_URL"
    git fetch -q --depth 1 origin "$COMMIT"
    git checkout -q FETCH_HEAD
    pip install -q -r requirements.txt pytest
    pytest -q --junitxml=../output/junit.xml

    Private repository? Pass a read-only token in env (for example GIT_TOKEN) and use https://x-access-token:$GIT_TOKEN@github.com/OWNER/REPO.git as REPO_URL inside the command.

  2. The CI script

    # ci/wbx_tests.py – needs: pip install wbxsandbox
    import os
    import sys
    from wbxsandbox import run_job
    
    COMMAND = """set -e
    mkdir -p output
    git init -q repo && cd repo
    git remote add origin "$REPO_URL"
    git fetch -q --depth 1 origin "$COMMIT"
    git checkout -q FETCH_HEAD
    pip install -q -r requirements.txt pytest
    pytest -q --junitxml=../output/junit.xml"""
    
    repo = os.environ["GITHUB_REPOSITORY"]                     # owner/name, set by GitHub Actions
    sha = os.environ["GITHUB_SHA"]
    job = run_job(
        command=COMMAND, template="base", timeout_seconds=1800,
        env={"REPO_URL": f"https://github.com/{repo}.git", "COMMIT": sha},
        artifacts=["output/"],
        max_cost=os.environ.get("WBX_MAX_COST", "0.20"),         # in your billing currency (for CZK use "1.50")
        webhook_url=os.environ.get("WBX_WEBHOOK_URL"),           # optional: https://… of your receiver
        idempotency_key=f"ci-{sha}-{os.environ.get('GITHUB_RUN_ATTEMPT', '1')}",
        metadata={"repo": repo, "commit": sha[:12]},
    )
    print("WBX job", job.id)
    
    job.wait(timeout=2100)                                    # a bit longer than timeout_seconds
    print(job.digest("summary")["text"])                       # test results, errors, end of the log
    s = job.summary()
    print("status:", s["status"], "| exit code:", s.get("exit_code"), "| cost:", s.get("cost"))
    sys.exit(0 if s["status"] == "completed" else 1)
    // ci/wbx_tests.mts – needs: npm install wbxsandbox (an ES module – top-level await)
    import { WBX } from "wbxsandbox";
    
    const COMMAND = `set -e
    mkdir -p output
    git init -q repo && cd repo
    git remote add origin "$REPO_URL"
    git fetch -q --depth 1 origin "$COMMIT"
    git checkout -q FETCH_HEAD
    pip install -q -r requirements.txt pytest
    pytest -q --junitxml=../output/junit.xml`;
    
    const repo = process.env.GITHUB_REPOSITORY!; // owner/name, set by GitHub Actions
    const sha = process.env.GITHUB_SHA!;
    const wbx = new WBX();
    const job = await wbx.jobs.create({
      command: COMMAND, template: "base", timeoutSeconds: 1800,
      env: { REPO_URL: `https://github.com/${repo}.git`, COMMIT: sha },
      artifacts: ["output/"],
      maxCost: process.env.WBX_MAX_COST ?? "0.20",          // in your billing currency (for CZK use "1.50")
      webhookUrl: process.env.WBX_WEBHOOK_URL || undefined,  // optional: https://… of your receiver
      idempotencyKey: `ci-${sha}-${process.env.GITHUB_RUN_ATTEMPT ?? "1"}`,
      metadata: { repo, commit: sha.slice(0, 12) },
    });
    console.log("WBX job", job.id);
    
    await job.wait({ timeoutMs: 2_100_000 }); // a bit longer than timeoutSeconds
    console.log((await job.digest({ mode: "summary" })).text); // test results, errors, end of the log
    const s = await job.summary();
    console.log("status:", s.status, "| exit code:", s.exit_code, "| cost:", s.cost);
    process.exit(s.status === "completed" ? 0 : 1);
    # ci/wbx_tests.sh – needs curl and jq (both on GitHub's ubuntu runners)
    set -euo pipefail
    H=(-H "Authorization: Bearer $WBXSANDBOX_API_KEY" -H "Content-Type: application/json")
    API=https://sandbox.wbx.cz
    CMD='set -e
    mkdir -p output
    git init -q repo && cd repo
    git remote add origin "$REPO_URL"
    git fetch -q --depth 1 origin "$COMMIT"
    git checkout -q FETCH_HEAD
    pip install -q -r requirements.txt pytest
    pytest -q --junitxml=../output/junit.xml'
    
    JOB=$(jq -n --arg cmd "$CMD" --arg repo "https://github.com/$GITHUB_REPOSITORY.git" --arg sha "$GITHUB_SHA" \
      --arg att "${GITHUB_RUN_ATTEMPT:-1}" \
      '{command: $cmd, template: "base", timeout_s: 1800, artifacts: ["output/"], max_cost: "0.20",
        env: {REPO_URL: $repo, COMMIT: $sha}, idempotency_key: ("ci-" + $sha + "-" + $att)}' |
      curl -sf -X POST $API/v1/jobs "${H[@]}" -d @- | jq -r .id)   # for CZK use max_cost "1.50"
    echo "WBX job $JOB"
    
    until curl -sf -X POST $API/v1/jobs/wait "${H[@]}" -d "{\"job_ids\": [\"$JOB\"], \"timeout_s\": 60}" | jq -e .done >/dev/null; do :; done
    curl -sf "$API/v1/jobs/$JOB/logs?mode=summary" "${H[@]}" | jq -r .text
    STATUS=$(curl -sf $API/v1/jobs/$JOB/summary "${H[@]}" | jq -r .status)
    echo "status: $STATUS"
    [ "$STATUS" = completed ]

    max_cost is in your account's billing currency. The job is accepted only if its worst case fits: 1800 s of tests plus about 7 minutes reserved for starting the sandbox and uploading results, on the 2 vCPU / 512 MB base template – a little under 0.05 in EUR or USD, about 1 in CZK. That is why 0.20 suits EUR and USD; for CZK use 1.50.

  3. The workflow

    # .github/workflows/wbx-tests.yml
    name: Tests in WBX Sandbox
    on: [push, pull_request]
    jobs:
      test:
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4            # only for ci/wbx_tests.py – the tests run in WBX
          - uses: actions/setup-python@v5
            with:
              python-version: "3.12"
          - run: pip install wbxsandbox
          - run: python ci/wbx_tests.py
            env:
              WBXSANDBOX_API_KEY: ${{ secrets.WBXSANDBOX_API_KEY }}
              # WBX_WEBHOOK_URL: https://ci-hooks.example.com/wbx

    GitHub does not give secrets to workflows started from pull requests of forks, so those runs cannot submit jobs. For a TypeScript script use actions/setup-node and npx tsx ci/wbx_tests.mts.

  4. Optional: receive the signed webhook

    With webhook_url set, WBX sends a POST with {"event": "job.finished", "id": "job_…", "created_at": …, "data": {…the job summary…}} when the job ends. The header X-WBX-Signature: t=<unix time>,v1=<hex> is an HMAC-SHA256 of <t>.<raw body> with your account's webhook secret; the SDK helpers check it and reject timestamps older than 5 minutes. Get the secret once with webhook_secret() (Python), wbx.webhooks.secret() (TypeScript) or GET /v1/webhooks/secret, and store it on the server.

    # webhook_receiver.py – put it behind your HTTPS reverse proxy
    import json
    import os
    from http.server import BaseHTTPRequestHandler, HTTPServer
    from wbxsandbox import verify_webhook
    
    SECRET = os.environ["WBX_WEBHOOK_SECRET"]
    
    class Hook(BaseHTTPRequestHandler):
        def do_POST(self):
            body = self.rfile.read(int(self.headers.get("Content-Length", 0)))   # the raw bytes
            if not verify_webhook(SECRET, body, self.headers.get("X-WBX-Signature", "")):
                self.send_response(401)
                self.end_headers()
                return
            event = json.loads(body)
            if event["event"] == "job.finished":
                d = event["data"]
                print(d["id"], d["status"], d.get("exit_code"), d.get("cost"))
                # here: set a commit status, post to chat, … (answer within 10 s)
            self.send_response(204)
            self.end_headers()
    
    HTTPServer(("0.0.0.0", 8080), Hook).serve_forever()
    // webhook_receiver.mts – put it behind your HTTPS reverse proxy
    import { createServer } from "node:http";
    import { verifyWebhook } from "wbxsandbox";
    
    const SECRET = process.env.WBX_WEBHOOK_SECRET!;
    
    createServer(async (req, res) => {
      const chunks: Buffer[] = [];
      for await (const c of req) chunks.push(c as Buffer);
      const body = Buffer.concat(chunks); // the raw bytes
      const sig = req.headers["x-wbx-signature"];
      if (req.method !== "POST" || !(await verifyWebhook(SECRET, body, typeof sig === "string" ? sig : undefined))) {
        res.writeHead(401).end();
        return;
      }
      const event = JSON.parse(body.toString("utf8"));
      if (event.event === "job.finished") {
        const d = event.data;
        console.log(d.id, d.status, d.exit_code, d.cost);
        // here: set a commit status, post to chat, … (answer within 10 s)
      }
      res.writeHead(204).end();
    }).listen(8080);

    Deliveries that do not get a 2xx answer within 10 seconds are retried after 10 s, 1 min, 5 min, 30 min, 2 h, 6 h and 12 h, so the same event can arrive twice – ignore repeats by the job ID in the body (data.id). X-WBX-Delivery is different on every attempt (<job ID>.<attempt>), so it is not a deduplication key on its own – only the part before the dot is. The job's state in the API stays the source of truth.

How to tell it works

  • The CI log shows WBX job job_…, then a digest with lines such as the pytest summary, then status: completed – and the CI step is green.
  • Break a test on purpose: the digest shows the failing test with its error, the status is failed and the CI step turns red.
  • The portal lists the job under Jobs with its full log and the output/junit.xml result file.
  • Your receiver prints one line per finished job; a request with a wrong signature gets 401.

Common problems

Status, code or messageMeaning and fix
401The CI secret is missing or wrong (for example a fork pull request, which gets no secrets).
400 invalid_webhookwebhook_url must be https:// on a public address, without a user name or password.
422 budget_too_lowThe worst case is above max_cost: (timeout_s + about 7 minutes reserved for start and result upload) × the number of attempts, at your class price. The message says which timeout fits. Remember the limit is in your billing currency.
402 budget_exceededYour monthly or daily budget is used up – raise it under Billing.
fatal: couldn't find remote ref in the logThe commit cannot be fetched – the repository is private (pass a token) or the commit was force-pushed away.
Error nonzero_exitThe install or the tests failed – that is the digest you are looking at.
Job expired, error timeoutThe tests ran longer than timeout_seconds and were stopped (the job ends as expired, not failed, so the script above exits with 1). Raise it (and max_cost), or split the suite into a batch.
Receiver answers 401 to real eventsThe body was changed before checking (parsed and re-serialised, or decoded) or the secret is old (rotated). Check the raw bytes with the current secret.

Next steps