Skip to main content

Testing

Synced from outbound-shipping

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​

LayerWhereCountNeedsNotes
Domain unitinternal/domain/{outboundload,shippingpackage,billoflading,shared}71 test functionsnothingInvariants, transitions, rehydration validation, short-ship validity. Pure Go, no I/O.
Use-case unitinternal/application/usecases/*_test.go49nothingThe consumer policies and REST commands over the in-memory doubles (internal/adapters/outbound/memory): expect, scan, load commands, on-departure, edges, projector, queries.
Adapter unitinternal/adapters/kafka/cloudevents, internal/adapters/outbound/kafka8nothingCloudEvents 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.go10 feature files, 139 Scenario/Scenario Outline definitions, 177 executed scenarios (1536 steps; none is tagged @known-bug any more)nothingWires 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.
Contractinternal/adapters/inbound/kafka/producer_contract_test.go, dock_contract_test.go, contracts/5nothingSee below.
Integrationinternal/adapters/outbound/postgres/service_integration_test.go (//go:build integration)3 (one is TestMain)DockerReal 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 functionsnothingSee below.
Mutation.gremlins.yamln/agremlins v0.6.0See 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:

FileDefinitionsRules
api_convention_rules.feature16Idempotency-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.feature6content, void with reason, void twice, bol-not-found
consumer_policy_rules.feature28ExpectPackage 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.feature30StagePackage, LoadPackage, UnloadPackage, CloseLoad (short-ships, outstanding packages, diverted once)
load_board_rules.feature9the adherence report after each fold, loads_at_risk horizon
load_lifecycle_rules.feature10reopen, cancel, confirmed loads, the cutoff key that plans a fresh load
load_listing_rules.feature9list filters, pages and cursor (a last page that is exactly full has no nextCursor), packages by state
missed_load_rules.feature14SweepMissedLoads at the cutoff, once across sweep and departure
ship_confirm_rules.feature12every 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)​

TestGuards
TestHexagonalArchitecturedependency direction between domain, application and adapters (arch-go).
TestMCPAdapterDependencyRulethe MCP adapter depends inward on the application layer only.
TestNoAuthMiddlewareReintroducedno 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.
TestKafkaConsumerGroupNeverHardcodedInlinegroup 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, TestNoEventEnvelopeToggleOrFlatEnvelopeCloudEvents 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​

TargetDoesNeeds
make helplist targets
make build, make vet, make fmt, make fmt-checkbuild, vet, format, format check
make lintgolangci-lint run ./... (pinned v2.14.0)golangci-lint
make testgo test ./... -race (unit, godog, fitness; no integration)
make coveragetests plus the 89 % gate
make bddgo test ./... -run TestFeatures -v
make arch-testgo test ./internal/architecture/... -v
make integrationgo test -tags=integration ./... -race -count=1Docker
make mutation / make mutation-fullgremlins, fast per-package / exhaustivegremlins
make vulngovulncheck ./...govulncheck
make checkfmt-check vet build lint test: the pre-commit loop
make check-allcheck plus coverage arch-test bdd: run before pushing
make check-fast, make guide-lint, make harness-testagent harness: fast gate, guide lint, hook testspython3

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.

JobRuns
lintgolangci-lint
guide-lintthe harness guide lint and hook tests
pinned-contractspinned-contract gate tests; pins equal the producers' develop
complexitygocyclo report (gate 15)
file-lengthfile length of the Go files a PR touches (blocking), backlog (informational)
testbuild, vet, make coverage
bddgo test ./... -run TestFeatures -v
integrationgo test -tags=integration ./... -race -count=1
mutation-fastgremlins on every domain package
mutationexhaustive gremlins (schedule)
driftdead code, go mod tidy -diff, coverage-quality (schedule)
api-lintspectral over apis/openapi.yaml and apis/asyncapi.yaml
vulngovulncheck
chart-testscharts/outbound-shipping/tests/*.sh and test_*.py (render_test.sh, test_service_selectors.py; a test printing SKIP fails the job)
arch-testgo test ./internal/architecture/... -v
docs-api-driftregenerates docs/docs/api-reference/rest from apis/openapi.yaml and fails when the committed files differ
trivy-scanpull requests only: builds the image locally (not pushed) and scans it with Trivy; blocks on CRITICAL or HIGH findings with a fix available
docker-publishimage build, push, signing, SBOM: only on a push to main, after the required jobs above. Ran once, for v0.1.0.
releaseversion, 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).