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.
Source: Makefile, .github/workflows/ci.yml, .gremlins.yaml, features/, internal/architecture/, internal/**/*_test.go, contracts/. Counts below are func Test... declarations and Gherkin scenarios counted in the tree on develop, not coverage claims.
The pyramid as it is
| Layer | Where | Count | Needs | Notes |
|---|---|---|---|---|
| Domain unit | internal/domain/{outboundload,shippingpackage,billoflading,shared} | 71 test functions | nothing | Invariants, transitions, rehydration validation, short-ship validity. Pure Go, no I/O. |
| Use-case unit | internal/application/usecases/*_test.go | 49 | nothing | The consumer policies and REST commands over the in-memory doubles (internal/adapters/outbound/memory): expect, scan, load commands, on-departure, edges, projector, queries. |
| Adapter unit | internal/adapters/kafka/cloudevents, internal/adapters/outbound/kafka | 8 | nothing | CloudEvents build and decode, writer settings. |
| BDD (godog) | features/*.feature (10 files), runner features/features_test.go (TestFeatures), steps in features_test.go, steps_rules_test.go, steps_rules_http_test.go, steps_rules_assert_test.go | 10 feature files, 139 Scenario/Scenario Outline definitions, 177 executed scenarios (1536 steps; none is tagged @known-bug any more) | nothing | Wires the use cases the REST and consumer surface needs (not only the first five), the in-memory board and idempotency stores and the real chi router with the Idempotency-Key middleware and Readiness (the same wiring as cmd/api buildHTTPServer), with an outbox recorder standing in for the relay. Strict mode. |
| Contract | internal/adapters/inbound/kafka/producer_contract_test.go, dock_contract_test.go, contracts/ | 5 | nothing | See below. |
| Integration | internal/adapters/outbound/postgres/service_integration_test.go (//go:build integration) | 3 (one is TestMain) | Docker | Real Postgres through testcontainers (internal/testing/pgtest): TestExpectPackagePlansExactlyOneLoadUnderConcurrency (the one-open-load race backstop) and TestServicePathOverPostgres (a full path through the real adapters). |
| Fitness (architecture) | internal/architecture/ | 13 files, 37 test functions | nothing | See below. |
| Mutation | .gremlins.yaml | n/a | gremlins v0.6.0 | See below. |
There are no handler unit tests for the REST adapter (internal/adapters/inbound/http; only the metrics tests and one problem-catalogue test) and none for the MCP adapter beyond the governance test (internal/adapters/inbound/mcp); the REST routes are covered by the BDD suite, which serves the real chi router with the Idempotency-Key middleware, and the MCP tools only indirectly (architecture sensors, the governance test, the Queries use case the BDD suite reads through). The Kafka consumers' decode paths are likewise exercised mostly through the use-case tests and the yard contract test. There is no end-to-end test of the Kafka consumers against a live broker in this repository (internal/testing/kafkatest exists as a helper; no test in the tree uses it).
The BDD scenarios
All six original scenarios are in features/ship_confirm_on_departure.feature: manifest, stage, load, close and depart with one bill of lading; a departure while LOADING that never confirms and flags what missed; a departure that arrives before the load closes (handled, never confirmed, and a re-delivery changes nothing); a departure delivered twice confirms once; a diverted package short-ships and the load still closes; the missed-load sweep flags once even when it runs twice.
Nine further *_rules.feature files pin the rules the documentation states (use-cases, aggregate canvas, troubleshooting, apis/openapi.yaml), one rule per scenario title:
| File | Definitions | Rules |
|---|---|---|
api_convention_rules.feature | 16 | Idempotency-Key (missing, 1, 128, 129 characters, replay, retryable release, reuse), malformed bodies, problem shape, query-parameter errors and limit bounds, /readyz, CloudEvents type, source and key |
bill_of_lading_rules.feature | 6 | content, void with reason, void twice, bol-not-found |
consumer_policy_rules.feature | 28 | ExpectPackage cutoff resolution (days of week, site timezone), schedule and layout replacement, BookAppointment (including the appointment-before-load gap as today's behaviour), DockTrailer, DivertPackage |
load_and_package_rules.feature | 30 | StagePackage, LoadPackage, UnloadPackage, CloseLoad (short-ships, outstanding packages, diverted once) |
load_board_rules.feature | 9 | the adherence report after each fold, loads_at_risk horizon |
load_lifecycle_rules.feature | 10 | reopen, cancel, confirmed loads, the cutoff key that plans a fresh load |
load_listing_rules.feature | 9 | list filters, pages and cursor (a last page that is exactly full has no nextCursor), packages by state |
missed_load_rules.feature | 14 | SweepMissedLoads at the cutoff, once across sweep and departure |
ship_confirm_rules.feature | 12 | every row of the OnDeparture table |
Scenarios tagged @known-bug describe a spec the code does not honour yet; the runner skips them unless BDD_TAGS selects them (BDD_TAGS=@known-bug go test ./features -run TestFeatures). None is open: the two the first BDD wave found are fixed (a short-ship entry without a reason is 400 bad-request; cancelling a ship-confirmed load is 409 load-confirmed), and the other divergences were ruled in ADR 0010. The one documented gap that remains, an appointment booked before its load, is pinned as today's behaviour and awaits ADR 0011 (Proposed).
Contract tests: the yard-management and dock-scheduling pins
contracts/yard-management.asyncapi.yaml is a copy of yard-management's apis/asyncapi.yaml on develop, listed in contracts/pinned.json. TestConsumedYardTypesMatchTheProducersIntegrationContract proves each consumed yard type (TrailerDocked, DoorWorkCompleted, TrailerDeparted) is declared on the producer's integration channel and that the producer's example decodes into the struct this service reads, with every field it acts on present; TestOnIntegrationChannelRejectsAnalyticsOnlyTypes proves the detector can fail. The CI job pinned-contracts (scripts/harness/pinned_contract_gate.py) fails when the pinned copy differs from the producer's develop (ADR 0006). The dock-scheduling contract is pinned the same way (ADR 0007): contracts/dock-scheduling.asyncapi.yaml is a copy of dock-scheduling's apis/asyncapi.yaml on develop (its AsyncAPI is 2.6, a channel with subscribe.message.oneOf), listed in contracts/pinned.json, with TestDockAppointmentBookedMatchesTheProducersIntegrationContract and its detector TestDockPublishedOnIntegrationIgnoresTheAnalyticsTwin. Both pins were refreshed against the producers' develop in PR 18. TestRealCptScheduleWithoutAVersionIsAccepted covers one more real producer payload. The other three consumed producers, process-path-management (CPTScheduleChanged), facility-layout (ZoneRegistered, LocationSlotRegistered) and fulfillment-execution (PackageManifested), are not in contracts/pinned.json: their payloads are mirrored by hand in cpt_layout_consumers.go and fulfillment_consumer.go (ADR 0007 lists the first and last as follow-ups).
Fitness tests (internal/architecture)
| Test | Guards |
|---|---|
TestHexagonalArchitecture | dependency direction between domain, application and adapters (arch-go). |
TestMCPAdapterDependencyRule | the MCP adapter depends inward on the application layer only. |
TestNoAuthMiddlewareReintroduced | no auth middleware in the REST or MCP routers. |
TestRuntimeBinaryHasNoInMemoryAdapters (+ TestRuntimeBinarySensorBites) | cmd/ never imports the memory adapters. |
TestNoGoFilesAtRepoRoot (+ two sensor tests) | no .go file at the repository root. |
TestKafkaConsumerGroupNeverHardcodedInline | group ids come from the environment. |
TestKafkaWritersSetRequiredAcks, TestKafkaWriterTopicNotSetTwice (+ ...SensorBites) | every writer sets RequiredAcks; no Topic on both Writer and Message. |
TestDeadLetterCallsGuardCancellation (+ ...SensorBites) | a dead-letter call checks for context cancellation first (shutdown is never a dead letter). |
TestReplayConsumersSetCommitInterval, TestCloudEventsOnly, TestNoEventEnvelopeToggleOrFlatEnvelope | CloudEvents 1.0 only, no envelope toggle. |
TestEventCatalogueMatchesContract (+ detector) | every type apis/asyncapi.yaml declares for this service is listed in ADR 0005. |
TestOutboxRelaysPassAttemptCap (+ two sensor tests) | the relay is built with WithMaxAttempts. |
TestMCPOptionalToolInputsCarryOmitempty (+ sensor test) | optional MCP inputs are not published as required. |
TestEveryMCPToolDeclaresAuthority, TestMCPWriteToolsAreAtLeastL3, TestA2ASkillsDeclareAuthority, TestMCPServerOffersResourceAndPrompt (+ five sensor tests) | agent surface rules: every MCP tool declares an authority level, write tools are L3 or above, the server offers a resource and a prompt. |
TestA2AAdapterDependencyRule, TestA2AAgentIsReadOnly (+ TestA2AReadOnlySensorBites) | the A2A adapter depends inward only and nothing depends on it; neither it nor cmd/a2a imports the Kafka client, relay, outbox or event sink, reads a Kafka or outbox variable, or builds a postgres write adapter (ADR 0013). |
TestGovernance_ToolSetIsPinnedAndHasNoWriteVerb, TestGovernance_EveryToolIsReadOnlyIdempotentClosedWorldWithItsLevel (+ TestGovernance_WriteVerbDetectorBites), in internal/adapters/inbound/mcp/governance_test.go (a unit test of the adapter, not of internal/architecture) | the real tools/list is exactly audit_load, get_bill_of_lading, get_closure_checklist, get_load, list_loads, loads_at_risk and missed_loads, no tool name carries a write verb, and each tool is read-only, idempotent, closed-world, non-destructive and at its pinned authority (audit_load L2, the rest L1; ADR 0014). stateless_test.go in the same package pins, with raw POSTs, that no Mcp-Session-Id is issued and server/discover answers. |
TestKafkaIntegrationTestsUseTestcontainers, TestPostgresIntegrationTestsUseTestcontainers (+ sensor test) | integration tests boot their own containers and never read DATABASE_URL. |
Mutation testing
.gremlins.yaml sets one worker, a timeout coefficient of 30 and thresholds efficacy: 90 and mutant-coverage: 90. The fast gate (make mutation, CI mutation-fast) runs gremlins on each domain package in turn: shared, outboundload, shippingpackage, billoflading, loadreview (88 mutants, all killed, when ADR 0014 landed). The exhaustive run (make mutation-full, CI mutation) runs ./internal/domain and is scheduled weekly (Monday 06:00 UTC), opening a harness:red issue when it fails.
Coverage gate
make coverage runs go test ./... -race with -coverpkg=./internal/domain/...,./internal/application/... and fails below 89 % (the Makefile notes 89.3 % measured). Adapters are outside that scope.
Make targets
| Target | Does | Needs |
|---|---|---|
make help | list targets | |
make build, make vet, make fmt, make fmt-check | build, vet, format, format check | |
make lint | golangci-lint run ./... (pinned v2.14.0) | golangci-lint |
make test | go test ./... -race (unit, godog, fitness; no integration) | |
make coverage | tests plus the 89 % 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 / make mutation-full | gremlins, fast per-package / exhaustive | gremlins |
make vuln | govulncheck ./... | govulncheck |
make check | fmt-check vet build lint test: the pre-commit loop | |
make check-all | check plus coverage arch-test bdd: run before pushing | |
make check-fast, make guide-lint, make harness-test | agent harness: fast gate, guide lint, hook tests | python3 |
make check is not enough to run the integration suite; integration is deliberately outside both check and check-all. lefthook runs fmt-check, vet and lint on commit and make check on push.
CI jobs (.github/workflows/ci.yml)
Triggers: push and PR on main and develop, a weekly schedule (mutation), manual dispatch.
| Job | Runs |
|---|---|
lint | golangci-lint |
guide-lint | the harness guide lint and hook tests |
pinned-contracts | pinned-contract gate tests; pins equal the producers' develop |
complexity | gocyclo report (gate 15) |
file-length | file length of the Go files a PR touches (blocking), backlog (informational) |
test | build, vet, make coverage |
bdd | go test ./... -run TestFeatures -v |
integration | go test -tags=integration ./... -race -count=1 |
mutation-fast | gremlins on every domain package |
mutation | exhaustive gremlins (schedule) |
drift | dead code, go mod tidy -diff, coverage-quality (schedule) |
api-lint | spectral over apis/openapi.yaml and apis/asyncapi.yaml |
vuln | govulncheck |
chart-tests | charts/outbound-shipping/tests/*.sh and test_*.py (render_test.sh, test_service_selectors.py; a test printing SKIP fails the job) |
arch-test | go test ./internal/architecture/... -v |
docs-api-drift | regenerates docs/docs/api-reference/rest from apis/openapi.yaml and fails when the committed files differ |
trivy-scan | pull requests only: builds the image locally (not pushed) and scans it with Trivy; blocks on CRITICAL or HIGH findings with a fix available |
docker-publish | image build, push, signing, SBOM: only on a push to main, after the required jobs above. Ran once, for v0.1.0. |
release | version, tag, chart package, GitHub release: only after docker-publish. Cut v0.1.0 on 2026-11-11. |
The documentation site is built by a separate workflow, .github/workflows/docs.yml (build on pull request, deploy on push to main or on manual dispatch). GitHub Pages is enabled for the repository and the site is at iqvo.github.io/outbound-shipping. main is protected: its required checks are lint, test, bdd, integration, mutation-fast, vuln, api-lint, arch-test and file-length. The first push to main failed vuln (GO-2026-6859) until go.mod moved to go 1.27.4 (PR 19).