Reeve Docs

Docs / Development

Testing

The tiers

Tier Runner Subject May assume
Backend unit xUnit with FluentAssertions and NSubstitute One class and its collaborators Nothing about the database provider. Much of this tier runs on the in-memory provider
Backend integration (API) xUnit over the real application The whole stack Containerised PostgreSQL/TimescaleDB, Redis and MQTT. In-memory or file-database substitutes for persistence or session storage are not allowed
Backend integration (infrastructure) xUnit The persistence layer A throwaway database force-dropped and recreated per test, with the real migration applied
Frontend unit Vitest with Testing Library and a request-mocking service worker Components and pure modules One shared module registry per worker. Charts do not render
Mobile unit xUnit against the platform-free core project only View models and services No page, host, activity or container can be constructed
End-to-end Playwright against a real stack Business outcomes Serial execution, one worker, database reset before each test

Continuous integration (.github/workflows/ci.yml) runs the unit tiers and the integration tiers on every push to main and on every pull request. The full Playwright suite runs on demand in .github/workflows/e2e.yml (Actions tab). Locally, run the tests your change can reach; getting started has the commands.

Testing rules

What a test proves

  • Write the failing test first and confirm it fails for the right reason. A refusal test pins the specific failure (error code or exception type), or it passes as soon as the code breaks in a different way.
  • Cover the negative case next to the happy path: a check that still passes when the enforcement is deleted proves nothing.
  • Assert the full expected set when you assert that something is absent, or the assertion holds for any input.
  • A test executes the production code. One that re-implements the production predicate cannot go red when production changes.
  • A test of a Redis- or PostgreSQL-backed store runs against the real store. A test double for a collaborator is fine.
  • Golden constants stay as they are. New behaviour gets new, non-golden cases.

Persistence and schema

  • A test context that applies a migration must register the TimescaleDB provider, or schema creation throws on the first hypertable operation even though the model builds.
  • After a change to entity shape, mapping or keys, run the full unit project and the integration tiers. The unit tier cannot see provider-level breakage.
  • The idempotent migration script is proved by generating it through the design-time factory and running it twice against an empty database: the first run provisions every migration and the second is a no-op. Applying migrations the normal way does not exercise that path.
  • A migration that inserts seed rows must be declared in the reset snapshot list used by the API test factory.

Time

  • Test time-dependent behaviour by setting or advancing the injectable clock, never by sleeping. Fixed sleeps waiting for asynchronous persistence are a flake source. Poll on the observable condition instead.
  • Return the current instant from a substitute clock rather than a captured value, or it goes stale during the test.
  • A poll that waits for a bare status can match the state that existed before the command was issued. Poll for the transition, or for a value only the command could produce.

End to end

  • A functional spec proves its outcome through an observable system boundary: backend state, virtual-device state, a delivered mail message, an audit entry, an exported file, a broker topic payload or an execution log. A re-render after a request proves nothing.
  • Feature specs carry no skip markers. A conditional skip on a genuinely missing prerequisite such as a credential is fine. A spec that is unconditionally skipped is a deferral, not coverage.
  • Bring the stack up through deploy/e2e/up.sh, never a bare compose command. Compose alone gives the backend no device source, so every device-bound spec fails in setup against a stack whose containers are all healthy.
  • Containers carry a per-stack name prefix so two stacks on one host cannot claim each other's containers.
  • Read the machine-readable run report rather than the JUnit output when triaging. JUnit records a test that passed on retry as a plain pass.

Frontend

  • Run the suite in full, with no name filter. It runs without per-file isolation and shares one module registry per worker, so a narrow run hides cross-file mock races that show only in a full pass. If the full run runs out of memory, reduce concurrency or split the test file.
  • Do not mock a shared module at file level, because the mock leaks into other files in load order. Assert against the real component with a real store, or use per-test request handlers.
  • A module mocked globally in the setup file must be implemented with plain functions, not spies. Mocks are restored between tests, and a restored spy loses its implementation for every later file in that worker. Map and video-player libraries are mocked this way. Anything about real tiles, real fitting or real playback belongs in a browser test.
  • Release fake timers after every test that installs them.
  • The type check is a project-references build. A no-emit invocation uses different module resolution and passes while the build fails. Run the production build after the tests land and again after the final rebase.

Mobile

  • Tests target the platform-free core project. The UI head cannot be instantiated headlessly, so its proof is the head build plus a pass on a device.
  • Do not modify the shared mobile test doubles. Add fakes in your own test file.
  • Markup defects compile clean, pass the whole machine suite, then throw at runtime. The build used for the device pass must compile its markup, and a plain Debug build compiles none.

Filters and coverage

  • A test filter that excludes integration tests by name also drops any unit project whose class names contain that word. Check what a filter selected before trusting a green run.
  • Coverage excludes migrations and the program entry point. There is no coverage threshold.

Running the end-to-end suite

The stack is TimescaleDB, a test MQTT broker (built from deploy/test-broker), Redis, a mail catcher, a trace collector, the virtual-devices simulator and the backend running the E2E image under the end-to-end environment. deploy/docker-compose.e2e.yml defines it.

The E2E image. backend/Dockerfile has a target e2e: the production stage plus Reeve.Api.E2E.dll, which holds the test controller, the settable clock and the plugin release-asset fixture. The suite therefore runs the bits that ship, plus that assembly. A build without --target produces the production image, which does not contain it.

At startup the host adds the E2E surface when, and only when, the environment is E2E. It loads Reeve.Api.E2E.dll from the application directory and lets the module that assembly declares register its controller, replace the clock and put the asset fixture in front of the github HTTP client. Under E2E with the assembly missing, startup refuses with E2ESurfaceMissingException, so a production image cannot be switched into the end-to-end environment. Outside E2E the assembly is ignored even when present. The in-process integration tests reference the project, so a factory under E2E gets the same surface.

Running it locally

You need Docker with Compose, Node.js 26 and oras. From the repository root:

deploy/e2e/up.sh              # mirror artifacts, fetch the device source, build and start the stack
deploy/e2e/up.sh --no-build   # reuse the existing backend image

cd frontend
npm ci
npm run e2e:install           # browsers, first time only
npm run e2e                   # everything
npm run e2e:smoke             # the critical path
npm run e2e:functional        # the outcome-proving suite
npm run e2e:ui                # interactive
npm run e2e:debug             # step-through

up.sh exists because two things must happen before compose starts. The virtual-devices plugin artifact and its simulator image are mirrored into a local registry, and that mirror is the tier's device source. The remaining bind-mounted plugin binary is fetched. Skipping either leaves a stack that reports every container healthy and fails every device-bound spec in setup. up.sh then waits for /api/auth/login-options to answer.

Stop the stack with docker compose -f deploy/docker-compose.e2e.yml down, and read the backend's log with the same file and logs backend.

The workload specs attach to the compose network and call the backend by container name, so the compose project name must match the variables they read. Set COMPOSE_PROJECT_NAME=reeve-e2e for up.sh and every later compose command, and point the specs at that network:

cd frontend
E2E_ADMIN_USERNAME=admin E2E_ADMIN_PASSWORD='admin123!' E2E_STACK_PREFIX=reeve-e2e \
  E2E_COMPOSE_NETWORK=reeve-e2e_default E2E_WORKLOAD_GATEWAY_URL=ws://reeve-e2e-backend:8080 \
  E2E_APP_BASE_URL=http://127.0.0.1:5173 E2E_API_BASE_URL=http://127.0.0.1:5000 \
  E2E_MAILHOG_BASE_URL=http://127.0.0.1:8025 \
  E2E_MQTT_URL=mqtt://127.0.0.1:1885 E2E_MQTT_USERNAME=reeve E2E_MQTT_PASSWORD=reeve \
  E2E_RUNNER_ALIAS=host.docker.internal E2E_BLUEPRINT_SERVER_HOST=host.docker.internal \
  E2E_WEBHOOK_RECEIVER_HOST=host.docker.internal \
  E2E_VIRTUAL_DEVICES_BASE_URL=http://127.0.0.1:5179 \
  npx playwright test           # or: <spec path>, --grep @smoke

Without E2E_ADMIN_PASSWORD most specs skip and the rest throw. Two specs default the broker login to reeve/reeve, which the test broker accepts; the E2E_MQTT_* variables override it. The compose file gives the backend container host.docker.internal:host-gateway in extra_hosts, so the name resolves on Linux without further setup.

Other settings in frontend/playwright.config.ts:

Variable Default Effect
E2E_APP_BASE_URL http://127.0.0.1:5173 Where the app is served. Playwright builds and previews the SPA there unless E2E_SKIP_FRONTEND_SERVER is set
E2E_API_BASE_URL http://127.0.0.1:5000 The backend the preview proxies to
E2E_TEST_TIMEOUT_MS 60 s, 180 s when CI is set Per-test timeout
E2E_EXPECT_TIMEOUT_MS 15 s, 30 s when CI is set Timeout of each expect
E2E_GLOBAL_TIMEOUT_MS none, 3.25 h when CI is set Whole-run timeout
E2E_RUN_ID local Suffix on test data, so two runs cannot collide

With CI set, forbidOnly is on. The browsers need their system libraries. npm run e2e:install runs playwright install --with-deps.

In GitHub Actions

.github/workflows/e2e.yml runs the same steps on demand from the Actions tab (workflow_dispatch). It pulls the virtual-devices simulator image, runs deploy/e2e/up.sh, which builds the images, starts the stack and waits for /api/auth/login-options, installs the frontend and a Chromium build, and runs the Playwright suite.

Support helpers live in frontend/e2e/support/: an authenticated API client, bootstrap credential handling, UI helpers, broker publishing, virtual-device seeding and assertions, notification and mail helpers, workflow builders and the clock control.

The visual harness

frontend/e2e/visual/ is a Playwright project that is not part of npm run e2e. It photographs the built SPA served by vite preview, which proxies /api and /hubs (websockets included, because the camera's WebRTC signalling is one) to a real backend running the virtual-devices plugin. Nothing is answered by a route handler. It is for changes to what a screen looks like: capture a set before and after a change against one seeding, then compare.

tools/visual-stack.sh up       # start a compose-e2e stack for this checkout
tools/visual-stack.sh seed     # fill it with a fixed household
tools/visual.sh capture --out <dir> [--only start,scenes.basic] [--theme dark] [--viewports desktop,phone]
tools/visual.sh compare <before-dir> <after-dir> --out <dir>   # writes <dir>/compare.html
tools/visual-stack.sh down

up derives the compose project name (reeve-visual-<checkout name>-<hash of its path>) and a block of twelve ports from the checkout path, so two checkouts never share a database. VISUAL_PORT_BASE moves the block if two paths collide. The backend image is tagged reeve-visual-backend:<hash of the files the Dockerfile copies>. up builds it when missing and reuses it otherwise, E2E_BACKEND_IMAGE overrides the tag, and tools/visual-stack.sh prune removes tags no container uses. The stack needs about 3.5 GB while up, and its mirror and simulator ports are published on the host, so keep the machine off untrusted networks while it runs.

The seed takes about three minutes. It empties the simulator and the database, pins the backend's test clock to a fixed day, creates the devices, scenes, rooms, two accounts (anna in Basic mode and tom in Advanced mode) and five automations each, replays 24 hourly steps of device history through the real command path, then waits until the physical-device details and the workload session diagnostics have stayed unchanged for 35 seconds. A capture never seeds. It reads the world from the stack and refuses a stack seeded by a different version of the harness. A seed stamp in the accounts' preferences and a stamp.json in each capture directory let compare warn when its two sets come from different seedings.

A screen that writes (a restore hook, such as the rename screens) is captured only when named in --only, one worker at a time, and undoes its writes through the API afterwards. A screen that changes the account (the dashboard-rooms pair) declares cleanup, which runs before and after it, and a group, whose screens run one after another in a single worker.

What fails a capture. A page error, an ErrorBoundary, a blank page, text saying a page, device or resource is not found, and any /api/ answer of 400 or more (the sign-in page's own 401 excepted). A failed screen is not photographed, and a capture does not retry.

Determinism. The browser clock is fixed to the backend's test clock, and the seed puts every timestamp at a fixed offset from it, so "x min ago" and "Last seen" read the same on every capture. The only mask is on ids: every UUID in the page text becomes one placeholder of the same shape, because the backend mints them at random.

Drawers. A Basic drawer scrolls inside itself, so a screen with fitContent waits until the drawer's height has held for two seconds, grows the viewport by what is missing and photographs the whole panel. A drawer taller than 8000 px fails the capture.

The launch set. Screens with a launch- id, plus login and change-password, form the launch screenshot set. A screen's heights cuts the picture to the viewport, and 'content' grows it to the page.

The screens, viewports and file names are defined in frontend/e2e/visual/screens.ts, and the static mockups the harness compares against are in frontend/e2e/visual/mockups/. Runs are bounded by VISUAL_TIMEOUT_MIN (default 60).

Host roll harness

tools/roll-harness/roll.py rolls the three-replica stack (deploy/docker-compose.yml, docker-compose.multi.yml and docker-compose.roll.yml) from an old release to the candidate, one replica at a time, and runs six checks on every step. No CI job runs it. A contributor starts it by hand before changing anything that has to survive a rolling upgrade. It takes about 35 minutes forwards only and 55 as a round trip.

Running it. It needs Docker with Compose and Buildx, oras, a full clone with the release tags, and the WASM fixtures under backend/tests/Fixtures/wasm/. BACKEND_IMAGE is the registry path of the backend image without a tag, ghcr.io/reeve-iot/reeve-backend for the published releases.

export BACKEND_IMAGE=ghcr.io/reeve-iot/reeve-backend
python3 tools/roll-pair.py --check-image | tee roll-pair.txt
python3 tools/roll-harness/roll.py --project reeve-roll-local --pair-file roll-pair.txt --out roll-out

The driver joins the stack's network through deploy/e2e/ci-join-network.sh, so it expects to run in a container on the same Docker daemon. ROLL_JOIN_NETWORK=0 skips that step. --self-test on either script runs its own unit checks without a stack.

Pair. tools/roll-pair.py picks the old release and the mode, and refuses a pair with a named reason: the old core is below the candidate's, or equal with the old commit a strict ancestor of the candidate's. Releases are tags vX.Y.Z, and release candidates are never the old side.

State Old side Mode
ReeveRollFrom equals the candidate's own core and no other release carries it (a full-stop window: the release that sets ReeveRollFrom to its own core, before it is tagged) none none: the driver prints the reason, starts no stack and exits 0
ReeveRollFrom names a released build below the candidate v<RollFrom> round trip: replace r3, r2, r1, then back r1, r2, r3
ReeveRollFrom names a missing tag, or a core above the candidate's refused (exit 1)
Proof run, not on a tag: ROLL_OLD_REF=v1.0.0 and ROLL_FROM_OVERRIDE=1.0.0 the named release forwards only. The candidate is built with that roll-from, which must be at most the old release's core and the candidate's

The driver builds the candidate from the commit (tools/roll-harness/build-candidate.sh, REEVE_ROLL_FROM build argument), so it is the same source and Dockerfile as the release image but not the release bytes. A candidate stamped with a ReeveRollFrom above the old replicas' core is the refused path. The host's own tests cover that refusal, and the harness does not build it.

Checks. A check fails only on a fact that exists when the replica is active, or on the answer of a command. None polls for an absence.

# Check Observer
1 sign-in and configuration write a cookie issued by one replica is accepted by the others. A room, a helper and an automation written through a replica of each build answer 201 and are read back once on the other replicas
2 an event fires once a StateChange trigger on the MQTT fixture's switch. Per step the fire claim keys are cleared, OFF then ON is published, and exactly one run and one holder-claim:fire:* key are expected. The stack widens Workflow:Engine:FireDedupWindowSeconds to 120 s so the key outlives the wait for the run
3 one owner per unit kind the candidate's unit: capabilities contain every baseline one. Each reeve_cluster.owned row of a baseline kind has a live owner holding its capability
4 plugin update on a mixed step an update of a deployment-bearing plugin answers 409 host_builds_mixed on a replica of each build. After the leg's last replacement the same call is accepted
5 parameter encryption a fresh sentinel written to a workload parameter is absent from the stored rows and enc:v1: is present (a direct read)
6 outsider refused a candidate process started with --roll-from-for-testing 99.0.0 exits 76 and records a [window] reason with no consecutive failure and no member row. /api/system/status shows the replica as Refused with its refusalReason

The driver exits 1 when a check fails and 2 on an infrastructure fault or an incomplete step. A check that did not run is a failure.

The fixtures are offline. A registry:2 service serves WASM plugins: an MQTT switch driver and three copies of the peer-service module that declare a deployment. Two copies are updated by check 4, and the third is never updated, so check 5's parameter write is not refused by a pending update. An MQTT message is the only simulated input. The deployment copies run peer-service because its describe() echoes no permissions, so a manifest declaring workloads.deploy is not refused by the echo cross-check.

Test-only endpoints

These exist only on the E2E image under the end-to-end environment (see the E2E image). The production image does not contain the controller, so no configuration maps them there. The E2E image booted under any other environment ignores the assembly, which makes every one of them a silent 404, so fixtures should smoke-check one before running.

Endpoint Effect
POST /api/test/reset Truncates application and auth data except the migration ledger, clears cached sessions, disables the preserved plugin instance rows (the platform-owned one aside) so the recovery sweep restarts nothing, stops running plugin instances so no stale loop writes device metadata, waits for the outage records those stops queue, and leaves each spec to enable the instance it needs. It then re-runs the initializer to restore migration-seeded rows and the bootstrap administrator, and resets the clock
POST /api/test/clock Sets the clock to an absolute instant, body { "nowUtc": "…" }
POST /api/test/time/advance?seconds=N Advances the clock

POST /api/workflows/{id}/execute is not test-only. It runs a workflow without a trigger for any caller holding the automation-management permission, and defaults to debug mode so execution logs and step errors are available.

The test clock is frozen by default, so the session-outage pass never marks a source in an end-to-end run: every LastSeenAtUtc equals the pass's read instant and the bound is strict.

Determinism

  • One worker, no parallelism. The database is reset before each test.
  • Each run uses a unique run identifier so data from two runs cannot collide, and a per-stack container prefix so two stacks on one host cannot either.
  • Health probes are /health/live and /health/ready returning plain-text Healthy. Every unmatched route, including a bare /health, returns RFC 7807 application/problem+json carrying a trace id. See observability.

Failure modes

Symptom Cause Fix
Every device-bound spec fails in setup, all containers healthy The stack was brought up with a bare compose command, so there is no device source Tear down and use deploy/e2e/up.sh
Every test-only endpoint returns 404 The end-to-end environment was declared after the backend booted Restart the backend container
The backend refuses to start with E2ESurfaceMissingException The stack runs the production image under the end-to-end environment Build the image with --target e2e
A long-lived stack starts failing A stale simulator health record, or the environment problem above Restart the backend and simulator containers before blaming the suite
A green run that hides a real defect Retries were enabled and the JUnit reporter recorded a test that passed on retry as a pass Read the machine-readable run report
A frontend test passes alone and fails in the full run, or the reverse Module-registry leakage between files in a worker Run the full suite. Never diagnose from a filtered run