Skip to main content

Testing

Synced from slotting-optimization

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 on develop, the make targets that run each layer, and the CI jobs that gate a pull request. Every count on this page was recounted on 2026-10-19 from develop at 3312858 (after the analytics read side, ADR 0006, and the real-only runtime, ADR 0011).

Source: Makefile, .github/workflows/ci.yml, features/*.feature, .gremlins.yaml, internal/architecture/*_test.go.

Make targets​

TargetCommandNeedsIn check / check-all
make testgo test ./... -racenothing (no database, no broker)both
make coveragego test ./... -race -coverprofile=coverage.out -coverpkg=./internal/domain/...,./internal/application/... plus the 90 % gatenothingcheck-all
make bddgo test ./... -run TestFeatures -vnothingcheck-all
make arch-testgo test ./internal/architecture/... -vnothingcheck-all
make integrationgo test -tags=integration ./... -race -count=1Docker onlyneither
make mutationgremlins unleash on ./internal/domain/slotplan, then ./internal/domain/planninggremlins v0.6.0neither
make mutation-fullgremlins unleash ./internal/domain --workers 1 --timeout-coefficient 30gremlinsneither
make lintgolangci-lint run ./... (complexity limits in .golangci.yml)golangci-lint v2.14.0both
make vulngovulncheck ./...govulncheckneither
make checkfmt-check vet build lint testthe pre-commit gate
make check-allcheck coverage arch-test bddrun before pushing
make check-fastfmt-check vet arch-test plus the tests of the Go packages changed vs HEADpython3the agent Stop hook

lefthook (lefthook.yml) runs fmt-check, vet and lint on commit and make check on push.

Unit tests​

Plain go test, no build tag, no I/O.

AreaWhereWhat it pins
Aggregateinternal/domain/slotplan/{plan,values}_test.goevery invariant of Restore, the Draft -> Approved/Rejected, Approved -> Superseded transitions, the events and their headers
Execution (ADR 0010)internal/domain/slotplan/execution_test.goParseMoveRef (<plan_id>:<move_seq>, digits only), NewRelocation required fields, MatchRef / MatchBins per kind and every unmatched reason, Progress (executed moves, summed quantities, latest instant, out-of-range positions ignored)
Plannerinternal/domain/planning/planner_test.gocandidates, ABC thresholds, hazmat and temperature compatibility, capacity, stickiness, move diffing, determinism
Use casesinternal/application/usecases/*_test.go with fakes_test.gounit-of-work boundaries, version guards, supersede-on-approve, consumer outcomes (applied, duplicate, stale, ignored); record_relocation_test.go: reference first, bins fallback, unmatched is claimed not recorded, CloudEvents-id and relocation-id dedupe, invalid facts touch nothing, transient errors roll back, GetPlan.View progress
HTTPinternal/adapters/inbound/http/*_test.go (not _integration)routes through httptest, problem mapping, readiness
Kafka ininternal/adapters/inbound/kafka/*_test.godispatch by full type, skip vs retry, backoff sequence, dead-lettering with fake readers and writers; stock_consumer_test.go: inventory-storage's AsyncAPI StockRelocated example decoded byte for byte (testdata/inventory_StockRelocated.golden.json), the move reference, poison dead-lettered at once, unmatched committed, other types skipped, shutdown never dead-letters; TestDomainDLQWriter_TopicComesFromTheMessage
HTTP / MCP execution viewinternal/adapters/inbound/http/execution_handlers_test.go, internal/adapters/inbound/mcp/execution_tool_test.goexecution on GET /slot-plans/{planId} and get_slot_plan (camelCase vs snake_case, omitted fields)
Kafka out, relayinternal/adapters/outbound/{kafka,outbox}/*_test.goCloudEvents encoding (golden), sink settings, relay batching; the attempt cap over the in-memory store (relay_cap_test.go: TestRelay_MaxAttempts_PoisonRowExcludedThenGoodRowPublishes, TestRelay_NoCap_PoisonRowBlocksLaterRows, TestRelay_MaxAttemptsNegativeIgnoredAndDefaultIsTwenty, TestRelay_SendFailureCarriesTheRow; ADR 0008)
In-memory adaptersinternal/adapters/outbound/memory/memory_test.gothe shared repository contract in internal/testing/repocontract
Analytics read model (ADR 0006)internal/analytics/report/report_test.gothe three projected kinds, Event.Validate, MilestonesOf, ParseGranularity, ParseRange (defaults, 366-day cap, inverted ranges), DayWindows, ComputeFreshness (no negative lag), Percentile (linear interpolation, the percentile_cont definition), TimingOf
Analytics storeinternal/adapters/outbound/analyticsstore/contract_test.goTestMemory_Contract: the shared projection/reader contract over the in-memory twin (the Postgres twin runs it under the integration tag)
Analytics stream and projector consumerinternal/adapters/outbound/kafka/analytics_encoder_test.go, internal/adapters/inbound/kafka/analytics_consumer_test.go, analytics_consumer_internal_test.gothe analytics golden wire format; FanoutEncoder: two rows and one id per event, the whole call fails on an unknown event, topic overrides, unique ids across occurrences; the consumer applies valid events, skips what it cannot route, dead-letters deterministic failures at once, retries transient ones without committing, never fails on a skip; the skip sampler; TestAnalyticsKindsCoverExactlyTheThreePublishedTypes
Reports HTTPinternal/adapters/inbound/http/reports_handler_test.gofunnel report shape, defaults and validation (invalid-report-range, invalid-report-granularity), freshness, 500 report-store-error, /healthz
Projector and reports rootscmd/slotting-projector/main_test.go, cmd/slotting-reports/main_test.goloadConfig defaults and overrides, fail-fast without the analytical DSN or brokers, /healthz vs /readyz flip on shutdown, a malformed DSN, LOG_LEVEL mapping
Composition rootcmd/api/main_test.go, outbox_relay_config_test.go, logger_level_test.go; cmd/mcp/main_test.go; cmd/api/e2e_integration_test.goenv parsing (the boot refusals of loadRuntime as a table asserting the error names the variable: TestLoadRuntimeRefusesWithAnErrorNamingTheVariable, TestLoadRuntimePermissiveMessageNamesRealKafka, TestNoDatabaseURLIsABootErrorEverywhere; relay interval, OUTBOX_MAX_ATTEMPTS (TestOutboxMaxAttempts, TestDefaultOutboxMaxAttemptsIsTwenty), LOG_LEVEL incl. warning (TestNewLoggerLevels in both binaries), LOOKBACK_DAYS, FORWARD_ZONE_CODES, DEMAND_SITE_ID/DEFAULT_SITE_ID, drain delay, MIGRATIONS_DATABASE_URL), consumers and relay start and stop, a worker that dies (TestWatchWorkersReportsAWorkerThatDied), the readiness dependencies, and TestRunOnRealPostgresAndKafka (integration tag): the real run() on testcontainers Postgres and Kafka driven only through REST and Kafka, including the exit when Kafka goes away. The composition root has no in-memory runtime: unit tests build the doubles directly (cmd/api/testdoubles_test.go)
Boot retry, telemetry, ids, clocktheir packages

Integration tests (testcontainers)​

Twenty-one files in ten packages carry //go:build integration:

PackageFilesBacking services and what the suite proves
internal/adapters/outbound/postgresmain_integration_test.go, repositories_integration_test.goPostgres: the same repocontract suite the memory adapters pass (TestSlotPlanRepoContract, TestDemandLedgerContract, TestProfileDirectoryContract, TestSlotCatalogueContract, TestMoveExecutionLedgerContract), the execution ledger joining the unit of work (TestMoveExecutionLedgerJoinsTheUnitOfWork), one Approved plan per site enforced by the database, the unit of work committing or rolling back plan, outbox and claim together, claim-once, outbox drain order and failure handling
internal/adapters/outbound/postgres/pgtxpgtx_integration_test.go (its own TestMain)Postgres: the transaction bracket every write relies on, through the real repositories and postgres.UnitOfWork. A plan save and its outbox rows commit together (TestPgtx_SaveAndPublishCommitAtomically); an error inside the scope rolls back the plan, the outbox rows and the processed-event claim (TestPgtx_AnErrorInsideTheScopeRollsEverythingBack); a reader on the pool sees nothing before commit (TestPgtx_ReposOutsideTheScopeSeeNothingUntilCommit); a nested Do joins the outer transaction (TestPgtx_NestedUnitOfWorkJoinsTheOuterTransaction); pgtx.With/pgtx.From carry a bare pgx transaction to the repositories (TestPgtx_ExplicitWithFromCarriesTheTransactionToAnyQuerier)
internal/adapters/outbound/outboxmain_integration_test.go, relay_integration_test.go, relay_cap_integration_test.go, outbox_trace_integration_test.goPostgres + Kafka: TestRelay_RealPostgresAndKafka_PublishesCloudEventsKeyedByPlanID. The attempt cap over real Postgres (ADR 0008): a poison row is excluded after the cap, logged once at ERROR with id, topic, type and key, and the good row of the same key behind it publishes (TestOutboxRelay_MaxAttempts_PoisonRowExcludedThenGoodRowPublishes); the runbook's re-arm SQL makes it claimable again (TestOutboxRelay_MaxAttempts_ReArmedRowIsClaimedAgain); without a cap the poison row blocks everything (TestOutboxRelay_NoCap_PoisonRowBlocksLaterRows). Trace continuity (ADR 0009): the approve request's traceparent is stored in outbox_events.headers, relayed by a background pass and extracts to the request span (TestOutboxTrace_TraceparentCrossesTheOutboxToKafka); a row without stored headers relays unchanged with none (TestOutboxTrace_RowWithoutTraceHeadersRelaysUnchanged)
internal/adapters/outbound/kafkamain_integration_test.go, publisher_integration_test.goKafka: the production Encoder and RelaySink (the writer settings cmd/api builds) publish the aggregate's three event kinds, then the test reads them back from the broker and asserts the CloudEvents 1.0 envelope (specversion, id, source, the com.warehouse.wms.slotting-optimization.slotplan.<Event> type), the content-type header, the payloads pinned in apis/asyncapi.yaml and a re-sent outbox row carrying the same CloudEvents id (TestKafkaPublisher_RealBrokerPublishesTheCloudEventsContract); every event of one plan carries the plan id as the Kafka key (TestKafkaPublisher_OnePlanSticksToOnePartitionKeysOrdering)
internal/adapters/inbound/httpmain_integration_test.go, helpers_integration_test.go, idempotency_integration_test.goPostgres: the Idempotency-Key middleware (400 without a key, replay of the original plan, 422 on a different body, different keys make different plans, a rejected request is cached too, concurrent requests with one key create one plan), approve end to end, racing approvals of one site leave one Approved plan
internal/adapters/inbound/kafkamain_integration_test.go, consumers_integration_test.go, stock_consumer_integration_test.go, analytics_consumer_integration_test.goPostgres + Kafka: the demand, product and layout consumers end to end; the StockRelocated consumer (ADR 0010, TestStockConsumer_RealKafkaAndPostgres): a relocation with the move reference updates the plan's progress, a redelivery and a replay under a new id count once, an unmatched relocation is committed past, and the poison message is the only one on warehouse.inventory.events.dlq; the projector's consumer over a real analytical database (TestAnalyticsConsumer_RealKafkaAndPostgres)
internal/adapters/outbound/analyticsstorepostgres_integration_test.goPostgres: the shared contract over the real store (TestPostgres_Contract), the analytical migrations up and down repeatably, the claim and the effect commit atomically, an integrity violation becomes ErrRejected, the read-only pool cannot write, the SQL day windows equal the Go definition
cmd/apie2e_integration_test.goPostgres + Kafka: TestRunOnRealPostgresAndKafka boots the real run() and drives it only through REST and Kafka, including the exit when Kafka goes away
cmd/mcpmain_integration_test.goPostgres: the MCP binary migrates a database itself, reads through every tool what the api's write use cases persisted, and adds no outbox row (TestMCPAgainstPostgres_ReadsWhatTheAPIWroteAndNeverWrites)
internal/application/usecasesmain_integration_test.go, wiring_integration_test.goPostgres: the write use cases wired like cmd/api (real Postgres repositories, unit of work, CloudEvents encoder and read-model adapters; only the clock is fixed). The local copies are seeded through the real ledger, profile directory and slot catalogue, then generate, approve, a second approval that supersedes the first, regeneration stickiness and a rejection are checked against the persisted state and the read models (TestUsecases_WiringPlanLifecycleEndToEnd). Every outbox row the lifecycle wrote is decoded as a CloudEvents 1.0 envelope with its pinned payload (TestUsecases_WiringPublishedEventsCarryTheCloudEventsContract)

internal/testing/pgtest starts one postgres:16-alpine container per test binary and clones a migrated template database per test (pgtest.NewPool(t)); internal/testing/kafkatest starts one confluentinc/confluent-local:7.6.1 broker per test binary and gives each test its own timestamp-suffixed topic (kafkatest.Topic). Both start their container lazily, on first use. Each integration package has a TestMain that runs the tests and then calls pgtest.Shutdown() and/or kafkatest.Shutdown(). Neither helper reads DATABASE_URL or KAFKA_BROKERS and neither skips, so a missing Docker daemon fails the run. Two fitness tests keep it that way (TestPostgresIntegrationTestsUseTestcontainers, TestKafkaIntegrationTestsUseTestcontainers). They check imports, so a suite that only goes through the helpers still names the testcontainers module itself: the Kafka check wants testcontainers-go/modules/kafka in every Kafka-touching _integration_test.go file (the publisher suite keeps a tckafka reference for that), and the Postgres check wants testcontainers-go/modules/postgres somewhere in each package that uses pgx or database/sql (the usecases and pgtx suites keep a tcpostgres reference).

make integration and the CI integration job both run go test -tags=integration ./... -race -count=1, so every package above runs in CI with no explicit package list to keep in sync.

BDD (godog)​

features_test.go (TestFeatures) and features_wave2_test.go drive the real chi router over HTTP and feed the local copies through the real consumers' HandleMessage with raw CloudEvents, over the in-memory adapters wired the way cmd/api wires them, with a fixed clock (2026-10-08 12:00 UTC) and sequential plan ids. Strict mode: an undefined step fails.

Feature fileScenario / Scenario Outline blocks
features/generate_plan.feature9
features/generate_plan_request.feature6
features/approve_and_reject.feature10
features/plan_decisions_and_events.feature20
features/velocity_and_listing.feature5
Total50 (7 of them are outlines with example tables)

Mutation testing​

.gremlins.yaml: workers: 1, timeout-coefficient: 30, thresholds efficacy: 99 and mutant-coverage: 99 (gremlins fails at or below the threshold). Measured on 2026-10-08: internal/domain/slotplan 72 killed / 0 lived, internal/domain/planning 46 killed / 0 lived, both 100 %.

Architecture fitness tests​

internal/architecture (make arch-test, CI job arch-test):

TestRule
TestHexagonalArchitecturedomain imports nothing from application or adapters; ports holds interfaces only; adapters never import each other; internal/analytics/** imports nothing internal but itself, and the OLTP domain and application never import it or analyticsstore (ADR 0006) (arch-go)
TestRuntimeBinaryHasNoInMemoryAdapters, TestRuntimeBinarySensorBitesno file under cmd/** imports internal/adapters/outbound/memory (ADR 0011)
TestMCPAdapterDependencyRulethe MCP adapter (internal/adapters/inbound/mcp) depends only on the application and domain layers and nothing imports it
TestMCPOptionalToolInputsCarryOmitempty, TestMCPOptionalToolInputsSensorFailsOnBadFixturesan MCP tool input whose jsonschema description calls it optional (optional / omitted) has omitempty in its json tag, or the SDK would mark it required (gap fix D16)
TestOutboxRelaysPassAttemptCap, TestOutboxRelayCapSensorFailsOnBadFixturesevery non-test file under cmd/ that builds an outbox relay passes WithMaxAttempts (gap fix D12, ADR 0008)
TestNoAuthMiddlewareReintroducedno auth middleware on the router (fleet decision)
TestKafkaConsumerGroupNeverHardcodedInlinegroup ids come from the environment
TestKafkaIntegrationTestsUseTestcontainers, TestPostgresIntegrationTestsUseTestcontainers, TestPostgresIntegrationSensorFailsOnBadFixturesintegration tests boot real containers and never skip
TestNoEventEnvelopeToggleOrFlatEnvelope, TestCloudEventsOnlyCloudEvents 1.0 only, built in one package
TestReplayConsumersSetCommitIntervala reader whose GroupID is a per-run unique group must set CommitInterval (no such reader exists here; the four api consumers and the projector use env-provided groups and synchronous commits)
TestEventCatalogueMatchesContract, TestEventCatalogueDetectorthe published types match apis/asyncapi.yaml
TestKafkaWritersSetRequiredAcks, TestKafkaWriterAcksSensorBitesEvery kafka-go Writer composite literal in a non-test file under internal/ or cmd/ sets RequiredAcks (the import alias is resolved per file). kafka-go defaults it to RequireNone (acks=0): the broker never confirms the write, so a broker blip silently drops the message while WriteMessages returns nil. The twin proves the sensor flags a bad fixture under any alias.
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.)

Contract and API checks​

There is no schemathesis (or other runtime contract) job in this repository. The contracts are checked statically: the api-lint job runs Spectral on apis/openapi.yaml (.spectral.yaml) and apis/asyncapi.yaml (.spectral.asyncapi.yaml) with --fail-severity=warn, and the CloudEvents golden tests plus TestEventCatalogueMatchesContract tie the encoder to the AsyncAPI document.

Evals​

EVALS.md records the harness evaluations (tools/harness_eval.py, tools/harness_eval2.py): agent runs against inventory-storage and fulfillment-execution comparing guided and unguided agents. They are not tests of this service and do not run in CI.

CI​

.github/workflows/ci.yml (on push to main/develop, every pull request into them, weekly schedule, manual dispatch):

JobRunsOn a PR into develop
lintgolangci-lint v2.14.0blocking
guide-lintscripts/harness/guide_lint.py and test_hook.pyadvisory (continue-on-error)
complexitygolangci-lint with only gocyclo,gocognit,cyclop,funlen,nestif, plus an informational gocyclo reportblocking
testgo build, go vet, then make coverage (go test ./... -race with the Makefile's coverage scope, domain and application, and the 90 % gate)blocking
bddgo test ./... -run TestFeatures -vblocking
integrationgo test -tags=integration ./... -race -count=1 (testcontainers on the runner's Docker)blocking
mutation-fastgremlins on slotplan and planningblocking
mutationgremlins on ./internal/domainskipped (schedule and dispatch only); opens or closes a harness:red issue
driftdeadcode, go mod tidy -diff, coverage-quality reportskipped (schedule and dispatch only), advisory
api-lintSpectral on both specsblocking
vulngovulncheck ./...blocking
arch-testgo test ./internal/architecture/... -vblocking
helm-lintct lint and the Service selector testpull requests only
chart-testscharts/slotting-optimization/tests/render_test.sh (the api Deployment mounts the ConfigMap with envFrom; OUTBOX_MAX_ATTEMPTS defaults to 20 and renders 0; every os.Getenv / getenv literal of the four cmd/*/main.go is rendered into its Deployment; no ConfigMap key is read by no binary; mcp does not mount the ConfigMap; the analytics components render only with analytics.enabled and a DSN source, the projector without a Service and without the api's OLTP env), and test_service_selectors.py (tests/test_kong_config.py exists, but no CI job runs it)every push and PR; not a required check (branch protection unchanged)
trivy-scanbuilds the image locally and scans it with Trivy (SARIF uploaded; blocking on CRITICAL/HIGH with a fix available)pull requests only
docker-publish, releaseimage, signature, SBOM, Helm chart, GitHub releaseskipped (push to main only)

Other workflows: docs.yml builds this site on every pull request touching docs/** or apis/** and deploys GitHub Pages from main; selftest.yml runs the harness template's own checks (hook tests, repo_lint tests, Python compile, the architecture tests, the migration tool); ai-review.yml is the automated review workflow.