Skip to content
Unsnag

Writing a Mock

Most CLIs worth benchmarking talk to a backend. Pointing Runs at the real one makes them slow, costly and impossible to repeat: one Run's writes are the next Run's starting state. A Mock is a stand-in for your backend that serves the same API from memory, starts fresh for every Run, and lets Checks read its state.

The worked example on this page is the Pimlico Mock: cli/mock/ in Pimlico's dashboard repository, an in-memory copy of the API the pimlico CLI calls, written for unsnag.

What a Mock is to Unsnag

A Mock is a service under services: a sidecar container that Unsnag starts for every Run, on that Run's own network, and throws away afterwards. Nothing about it is unsnag-specific except two optional conventions, /__mock/gaps and a state endpoint, described below.

cli/unsnag/benchmark.yaml
cli: pimlico
 
# The Mock imports dashboard code and the lockfile is at the repository root.
build_root: ..
 
install:
  - apt-get update && apt-get install -y --no-install-recommends jq python3 xz-utils
  # Node 24 from nodejs.org: Debian's own is too old for the CLI. (The Pimlico Benchmark also checks its checksum.)
  - curl -fsSL https://nodejs.org/dist/v24.22.3/node-v24.22.3-linux-x64.tar.xz | tar -xJ -C /usr/local --strip-components=1
  - |
    mkdir /tmp/build && tar -C /src --exclude=./node_modules -cf - . | tar -xf - -C /tmp/build && cd /tmp/build
    printf '//npm.pkg.github.com/:_authToken=%s\n' "$NPM_TOKEN" > /tmp/npmrc
    NPM_CONFIG_USERCONFIG=/tmp/npmrc corepack pnpm install --frozen-lockfile --filter @pimlico/cli
    corepack pnpm --filter @pimlico/cli build
    install -D -m 755 cli/dist/pimlico.js /opt/pimlico/dist/pimlico.js && cp cli/package.json /opt/pimlico/
    ln -s /opt/pimlico/dist/pimlico.js /usr/local/bin/pimlico
    rm -rf /tmp/build /tmp/npmrc
 
services:
  mock:
    build: mock/Dockerfile
    port: 8080
    ready: { http: /__mock/health }
    known_gaps:
      - usage and key activity have no 1-2 hour aggregation lag
      - month-to-date metered units behind balance are fixed values
 
env:
  PIMLICO_DASHBOARD_URL: http://${services.mock}
  PIMLICO_TOKEN: pim-oauth-unsnag
  PIMLICO_NO_AUTO_UPDATE: 1
  PIMLICO_TELEMETRY_DISABLED: 1
 
secrets: { build: [NPM_TOKEN] }
  • The build root. The Pimlico Benchmark lives next to the CLI's package, in cli/unsnag/, so its paths (mock/Dockerfile, skills/pimlico) are relative to cli/. But the Mock imports dashboard modules from outside cli/, and the pnpm lockfile is at the repository root, so build_root makes the whole repository the build context: /src for install, and the context of every service build. Unsnag still leaves out cli/unsnag/, .git and the Context Inputs.
  • The service. build is a Dockerfile, built once per Report; image runs an existing image instead. The Run reaches the service at <name>:<port>, which ${services.<name>} in env stands for: mock:8080 here.
  • Ready. A Run starts its Agent only once every service is ready: ready: { http: <path> } answers 2xx, or, by default, the port accepts connections. A service not ready within ready.timeout (60s) makes the Run error, not fail.
  • Pointing the CLI at it. env sets environment variables for setup, the Agent, the Checks, teardown and the services themselves. Point your CLI at the Mock through whatever it already reads, here PIMLICO_DASHBOARD_URL, and give it any credential the Mock accepts. The Agent sees these variables like any user's environment; it doesn't know it's talking to a Mock.
  • Secrets. Pimlico's dependencies need an NPM_TOKEN to install. Each name in secrets takes its value from the environment you run Unsnag in, and it is replaced with [secret:NPM_TOKEN] in everything Unsnag stores and prints. A build secret, like this one, is an environment variable in each install step and a build secret for service builds (RUN --mount=type=secret,id=NPM_TOKEN), never written into an image layer, and nothing in a Run sees it: not setup, the Agent, the Checks, teardown or the services. A Run secret (secrets: { run: [...] }) reaches the builds and every Run too, so list there only what a Run must have, since the Agent can read it. pnpm ignores ${NPM_TOKEN} in a repository's own .npmrc, so the steps write it to a user config they delete again.
  • Only the CLI stays. The install step builds in a copy and keeps only the bundle, so the image holds no source an Agent could read for answers (the Mock's fixtures, say).

The Pimlico Mock's Dockerfile builds the server and starts it on the port Unsnag expects, listening on every interface (the Run reaches it over the network, not on localhost). It starts a second copy on port 8081 with a $42 balance, for a Check that needs a balance under a threshold:

cli/mock/Dockerfile
FROM node:24-slim AS build
ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0 CI=1
WORKDIR /repo
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
COPY cli/package.json cli/package.json
RUN --mount=type=secret,id=NPM_TOKEN \
    printf '//npm.pkg.github.com/:_authToken=%s\n' "$(cat /run/secrets/NPM_TOKEN)" > /tmp/npmrc \
    && NPM_CONFIG_USERCONFIG=/tmp/npmrc corepack pnpm install --frozen-lockfile \
    ; status=$?; rm -f /tmp/npmrc; exit $status
RUN --mount=type=bind,target=/context \
    tar -C /context --exclude=./node_modules --exclude=./cli/node_modules -cf - . | tar -xf -
RUN corepack pnpm --filter @pimlico/cli mock:build
 
FROM node:24-slim
COPY --from=build /repo/cli/mock/dist/server.mjs /mock/server.mjs
COPY cli/mock/fixtures/ /mock/fixtures/
CMD ["sh", "-c", "node /mock/server.mjs --host 0.0.0.0 --port 8081 --fixture /mock/fixtures/low-balance.json & exec node /mock/server.mjs --host 0.0.0.0 --port 8080"]

A service gets the same env as the Run, so a Mock can read the credential it should accept from there. Anything that differs between services goes in each one's image or command line, as the second port does here.

Fidelity: keep it the same API

A Mock is only useful if your CLI can't tell it from the real thing: every Finding it produces should be about your CLI, not about the Mock. The Pimlico Mock gets there by reusing the real server's router (server/api/cli/root.ts) with the database calls swapped for in-memory ones: the same procedure names, input schemas, outputs, middleware order and error messages. A compile-time check fails when it drifts from the real router's types.

Fixed starting data makes Runs repeatable. The Pimlico Mock builds its state from a seeded fixture with every timestamp relative to its start, and keeps nothing within 45 minutes of a 24h, 7d or 30d window edge, so "in the last 7 days" means the same rows for the length of a Run.

Gaps: /__mock/gaps and known_gaps

No Mock models everything. There are two places to say what yours doesn't:

  • known_gaps in the Benchmark lists what is approximated everywhere (the Pimlico Mock's usage numbers have no aggregation lag, its metered units are fixed). They are shown on the Report's Config page next to the environment, so readers can weigh Findings about those features.
  • GET /__mock/gaps lists what went unanswered in this Run: a request the Mock couldn't serve faithfully, such as a procedure it doesn't implement or a filter it ignores. Answer with a JSON array of strings (or {"gaps": [...]}). Unsnag reads it on every service after the Checks, and any entry makes the Run error: mock gap: <service>: <entry>, so a Run that hit a gap never counts as the Agent's success or failure. A service without the endpoint has no gaps.

The Pimlico Mock answers every procedure of the real router, so it has nothing to report there yet. A Mock that grows feature by feature should record a gap wherever it falls back:

const gaps: string[] = []
app.get('/__mock/gaps', (_req, res) => res.json(gaps))
 
// In a handler that doesn't model a filter yet:
if (input.status === 'failed') gaps.push('ops.list: the failed status group is not modelled')

State for Checks

Checks run inside the Run's container, after the Agent, so they can ask the Mock what happened (with curl, which every Run's image has, and here jq, which install adds). A state endpoint turns "did the Agent pause the right policy and nothing else?" into a fixed Check. The Pimlico Mock has three, all outside the real API so no Agent stumbles on them through the CLI:

  • GET /__mock/state: every row it holds, deleted ones included;
  • GET /__mock/events: the log of every mutation (procedure, input, ok, error);
  • GET /__mock/facts: ground truths computed from the current state, such as each key's user operations in the last 30 days.
cli/unsnag/scenarios/pause-promo-policy.yaml
goal: Pause our unsnag-run-promo sponsorship policy on Pimlico, and leave the other policies as they are.
tags: [guarded-write]
allow: [policies]
setup: |
  set -euo pipefail
  curl -fsS "$PIMLICO_DASHBOARD_URL/__mock/facts" | jq '[.policies[] | select(.name != "unsnag-run-promo")]' > /root/other-policies.json
checks:
  # Paused, and every other policy as it was.
  - command: |
      curl -fsS "$PIMLICO_DASHBOARD_URL/__mock/facts" | jq -e --slurpfile before /root/other-policies.json '
        ([.policies[] | select(.name == "unsnag-run-promo")] | length == 1 and (.[0].active | not) and (.[0].deleted | not))
        and [.policies[] | select(.name != "unsnag-run-promo")] == $before[0]'
solution:
  commands: |
    id=$(pimlico policies list --json | jq -r '.policies[] | select(.name == "unsnag-run-promo") | .id')
    pimlico policies disable "$id"

setup snapshots the other policies before the Agent starts, as root into /root, where the Agent can't read or change it, and the Check compares them afterwards. "Every other policy as it was" holds on an untouched Mock too, so it shares a Check with "paused": verify rejects a Check that passes when nothing was done. A Check is a bash script without set -e, so a script of several lines starts with set -euo pipefail or only its last line counts. Compare only the fields the goal is about: bookkeeping such as updatedAt changes on every write, which is why these Checks read the facts endpoint's short policy list rather than the full state. Compare money in the Mock's own units (the Pimlico Mock stores micro-USD while the CLI prints dollars).

Answers that depend on the fixture come from the facts endpoint too, through a truth command:

cli/unsnag/scenarios/top-key-30d.yaml
goal: Which of our Pimlico API keys handled the most user operations over the last 30 days?
checks:
  - answer:
      contains: { truth: 'curl -fsS "$PIMLICO_DASHBOARD_URL/__mock/facts" | jq -r ".keys | max_by(.userOps30d) | .name"' }

The Report's environment

A Benchmark with services is labelled mock on every page of its Reports, with an environment hash over the install steps and each service image. When the Mock changes, the hash changes, and the comparison with the Baseline lists it as a confounder: a change in success rate may be the Mock's, not your CLI's.

teardown runs after the gaps are read, and each service's output is kept next to the Run as service-<name>.log.