Testing
This page is a copy of docs/docs/development/testing.md on develop, derived from that repository's code. Edit it there, then re-sync.
The test pyramid as it exists in this repo, the make targets that run each
layer and the CI jobs in .github/workflows/ci.yml that gate a pull request.
Counts below are func TestXxx functions on the current develop, not
sub-tests.
The layers
| Layer | Where | Count | How it runs | Needs |
|---|---|---|---|---|
| Domain unit tests | internal/domain/{processcapacity,capacityplan,processpath,demand} | 91 tests in 12 files | make test | nothing |
| Application (use case) tests | internal/application/usecases, internal/application/outbox | 69 tests in 11 files | make test, with the in-memory test doubles | nothing |
| Analytics report tests | internal/analytics/report | 17 tests in 2 files | make test | nothing |
| Adapter tests (httptest, fake Kafka reader/writer, in-memory stores) | internal/adapters/... (http 57, kafka inbound 65, mcp 19, outbound kafka 22, memory 16, outbox 12, cloudevents 6, analyticsstore 3) | 200 tests | make test | nothing |
| Composition-root tests | cmd/*/main_test.go, cmd/api/{readiness,logger_level,outbox_relay_config}_test.go, cmd/planning-projector/telemetry_test.go (boot errors that name the variable, /readyz, the relay) | 35 tests | make test | nothing |
| BDD acceptance (godog) | features/*.feature, driven by features_test.go, features_demand_test.go, features_list_test.go at the repo root | 25 features, 191 scenarios (231 executed) | make bdd (go test ./... -run TestFeatures -v), also part of make test | nothing |
Integration (-tags=integration) | 37 files: the Postgres repositories and unit of work, the outbox relay (including its attempt cap and trace propagation), the six Kafka consumers, the analytics store, cmd/mcp, cmd/api/e2e_integration_test.go (boots the real run()) and analytics_e2e_integration_test.go | 84 tests | make integration (go test -tags=integration ./... -race -count=1) | Docker |
| Architecture fitness | internal/architecture | 18 tests | make arch-test | nothing |
| Mutation | .gremlins.yaml | see below | make mutation-fast, make mutation-full | gremlins v0.6.0 |
| Frontend remote | web/src/**/*.test.ts(x) (8 files, vitest + Testing Library) | cd web && npm test | Node, a built ../../warehouse-ui-kit | |
| Chart wiring | charts/warehouse-planning/tests/test_service_selectors.py, charts/warehouse-planning/tests/render_test.sh | python3 charts/warehouse-planning/tests/test_service_selectors.py, bash charts/warehouse-planning/tests/render_test.sh | Python with pyyaml, Helm | |
| Agent harness | scripts/harness/test_hook.py, test_repo_lint.py; guide_lint.py, repo_lint.py | make harness-test, make guide-lint | Python |
Not present in this repo: contract tests against the live API (no schemathesis
job, no .schemathesis/), and evals. The OpenAPI and AsyncAPI specs are
linted with Spectral (api-lint), not exercised.
BDD features
The godog suite drives the real chi router over httptest with the in-memory
test doubles (the shipped binaries have no in-memory mode, ADR 0016). The Kafka-fed read models are filled by handing real
CloudEvents bytes to the real consumers' HandleMessage. Strict: true fails
a scenario with an undefined step.
25 feature files hold 191 Scenario/Scenario Outline blocks (count:
git grep -c -E "^[[:space:]]*Scenario" -- features). None is tagged
@known-bug any more; the runner still excludes that tag by default
(BDD_TAGS defaults to ~@known-bug) so a future known gap can be parked
there, and make bdd runs all 191 blocks as 231 executed
scenarios (Examples rows expanded) and 1678 steps (231 scenarios (231 passed), 1678 steps (1678 passed), godog's summary from go test . -run TestFeatures -count=1 -v).
| Feature file | Scenarios | Executed | What it pins |
|---|---|---|---|
capacity_plan.feature | 7 | 7 | the 12,000-order worked example (shortage 4,000, bottleneck REBIN, the four outbox events, a second publish = 409), no shortage under capacity, unknown path, negative demand, unknown plan, window coverage for plans |
capacity_plan_doc_rules.feature | 11 | 15 | plan arithmetic over the window and the rate's period, two creates = two plans, Idempotency-Key replay / reuse / missing, explicit assigned_demand: 0, the CloudEvents attributes and payload of each plan event |
capacity_plan_rules.feature | 5 | 5 | CapacityPlan rules, events and validation |
demand_and_list_limits.feature | 2 | 2 | demand request validation and plan list limits |
expected_demand.feature | 8 | 8 | the demand window [start, end), latest event wins, ignored events, site attribution, demand_source orders vs request, no data = 422, RFC 7807 validation |
forecast_demand.feature | 4 | 4 | demand_source: forecast: the [window_start, window_end) bucket rule, ceil to orders, no bucket = 422, units_per_order required, forecast_path_id (ADR 0024) |
inbound_demand.feature | 18 | 18 | inbound labour demand from dock-scheduling appointments |
inbound_observed_paging_doc_rules.feature | 14 | 25 | the door-window boundaries, the appointment version guard, task completions at the window boundaries, variance, and keyset paging edges (limit, nextCursor, invalid-cursor, unknown-query-parameter) |
labor_capacity.feature | 6 | 6 | labor capacity from committed shift plans |
labour_plan.feature | 9 | 9 | labour plan PUT/GET/list (ADR 0023): sent vs derived heads, no forecast in the shift = 422, heads above stations = 422, unchanged PUT raises nothing, the station warning, listing a shift, the canonical path code |
labour_plan_drift.feature | 10 | 10 | LabourPlanDriftDetected from both triggers: first drift raised, same drift not, cleared then returned raised, no plan or no commitment = nothing, redelivery = nothing, mixed-case path codes meet (ADR 0023 decision 3) |
labour_requirement.feature | 6 | 6 | labour required per plan step from the local labour-standard copy (ADR 0022): legacy plans unchanged, the standard in force for the site and window, uncountable tasks are unknown, PICK tasks from released lines, replays change nothing, non-positive task factor = 422 |
list_endpoints.feature | 5 | 5 | GET /process-paths and GET /capacity-plans (empty, ordering, PUBLISHED, bad limit) |
observed_capacity.feature | 8 | 8 | observed capacity feedback from task completions |
plan_comparison.feature | 5 | 5 | GET /capacity-plans/comparisons: 2 to 5 ids, one site and window, as stored (ADR 0024) |
plan_scenarios.feature | 3 | 3 | the scenario label and the additive GET /capacity-plans filters (ADR 0024) |
process_capacity.feature | 6 | 6 | effective rate bound by LOCATION, unknown capacity = 404, unit mismatch = 409 |
process_capacity_doc_rules.feature | 19 | 28 | tie-breaks (earliest constraint, step ties), zero vs negative quantity, window coverage at the exact boundary, ProcessCapacityChanged only when the effective rate moves, per-second rate comparison, stations and standards without labor |
process_capacity_rules.feature | 4 | 4 | ProcessCapacity registration rules |
process_path_capacity.feature | 5 | 5 | Pick, Rebin, Pack bound by Rebin, unknown path, missing step capacity, live-shaped windows resolved by coverage |
process_path_rules.feature | 4 | 4 | ProcessPath registration and path capacity rules |
station_capacity.feature | 6 | 6 | stations binding a path once a standard exists, the no-standard warning, declare twice = replace, the storage-capacity read model |
station_lifecycle.feature | 5 | 5 | station standards and the facility tally lifecycle |
upstream_events_doc_rules.feature | 13 | 27 | the policies driven by ShiftPlanCommitted, LocationSlot* and OrderAllocated: unusable messages are acknowledged and change nothing, redelivery, ordering |
workload_forecast.feature | 6 | 6 | workload forecast PUT/GET (ADR 0023): first receipt at version 1, whole replacement, identical receipt raises nothing, negative quantity refused, the canonical path code |
| 18 files | 146 | 186 |
The *_doc_rules.feature files pin rules written in the documentation; their
steps are in steps_doc_rules_test.go. Two of them
(capacity_plan_doc_rules.feature) pin 422 missing-required-field for a
blank location or path_id. They were @known-bug until CreateCapacityPlan
started validating the required identifying fields
(capacityplan.ValidateRequired) before it composes the path capacity or
resolves the demand; BDD_TAGS=@known-bug go test . -run TestFeatures -count=1
now selects no scenario.
Integration tests
Every integration test starts its own containers with testcontainers
(postgres:16-alpine, confluentinc/confluent-local:7.6.1); none reads
DATABASE_URL or KAFKA_BROKERS, and two fitness tests enforce that. The
cmd/api/e2e_integration_test.go test boots the real run() of cmd/api against
Postgres and Kafka containers and drives it only through REST and Kafka (three
consumers, plan create/publish, NUL guard, both output topics, restart,
/readyz with missing topics and with Postgres gone, exit when Kafka goes
away). analytics_e2e_integration_test.go covers the whole read side: plan
created and published, outbox, relay, Kafka, projector, analytical database,
report.
Gap-fix tests (2026-10-12 wave), all in internal/adapters/outbound/outbox:
relay_cap_integration_test.go(ADR 0013), real Postgres:TestOutboxRelay_MaxAttempts_PoisonRowExcludedThenGoodRowPublishes,TestOutboxRelay_MaxAttempts_ReArmedRowIsClaimedAgain,TestOutboxRelay_NoCap_PoisonRowBlocksLaterRows. Their in-memory twins live inrelay_cap_test.go(TestRelay_MaxAttempts_*,TestRelay_NoCap_*,TestRelay_SendFailureCarriesTheRow).outbox_trace_integration_test.go(ADR 0014), real Postgres and its own Kafka container:TestOutboxTrace_TraceparentCrossesTheOutboxToKafka,TestOutboxTrace_RowWithoutTraceHeadersRelaysUnchanged.
Chart render tests
charts/warehouse-planning/tests/render_test.sh renders the chart with helm template and asserts: the api Deployment mounts the ConfigMap with
envFrom and the other Deployments do not (D14); OUTBOX_MAX_ATTEMPTS
defaults to 20 and 0 renders as is (D12); every backend Deployment sets
ENVIRONMENT, SERVICE_VERSION and, while otel.enabled,
OTEL_EXPORTER_OTLP_ENDPOINT, and the api sets SHUTDOWN_DRAIN_DELAY when
configured (D21). It also asserts that the chart refuses every missing
mandatory value (database, brokers, consumer groups, demand site) and renders
warehouse-infra's current values with every mandatory variable provided. The
chart-tests CI job runs it with the Service-selector test on every push and PR.
Architecture fitness tests
| Test | Enforces |
|---|---|
TestHexagonalArchitecture | dependencies point inward; inbound and outbound adapters never import each other (arch-go) |
TestMCPAdapterDependencyRule | the MCP adapter depends only on application and domain, and nothing depends on it (ADR 0008) |
TestNoAuthMiddlewareReintroduced | no bearer/JWT middleware under internal/adapters/inbound |
TestRuntimeBinaryHasNoInMemoryAdapters, TestRuntimeBinarySensorBites | no non-test file under cmd/** imports internal/adapters/outbound/memory (ADR 0016); the detector is proven to flag plain, aliased, blank, dot and nested imports |
TestKafkaConsumerGroupNeverHardcodedInline | consumer group ids come from the composition root, never a literal |
TestKafkaIntegrationTestsUseTestcontainers, TestPostgresIntegrationTestsUseTestcontainers, TestPostgresIntegrationSensorFailsOnBadFixtures | integration tests boot their own Kafka/Postgres; the sensor itself is proven to fail on bad fixtures |
TestNoEventEnvelopeToggleOrFlatEnvelope, TestCloudEventsOnly | CloudEvents 1.0 is the only envelope; no envelope toggle; kafka-go users must build envelopes with the CloudEvents SDK |
TestReplayConsumersSetCommitInterval | a full-replay cache consumer (unique group) must set its commit interval |
TestKafkaWritersSetRequiredAcks, TestKafkaWriterAcksSensorBites | every kafka-go Writer{...} literal in a non-test file under internal/ or cmd/ sets RequiredAcks (kafka-go defaults to RequireNone, acks=0, which silently drops messages on a broker blip); the sensor is proven to fail |
TestDeadLetterCallsGuardCancellation (+ TestDeadLetterShutdownSensorBites, kafka_dlq_shutdown_fitness_test.go) | Every function in a non-test file under internal/adapters/inbound/kafka that sends to the dead-letter topic must reference ctx.Err() (any context-named value) or context.Canceled in its own body, or carry a //dlq:deterministic <reason> comment on the call line or the line above it. A handler that fails because the process is stopping must not dead-letter a good message and commit past it (network-fulfillment #89); a guard in the caller does not count. The sensor test proves the detector flags the pre-fix shape. |
TestKafkaWriterTopicNotSetTwice (+ TestKafkaWriterTopicSensorBites, kafka_writer_topic_fitness_test.go) | kafka-go rejects every write whose Message.Topic is set when the Writer also has a Topic. Per Go package under internal/ and cmd/: once any kafka-go Message literal sets Topic, every Writer literal in that package must leave Topic empty, unless it carries //kafka:fixed-topic-writer <reason> and no Topic-setting Message is provably written through it. Writers configured after construction and WriterConfig are not covered. (Escape: warehouse-planning's domain DLQ writer, where no dead letter ever landed.) |
TestEventCatalogueMatchesContract, TestEventCatalogueDetector | every type this service declares in apis/asyncapi.yaml appears in the CloudEvents catalogue ADR (docs/adr/0006-...); the detector is itself tested |
TestOutboxRelaysPassAttemptCap, TestOutboxRelayCapSensorFailsOnBadFixtures | every non-test file under cmd/ that builds an outbox relay passes WithMaxAttempts (ADR 0013); the sensor is proven to fail |
TestMCPOptionalToolInputsCarryOmitempty, TestMCPOptionalToolInputsSensorFailsOnBadFixtures | an MCP tool input whose jsonschema description says optional/omitted carries omitempty (else the SDK marks it required); the sensor is proven to fail |
internal/adapters/inbound/mcp/governance_test.go also pins the MCP tool
budget (maxTools = 11).
Coverage and mutation gates
- Coverage:
make coverage(which the CItestjob runs; the Makefile is the single source of the scope and threshold, gap 16d, and harnessrepo_lintrule R11 forbids a workflow passing-coverpkgitself) runsgo test ./... -race -coverprofile=coverage.out -coverpkg=./internal/domain/...,./internal/application/...,./internal/analytics/...and fails below 90 %. - Mutation (
.gremlins.yaml, gremlins v0.6.0):workers: 1,timeout-coefficient: 30, thresholds efficacy 99 and mutant-coverage 99 (gremlins fails when the value is ≤ the threshold, so any surviving mutant fails).make mutation-fastand themutation-fastjob run onegremlins unleashper package:./internal/domain/processcapacity,./internal/domain/capacityplan,./internal/domain/processpath,./internal/domain/demand,./internal/analytics/report.make mutation-fulland the scheduledmutationjob run./internal/domainas a whole. The last recorded measurement (comments in.gremlins.yaml) is 100 % efficacy and coverage in every package.
Make targets
| Target | Runs |
|---|---|
make build / vet / fmt / fmt-check | go build ./..., go vet ./..., gofmt -w ., fail on gofmt -l . output |
make lint | golangci-lint run ./... (v2.14.0 in CI) |
make test | go test ./... -race (unit, httptest, BDD) |
make coverage | the CI coverage command plus the 90 % gate |
make bdd | go test ./... -run TestFeatures -v |
make arch-test | go test ./internal/architecture/... -v |
make integration | go test -tags=integration ./... -race -count=1 (Docker) |
make mutation-fast (alias mutation), make mutation-full | gremlins, as above |
make vuln | govulncheck ./... |
make check | fmt-check vet build lint test: the lefthook pre-push gate |
make check-all | check coverage arch-test bdd |
make check-fast | fmt-check vet arch-test plus the tests of packages changed vs HEAD |
make guide-lint, make harness-test | agent-guide lint and hook tests |
lefthook.yml runs fmt-check, vet and lint on commit and make check
on push, once lefthook install has been run in the clone.
CI jobs (.github/workflows/ci.yml)
Triggers: push and pull request on main and develop, a weekly schedule
(Monday 06:00 UTC) and manual dispatch.
| Job | Runs | When |
|---|---|---|
lint | golangci-lint v2.14.0 | every push/PR |
guide-lint | guide_lint.py, repo_lint.py, test_hook.py, test_repo_lint.py | every push/PR |
complexity | golangci-lint with only gocyclo, gocognit, cyclop, funlen, nestif (cyclomatic 15, cognitive 20, nesting 5, 80 lines / 50 statements) plus an informational gocyclo > 10 report | every push/PR |
test | build, vet, then make coverage (race tests with the Makefile's coverage scope and 90 % gate) | every push/PR |
bdd | go test ./... -run TestFeatures -v | every push/PR |
integration | go test -tags=integration ./... -race -count=1 on the runner's Docker | every push/PR |
mutation-fast | gremlins on the six packages of MUTATION_FAST_PKGS | every push/PR |
mutation | gremlins on ./internal/domain; opens or closes a harness:red issue on schedule | schedule, dispatch |
drift | deadcode, go mod tidy -diff, coverage-quality (high-coverage functions with a surviving mutant); advisory | schedule, dispatch |
api-lint | Spectral on apis/openapi.yaml and apis/asyncapi.yaml (--fail-severity=warn) | every push/PR |
vuln | govulncheck ./... | every push/PR |
docs-api-drift | regenerates docs/docs/api-reference/rest from the OpenAPI spec and fails on a diff | every push/PR |
helm-lint | ct lint on the chart and the Service-selector test | pull requests |
chart-tests | render_test.sh and the Service-selector test | every push/PR |
arch-test | go test ./internal/architecture/... -v | every push/PR |
web | web/ lint (oxlint), tsc -b, vitest, build, against a sibling warehouse-ui-kit checkout | every push/PR |
trivy-scan | builds the image and scans it (blocks on fixable CRITICAL/HIGH) | pull requests |
docker-publish, release | push to GHCR with cosign signature and SBOM; tag, release and Helm chart | push to main only |
Two more workflows: .github/workflows/docs.yml builds this Docusaurus site on
every pull request touching docs/** or apis/** and deploys it to GitHub
Pages on push to main; .github/workflows/ai-review.yml posts an advisory
architecture review on PRs into develop that touch domain, application, APIs
or charts (a no-op without the ANTHROPIC_API_KEY secret).