Skip to content

Latest commit

 

History

History
241 lines (206 loc) · 15.3 KB

testing-guide.md

File metadata and controls

241 lines (206 loc) · 15.3 KB

Testing Guide (for developers)

Where to put a test for a change you just made, and how to run it. The Testing Strategy explains why the tiers exist; make test-inventory generates a list of what exists today (git-ignored — read it locally).

Principles

  • Test the intent, not the line. A test pins down a behavior or contract — "a pruned node displays Pruned", "the gate holds until both chains sync", "an old DB migrates without losing history" — and reads clearly enough that its name plus a one-line comment explain why it exists. Don't add a test purely to move the coverage number.
  • The 80% coverage gate is a floor, not a target. Uncovered defensive error-handling is fine; uncovered behavior (a migration path, a retention rule, a decision branch) is a gap.
  • Tests are real code. They are linted (shellcheck), version-controlled with the change they protect, and listed in the inventory. CI reruns the inventory generator and fails if an enumerated suite has no counted assertions; the generated inventory stays untracked.

Commands

Run these on Linux, or in the container on any host. macOS is deprecated as a test platform (2026-09-10) and the shell suite refuses to start there: the assertions are written against GNU sed/stat, BSD tools differ without failing loudly, and a grep that is a ugrep shim silently matches nothing for a pattern holding a non-terminal $. A control run on an unmodified develop scored 3708 passed / 148 failed, so a result from there is not evidence either way. PITHEAD_UNTRUSTED_MACOS_RUN=1 overrides the refusal for portability debugging, and is named for what the result is worth.

make test-container is the answer to that refusal rather than a way around it: it runs the same targets in tests/runner/Dockerfile, a pinned Debian image carrying the toolchain at the versions the Makefile pins, as a non-root user. It needs Docker on the host and nothing else, so the verdict is the one CI reaches. Tier 4's appliance battery stays out — it needs KVM and libvirt on the machine itself, which no container supplies on macOS or Windows.

The standalone Quadlet provenance regression also runs on macOS with Bash 5 or newer on PATH and Python 3.9 or newer. Run make, then python3 tests/stack/standalone/test_quadlet_provenance.py. It checks image selection and all three fixture sets without starting containers; it does not replace the Linux shell suite or the required live rendering proof.

make test-container       # all of the below in the pinned Linux image (any host with Docker)
make test-container ARGS="make test-mini-stack"   # tier 3 in the image (host daemon via the socket)
# Tier 4's live driver runs in the image too. It carries an ssh client, and `--ssh` mounts your
# ~/.ssh read-only so the harness reaches the reserved box. Opt-in on purpose: no other tier needs
# the keys, and a mounted ~/.ssh is readable by anything the tiers execute.
make test-container ARGS="--ssh make test-integration ARGS='--host user@box --dir pithead --check'"
make test                 # local gates; needs Docker, but no live test server
make test-dashboard       # dashboard pytest + 80% coverage gate
make test-stack           # pithead shell suite
bash tests/stack/run.sh 3 # one of the shell suite's five blocks, as one CI leg runs it
# Run one #2048 prerequisite independently, with no predecessor fragment:
bash -uo pipefail -c 'source tests/stack/lib.sh; source tests/stack/test-spool-audit.sh; [ "$PASS" -gt 0 ] && [ "$FAIL" -eq 0 ]'
make test-fakes           # tier-2 contract test (real clients vs fakes)
make test-integration-selftest   # the integration harness's own logic
make test-inventory       # write a generated (git-ignored) coverage list to docs/dev/test-inventory.md
make test-mini-stack      # tier-3 docker mini-stack (needs docker)
make test-integration ARGS="--host user@box --dir pithead --check"   # tier-4 live, non-destructive

Run the shell and appliance selftests as a non-root user on Linux; root bypasses permission-denied fixtures, and BSD utilities differ from their GNU counterparts. See development setup for prerequisites.

Where tests live

You changed… Write the test here Tier
Dashboard logic (a decision, metric, /api/state field) dashboard/tests/**/test_*.py (pytest) 1
Frontend logic (worker sort, formatting) dashboard/tests/frontend/<feature>/*.test.mjs (node --test) 1
A client that parses a daemon (monerod RPC, Tari gRPC) tests/integration/fakes/test_contract.py (+ extend the fakes) 2
The control plane (sync-gate #35, failover #31) dashboard/tests/service/test_data_service_*.py (+ a mini-stack scenario) 1 + 3
pithead CLI behavior Matching feature suite under tests/stack/, loaded by run.sh 1
A compose security/hardening invariant (caps, no-new-privileges, no secret in a healthcheck, socket-proxy scope) the #90 section of tests/stack/standalone/test_compose.sh 1
A new config.json axis one row in tests/integration/scenarios.sh 4
A failure mode needing real containers run.sh --fault-injection and/or a mini-stack scenario 4 / 3
The integration harness's own logic Matching tests/integration/selftest/selftest-*.sh —

Recipes

Dashboard behavior (tier 1)

Add a test_* to the matching file under dashboard/tests/. Name it for the behavior, add a one-line docstring stating the intent, mock at the client boundary (the conftest gives you an in-memory state_manager). Run make test-dashboard; coverage must stay ≥ 80%. Both test directories keep their shared builders in a conftest.py. Under dashboard/tests/web/ those are the view-layer builders — _metrics, _sync, _hashrate, _state_mgr and _data; under dashboard/tests/service/ they are _totals, _posture, _topo, _edge, _on and _down, plus the algo service and the _SAFE resting config the posture builders read. All of them are factory fixtures: take the one you need as a parameter instead of writing another copy. What is deliberately not shared, and why, is recorded in each file — several builders share a name across modules while building different things, so check there before assuming two copies are the same builder.

def test_pruned_node_is_labelled_pruned(...):
    # Intent: a local pruned node shows "Pruned" so a config/DB mismatch is visible (#32).
    ...

A client parsing a new daemon state (tier 2)

  1. Teach the fake to produce the state: edit tests/integration/fakes/fake_monerod.py or fake_tari.py (add a mode, or a field the daemon returns).
  2. Assert the real client parses it: add a test to fakes/test_contract.py that points the real MoneroClient/TariClient at the fake and checks the parsed result.
  3. make test-fakes. This is the seam that catches "the daemon changed its wire format".

A config axis (tier 4)

Add a NAME<TAB>overrides row to scenario_matrix() in scenarios.sh, keeping comments outside the data-only heredoc, and add the value to axis_coverage(). The self-test requires a tab in every row and enforces that every axis value appears in some scenario, so malformed rows and half-added axes fail make test-integration-selftest. No code changes needed.

A control-plane scenario (tier 3)

Add a scenario to tests/integration/mini-stack/run-mini-stack.sh: drive the fakes via their /control endpoints (set_monerod/set_tari) and assert real container state with assert_state / assert_stays. make test-mini-stack (needs docker).

Visual check (frontend, pre-PR)

The node --test frontend suite renders components as strings, so it cannot see a layout bug — an overflowing table, a wrapped stat, a broken breakpoint. Before a PR that touches the dashboard's look, render the real frontend in a real browser against a canned /api/state payload — no docker, no stack. The fixture half lives in the repo: tests/frontend/fixtures/_gen_state.py writes state.json, a real build_state() payload (the exact contract the client renders). Regenerate it whenever the payload contract changes — a drift guard in tests/web/views/test_views.py reruns the generator and fails on any structural difference from the checked-in fixture, down to nested keys. Then serve the real app around it:

cd dashboard
uv run --extra test python tests/frontend/fixtures/_gen_state.py
python3 - <<'EOF'
import http.server, mimetypes
from pathlib import Path
mimetypes.add_type("text/javascript", ".mjs")
web, fix = Path("mining_dashboard/web"), Path("tests/frontend/fixtures/state.json")
class H(http.server.SimpleHTTPRequestHandler):
    def translate_path(self, path):
        p = path.split("?")[0]
        if p.startswith("/api/state"): return str(fix)
        if p.startswith("/static/"): return str(web / p.lstrip("/"))
        return str(web / "templates/index.html")
http.server.ThreadingHTTPServer(("127.0.0.1", 8000), H).serve_forever()
EOF

Open http://127.0.0.1:8000 and eyeball the page at a desktop and a phone width (the browser's device toolbar is enough). Only /api/state is served — every other API call fails, which the page tolerates; the main view is the point. This is a manual pre-PR step, not a test tier: it has caught real bugs (a "≈ 0.0 blocks" display, a WebKit table overflow) that the string-render tests structurally cannot.

Conventions

  • Determinism, no sleep-and-hope. Wait on a real signal with a timeout (wait_for, assert_state, wait_status_ok). For time-based logic, backdate timestamps white-box rather than patching the global clock — push an old point into the deque, then act (see test_history_older_than_retention_pruned_from_memory).
  • Shell: pure logic goes in lib.sh/scenarios.sh and is tested by selftest.sh. I/O (ssh, docker, RPC) is thin wrappers that aren't unit-tested. Everything stays shellcheck --severity=warning clean.
  • Hermetic against the host. The release gate runs make test on a box that has a live stack, no TMPDIR/RUNNER_TEMP and no GitHub runner image, so a shell test takes its inputs from its fixture, not the host. The harness covers scratch under ${TMPDIR:-${RUNNER_TEMP:-/tmp}}, addresses and bridges through stub_host_addrs, systemd units through the sandboxed PITHEAD_UNIT_DIR, and the iptables, nft and systemctl verbs: tests/stack/lib/host-fence.sh puts a sudo and a recording no-op for each of those tools first on PATH, so a fixture that stubs only docker cannot rewrite the host's Tor-only egress fence, and neither can a fixture's own pass-through sudo or a sudo env PATH=... that keeps the inherited PATH. Run no such tool by absolute path, and never build a PATH that drops the inherited one. test-harness-tooling.sh runs a canary down each route and every block ends by checking the stubs still lead PATH. A fixture stubs everything else it reaches: other sudo commands, read-only systemctl queries, the dashboard on 127.0.0.1:8000, the Avahi config (PITHEAD_AVAHI_CONF). A fixture whose path reaches apply_tor_egress_firewall stubs it too: the fenced iptables -S reads as an absent rule and warns. A test that genuinely needs a tool (Go 1.21 or newer for the raise-watch self-test) fails by naming it and its version, and the release preflight requires it; it never skips.
  • make test-inventory writes a generated (git-ignored) coverage list you can read locally — handy for seeing what already exists before you add a test.
  • Secrets: never print tokens, creds, or onions. The harness redacts artifacts and hashes secrets on the box. If you add a secret-bearing field to config.reference.json, tests/integration/selftest/selftest-redact.sh fails until you classify it — either redact() covers it, or the file records why it is safe to keep. An array you add is classified as an array, whether or not the reference populates it.

Gotchas learned on real hardware

The live harness was first run against a real synced, mining box. These are the calibration lessons now baked into the tests.

  • A synced local monerod shows state: "loading" in /api/state, not "done" — it has no target height once caught up. Assert "synced" via monerod's own get_info.synchronized (the harness's monero_caught_up), not the dashboard UI field.
  • stratum.conns can read 0 on a healthy, mining box. Use proxy_workers / total_hashes for mining-liveness; conns is informational.
  • The mini-stack must be isolated. Containers are named itest-* and control ports are 28081/28152 so it can't collide with — or control — a real deployment on the same host. A fake server inside a container must bind 0.0.0.0; binding 127.0.0.1 makes it unreachable from peer containers, which once broke release in the mini-stack.
  • monerod-down failover IS simulated in the mini-stack (scenarios 6–9: outage, readmit, busy/mid-reorg, double outage) — but only because the fake compose sets LOCAL_MONERO_HOST to the fake monerod's hostname. If it doesn't match MONERO_NODE_HOST, the dashboard treats monerod as "remote" and never probes it for reachability, so an outage becomes a silent no-op — the original wiring bug. The tier-4 run.sh --fault-injection run still proves the real-binary leg on real hardware.
  • Run --check first. Against any real box, run.sh --check asserts the current live state non-destructively (no config change). It's the safe way to validate before the config-churning matrix.

Native browser regressions

Install the locked Playwright runner and browsers, then run the suite:

npm ci --prefix dashboard/tests/browser --ignore-scripts
dashboard/tests/browser/node_modules/.bin/playwright install chromium firefox webkit
make test-browser

On Linux, add --with-deps to the install command. The separate browser.yml workflow installs these dependencies and runs Chromium, Firefox, WebKit and mobile Chromium. The job allows 45 minutes for cold browser/system-library downloads and the full suite; individual Playwright tests retain their 30-second deadline and run without retries. Missing dependencies fail the suite. Pure frontend tests remain dependency-free. See browser testing for focused runs, failure artifacts and coverage limits. The backup regression serves the production backup component over self-signed HTTPS, accepts the browser's certificate interstitial, and records the exact Chromium version in both fresh-profile and explicitly disabled-extension runs. CI repeats the backup tests with Google Chrome for Testing 141.0.7390.37; its executable can also be selected with PITHEAD_BACKUP_BROWSER_EXECUTABLE. It saves the kit and a 22 MiB encrypted fixture through the GUI, compares archive length and SHA-256, decrypts with the saved kit, and verifies gzip/tar integrity and member bytes. A client-blocked transfer must leave the kit available for retry without another backup request; an interrupted transfer must report a failed download and permit a complete retry. These fixtures do not contact an appliance, prove host backup creation, or identify an operator's extension or managed policy.

The configuration draft browser regression exercises valid edits and invalid JSON through Simple, Advanced and Backup, dirty markers, reset, failed apply and successful apply. The provision phase also fetches the shipped editor modules through the appliance dashboard.