📚 Correct backend testing guidance

Require permission before database reinitialization and distinguish the
full CI checks from test-only runs while retaining backend test traps.

AI-assisted-by: gpt-6.1-terra
This commit is contained in:
Andrey Antukh 2026-11-23 22:38:33 +00:00
parent 3336aa1bdf
commit e202ed1878

View File

@ -1,25 +1,17 @@
# Backend Testing
# Backend testing
JVM `clojure.test` (kaocha runner) under `backend/test/backend_tests/`.
- **Read `mem:testing` first** for cross-cutting test design and output discipline. Backend uses Kaocha and discovers namespaces under `backend/test/backend_tests/` automatically.
- From the repo root, `./scripts/ci backend` runs lint, tests and format; `./scripts/ci --test backend` runs only tests. Both append `enable-backend-asserts` to `PENPOT_FLAGS`. From `backend/`, direct and focused runs must append the flag too: `PENPOT_FLAGS="${PENPOT_FLAGS:+$PENPOT_FLAGS }enable-backend-asserts" clojure -M:dev:test`. Assertions are selected when `app.config` loads, before fixtures change flags.
- Kaocha accepts repeated `--focus` flags for namespaces or vars. An Integrant schema assertion during test-system construction is a load/build error, not a failed test assertion; see `mem:backend/integrant-schemas`.
- Use the workspace's existing `PENPOT_TEST_*` database and Redis URIs, not CI values copied from logs. Confirm the destination before changing it; see `mem:devenv/core`. Test databases can have newer migrations, but never drop or recreate one without explicit permission.
- Redirect test output to a file before inspecting or filtering it. For coverage, `clojure -M:dev:test:coverage` instruments all `app.*` namespaces even on focused runs; it is slower and produces reflection warnings. Output in `target/coverage/` includes lcov, HTML and EMMA form counts; use normal tests for routine checks.
- READ `mem:testing` FIRST — it defines the execution discipline (no piping, tee to file, preferred commands) that applies to all JVM test runs.
- Test DB/Redis come from the `PENPOT_TEST_*` env vars already set in the shell (`PENPOT_TEST_DATABASE_URI`, `PENPOT_TEST_REDIS_URI`, ...); per instance they point at `penpot_test` / `penpot_test_wsN` and valkey DB `6+N` (`mem:devenv/core`). Do not override them with values copied from CI logs or other sources unless the user asks (e.g. "use a temporary database"); the CI env (`redis://redis/1`, `postgresql://postgres/penpot_test`) only works inside the CI docker network.
- The test database may have migrations applied from newer versions (it is shared dev infra). Reinitializing it — `dropdb`/`createdb` of the `PENPOT_TEST_*` database only — is explicitly permitted when that blocks a test run; never drop the main `penpot` database or another instance's test database.
- All CLI commands must be executed from the `backend/` subdirectory.
- Tests are invoked directly via `clojure -M:dev:test` (kaocha) — there is no pnpm wrapper. Kaocha auto-discovers test namespaces, so no runner registration is needed.
- **Preferred way to run them: `scripts/ci <module> --test`**, which runs lint, tests and format per module and writes a log per task under `.ci-logs/`. It exports `PENPOT_FLAGS` with `enable-backend-asserts` appended, so use it rather than calling `clojure -M:dev:test` by hand.
- **Why the flag matters:** `clojure.core/assert` is elided at compile time when `*assert*` is false, and `app.config` only sets that var from the flags when it loads. The test fixture redefines the flags after that, so they never reach it: without the flag the suite runs with every assertion compiled out, and a test that depends on an assert only means something with it set. `scripts/ci` and `tests-backend.yml` export the flag (GitHub Actions sets it too). When running the suite directly — including a `--focus` run — the command is `PENPOT_FLAGS="enable-backend-asserts" clojure -M:dev:test`.
- Coverage: if code is added or modified in `src/`, corresponding tests in `test/backend_tests/` must be added or updated.
- Isolated run: `clojure -M:dev:test --focus backend-tests.my-ns-test` for a specific test namespace, or `clojure -M:dev:test --focus backend-tests.my-ns-test/my-test-var` for a specific test var. Keep the `PENPOT_FLAGS="enable-backend-asserts"` prefix on these too; a focused run without it hides assert-dependent failures exactly like a full one.
- An `ig/assert-key` failure while building the test system occurs outside `clojure.test`, so Kaocha reports a load/build error rather than a failed assertion in a test. Diagnose the schema or injected params with `mem:backend/integrant-schemas`.
- **Log lines are not tested.** A log record is for the operator, not a contract: do not add a test that captures it (`add-watch` on `app.common.logging/log-record`, or `with-redefs` on `enabled?`/`emit-log`) to assert its message, hint or props, and do not keep such a test alive when the line changes. Whatever must be guaranteed belongs in a returned value, an event or a metric, and the test asserts that; a log line may change its wording at any time.
- Multiple focus symbols are supported by REPEATING the flag (kaocha accumulates them, last-wins does not apply): `clojure -M:dev:test --focus backend-tests.ns-one --focus backend-tests.ns-two` — preferred over a shell loop of isolated runs.
- Regression run: `clojure -M:dev:test` to ensure no regressions in related functional areas.
- Line coverage: append the `:coverage` alias (`clojure -M:dev:test:coverage`, kaocha-cloverage). It instruments every `app.*` namespace under `src/` at load, before any test runs, so even a `--focus` run instruments them all; options live under `:cloverage/opts` in `tests.edn`, output in `target/coverage/` (lcov, HTML, and EMMA `coverage.xml` whose form counts the PR report shows as statements; cloverage measures no functions or branches) (`lcov.info`, HTML). About 2x slower and noisy with reflection warnings (instrumented forms lose type hints): never use it for normal runs. `tests-backend.yml` runs it and renders the step summary with `scripts/coverage-summary.mjs`.
- If you need to filter output, tee to a temp file first: `clojure -M:dev:test 2>&1 | tee /tmp/penpot-test-output.txt`.
- RPC test helpers `command!`/`management-command!` split the data map: qualified keys become server params, unqualified keys become request body params. To inject request-level context (headers, `:app.http/auth-key-id`, ip), pass a map under `:app.http/request` metadata; non-map `IRequest` stubs fall back to a dummy request.
- The test system is `main/system-config` + `main/worker-config` with the components that must not run in the background dropped: HTTP, the srepl, cron, the dispatcher, the three audit-log consumer loops (`:app.loggers.audit.consumers.nexus/consumer`, `:app.loggers.audit.consumers.admin-console/consumer`, `:app.loggers.audit.consumers.telemetry/consumer`) and **every** `[<profile> :app.worker/runner]` (`helpers/remove-job-runners`). A live runner of any queue races the tests that drive the loop by hand (`wdisp/run-batch` + `@#'wrkr/run-worker-loop`): it takes the job the test just dispatched and completes it behind the test's back, so the test's own assertions read a state it did not produce. A live consumer loop races the tests the same way: it drains `audit_log` in the background. Do not re-add any of them by editing that list by hand; the runner removal matches by key shape on purpose.
- `th/run-task!` invokes a job by name; audit-log consumers are not jobs. Call `(consumers/run-pass cfg consumer)` with the prepared cfg (`::db/pool`, `::mtx/metrics` and transport deps) and the transport's `consumer` definition. A successful pass returns nil and publishes totals as metrics; `::consumers/busy` and `::consumers/disabled` mean no work started.
- `app.loggers.audit/submit` propagates its failure (`submit*` no longer swallows it), so a DB-free unit test that reaches a code path emitting an audit event must stub it (`with-redefs [app.loggers.audit/submit (constantly nil)]`, as the `helpers.clj` fixture does globally) or pass a cfg carrying `::db/pool`. Otherwise the throw detours the flow under test into its error path.
- `system-config` and `worker-config` are `def`s: their `(cf/get ...)` calls are evaluated when the namespace loads, against the real environment, while test code calling `cf/get` at run time sees the `penpot-test`-prefixed config. The two can disagree — in the devenv `:tenant` is `devenv-ws0` for the defs and `default` inside a test — so a component built from `worker-config` can talk to a different Redis key prefix than a cfg the test builds itself. The symptom is a component that silently does nothing locally and races in CI (which sets no `PENPOT_TENANT`).
- `backend-tests.helpers` has `metrics-stub` (a metrics instance with no collectors, where every `run!` is a no-op), `init-climit` (a concurrency limiter built from an inline config map, with an optional second argument for the metrics instance to publish to) and `with-climit`, the macro that builds one, runs the body and halts it. `init-climit` starts the republisher daemon thread, so a test that builds a limiter without halting it leaks that thread for the rest of the JVM run: use `with-climit`.
## Test system and helpers
- `backend-tests.helpers` builds the system from `main/system-config` and `main/worker-config`, excluding HTTP, srepl, cron, dispatcher, audit consumer loops and every worker runner. Live runners or consumers race tests that drive jobs or audit passes manually. Keep runner removal by key shape, not a fixed profile list.
- Those configs are `def`s evaluated at namespace load against the real environment; runtime `cf/get` inside tests can see the test-prefixed config instead. A tenant mismatch can silently send a component and test to different Redis keys.
- `th/run-task!` runs a job by name, not an audit consumer. For consumers call `(consumers/run-pass cfg consumer)` with pool, metrics and transport dependencies; nil means success, while `::consumers/busy` and `::consumers/disabled` mean no work started.
- `app.loggers.audit/submit` propagates failures. DB-free tests that reach audit emission need a stub or a cfg with `::db/pool`; the shared fixture stubs it.
- RPC helpers `command!` and `management-command!` split qualified keys into server params and unqualified keys into the request body. Pass request-level context in `:app.http/request` metadata; non-map request stubs fall back to a dummy request.
- `metrics-stub` provides no-op collectors. Use `with-climit` or explicitly halt the limiter created by `init-climit`: it starts a republisher thread.
- Do not assert log lines, hints or props. Logs are not test contracts; assert the returned value, event or metric that must remain stable instead.