Skip to main content

Testing

Synced from warehouse-planning

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​

LayerWhereCountHow it runsNeeds
Domain unit testsinternal/domain/{processcapacity,capacityplan,processpath,demand}91 tests in 12 filesmake testnothing
Application (use case) testsinternal/application/usecases, internal/application/outbox69 tests in 11 filesmake test, with the in-memory test doublesnothing
Analytics report testsinternal/analytics/report17 tests in 2 filesmake testnothing
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 testsmake testnothing
Composition-root testscmd/*/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 testsmake testnothing
BDD acceptance (godog)features/*.feature, driven by features_test.go, features_demand_test.go, features_list_test.go at the repo root25 features, 191 scenarios (231 executed)make bdd (go test ./... -run TestFeatures -v), also part of make testnothing
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.go84 testsmake integration (go test -tags=integration ./... -race -count=1)Docker
Architecture fitnessinternal/architecture18 testsmake arch-testnothing
Mutation.gremlins.yamlsee belowmake mutation-fast, make mutation-fullgremlins v0.6.0
Frontend remoteweb/src/**/*.test.ts(x) (8 files, vitest + Testing Library)cd web && npm testNode, a built ../../warehouse-ui-kit
Chart wiringcharts/warehouse-planning/tests/test_service_selectors.py, charts/warehouse-planning/tests/render_test.shpython3 charts/warehouse-planning/tests/test_service_selectors.py, bash charts/warehouse-planning/tests/render_test.shPython with pyyaml, Helm
Agent harnessscripts/harness/test_hook.py, test_repo_lint.py; guide_lint.py, repo_lint.pymake harness-test, make guide-lintPython

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 fileScenariosExecutedWhat it pins
capacity_plan.feature77the 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.feature1115plan 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.feature55CapacityPlan rules, events and validation
demand_and_list_limits.feature22demand request validation and plan list limits
expected_demand.feature88the demand window [start, end), latest event wins, ignored events, site attribution, demand_source orders vs request, no data = 422, RFC 7807 validation
forecast_demand.feature44demand_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.feature1818inbound labour demand from dock-scheduling appointments
inbound_observed_paging_doc_rules.feature1425the 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.feature66labor capacity from committed shift plans
labour_plan.feature99labour 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.feature1010LabourPlanDriftDetected 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.feature66labour 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.feature55GET /process-paths and GET /capacity-plans (empty, ordering, PUBLISHED, bad limit)
observed_capacity.feature88observed capacity feedback from task completions
plan_comparison.feature55GET /capacity-plans/comparisons: 2 to 5 ids, one site and window, as stored (ADR 0024)
plan_scenarios.feature33the scenario label and the additive GET /capacity-plans filters (ADR 0024)
process_capacity.feature66effective rate bound by LOCATION, unknown capacity = 404, unit mismatch = 409
process_capacity_doc_rules.feature1928tie-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.feature44ProcessCapacity registration rules
process_path_capacity.feature55Pick, Rebin, Pack bound by Rebin, unknown path, missing step capacity, live-shaped windows resolved by coverage
process_path_rules.feature44ProcessPath registration and path capacity rules
station_capacity.feature66stations binding a path once a standard exists, the no-standard warning, declare twice = replace, the storage-capacity read model
station_lifecycle.feature55station standards and the facility tally lifecycle
upstream_events_doc_rules.feature1327the policies driven by ShiftPlanCommitted, LocationSlot* and OrderAllocated: unusable messages are acknowledged and change nothing, redelivery, ordering
workload_forecast.feature66workload forecast PUT/GET (ADR 0023): first receipt at version 1, whole replacement, identical receipt raises nothing, negative quantity refused, the canonical path code
18 files146186

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 in relay_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​

TestEnforces
TestHexagonalArchitecturedependencies point inward; inbound and outbound adapters never import each other (arch-go)
TestMCPAdapterDependencyRulethe MCP adapter depends only on application and domain, and nothing depends on it (ADR 0008)
TestNoAuthMiddlewareReintroducedno bearer/JWT middleware under internal/adapters/inbound
TestRuntimeBinaryHasNoInMemoryAdapters, TestRuntimeBinarySensorBitesno 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
TestKafkaConsumerGroupNeverHardcodedInlineconsumer group ids come from the composition root, never a literal
TestKafkaIntegrationTestsUseTestcontainers, TestPostgresIntegrationTestsUseTestcontainers, TestPostgresIntegrationSensorFailsOnBadFixturesintegration tests boot their own Kafka/Postgres; the sensor itself is proven to fail on bad fixtures
TestNoEventEnvelopeToggleOrFlatEnvelope, TestCloudEventsOnlyCloudEvents 1.0 is the only envelope; no envelope toggle; kafka-go users must build envelopes with the CloudEvents SDK
TestReplayConsumersSetCommitIntervala full-replay cache consumer (unique group) must set its commit interval
TestKafkaWritersSetRequiredAcks, TestKafkaWriterAcksSensorBitesevery 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, TestEventCatalogueDetectorevery type this service declares in apis/asyncapi.yaml appears in the CloudEvents catalogue ADR (docs/adr/0006-...); the detector is itself tested
TestOutboxRelaysPassAttemptCap, TestOutboxRelayCapSensorFailsOnBadFixturesevery non-test file under cmd/ that builds an outbox relay passes WithMaxAttempts (ADR 0013); the sensor is proven to fail
TestMCPOptionalToolInputsCarryOmitempty, TestMCPOptionalToolInputsSensorFailsOnBadFixturesan 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 CI test job runs; the Makefile is the single source of the scope and threshold, gap 16d, and harness repo_lint rule R11 forbids a workflow passing -coverpkg itself) runs go 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-fast and the mutation-fast job run one gremlins unleash per package: ./internal/domain/processcapacity, ./internal/domain/capacityplan, ./internal/domain/processpath, ./internal/domain/demand, ./internal/analytics/report. make mutation-full and the scheduled mutation job run ./internal/domain as a whole. The last recorded measurement (comments in .gremlins.yaml) is 100 % efficacy and coverage in every package.

Make targets​

TargetRuns
make build / vet / fmt / fmt-checkgo build ./..., go vet ./..., gofmt -w ., fail on gofmt -l . output
make lintgolangci-lint run ./... (v2.14.0 in CI)
make testgo test ./... -race (unit, httptest, BDD)
make coveragethe CI coverage command plus the 90 % gate
make bddgo test ./... -run TestFeatures -v
make arch-testgo test ./internal/architecture/... -v
make integrationgo test -tags=integration ./... -race -count=1 (Docker)
make mutation-fast (alias mutation), make mutation-fullgremlins, as above
make vulngovulncheck ./...
make checkfmt-check vet build lint test: the lefthook pre-push gate
make check-allcheck coverage arch-test bdd
make check-fastfmt-check vet arch-test plus the tests of packages changed vs HEAD
make guide-lint, make harness-testagent-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.

JobRunsWhen
lintgolangci-lint v2.14.0every push/PR
guide-lintguide_lint.py, repo_lint.py, test_hook.py, test_repo_lint.pyevery push/PR
complexitygolangci-lint with only gocyclo, gocognit, cyclop, funlen, nestif (cyclomatic 15, cognitive 20, nesting 5, 80 lines / 50 statements) plus an informational gocyclo > 10 reportevery push/PR
testbuild, vet, then make coverage (race tests with the Makefile's coverage scope and 90 % gate)every push/PR
bddgo test ./... -run TestFeatures -vevery push/PR
integrationgo test -tags=integration ./... -race -count=1 on the runner's Dockerevery push/PR
mutation-fastgremlins on the six packages of MUTATION_FAST_PKGSevery push/PR
mutationgremlins on ./internal/domain; opens or closes a harness:red issue on scheduleschedule, dispatch
driftdeadcode, go mod tidy -diff, coverage-quality (high-coverage functions with a surviving mutant); advisoryschedule, dispatch
api-lintSpectral on apis/openapi.yaml and apis/asyncapi.yaml (--fail-severity=warn)every push/PR
vulngovulncheck ./...every push/PR
docs-api-driftregenerates docs/docs/api-reference/rest from the OpenAPI spec and fails on a diffevery push/PR
helm-lintct lint on the chart and the Service-selector testpull requests
chart-testsrender_test.sh and the Service-selector testevery push/PR
arch-testgo test ./internal/architecture/... -vevery push/PR
webweb/ lint (oxlint), tsc -b, vitest, build, against a sibling warehouse-ui-kit checkoutevery push/PR
trivy-scanbuilds the image and scans it (blocks on fixable CRITICAL/HIGH)pull requests
docker-publish, releasepush to GHCR with cosign signature and SBOM; tag, release and Helm chartpush 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).