Skip to main content

Testing

Every make target mirrors a job in .github/workflows/ci.yml, so a local pass predicts a CI pass. Two bundles cover most local runs:

make check # fmt-check vet build lint test (lefthook pre-push runs this)
make check-all # check + coverage (90% gate) + arch-test + bdd

None of the default targets needs Docker, Postgres or Kafka. Only the integration build tag starts containers.

Source: Makefile, .github/workflows/ci.yml, features/, internal/**/*_test.go.

Unit tests​

  • Command: make test (go test ./... -race). CI job test also runs go build ./..., go vet ./... and a gofmt check.
  • Scope: domain aggregates and pure functions (ClassifyTrend, DetectCoachingFlag, idleness.New, UtilizationPct), use cases over in-memory fakes (internal/application/usecases/fakes_test.go), HTTP handlers through httptest (internal/adapters/inbound/http/*_test.go), Kafka consumers over fake readers, golden-file tests for the CloudEvents wire format (internal/adapters/outbound/kafka/golden_cloudevents_test.go) and log publisher (internal/adapters/outbound/events/testdata/*.json), and the composition roots' wiring (cmd/labor/wiring_test.go, cmd/mcp/wiring_test.go).
  • Coverage gate: make coverage runs with -coverpkg=./internal/domain/...,./internal/application/...,./internal/analytics/... and fails below 90%. CI enforces it in the test job (which runs make coverage itself) and uploads coverage.out as an artifact.

The Makefile is the single source of the coverage scope and threshold (gap 16d): the CI test job runs make coverage instead of its own go test -coverpkg=... command, so the local and the PR gate cannot drift; harness repo_lint rule R11 (coverage-scope) forbids a workflow passing -coverpkg itself. Change the scope or the threshold in the Makefile only.

BDD acceptance tests (godog)​

  • Command: make bdd (go test ./... -run TestFeatures -v). CI job: bdd.
  • Wiring: features_test.go and features_wave2_test.go drive the real chi router (httptest.NewServer(inboundhttp.NewRouter(...))) over the in-memory adapters. Kafka-driven steps call RecordTaskPerformance directly.
  • Features: 19 files under features/ hold 158 Scenario/Scenario Outline blocks (30 of them outlines; count with git grep -c -E "^[[:space:]]*Scenario" -- features). No block 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 158 blocks as 249 executed scenarios and 1593 steps (249 scenarios (249 passed), 1593 steps (1593 passed), godog's own summary from go test . -run TestFeatures -count=1 -v):
FileScenariosExecutedFeature
features/event_contract_rules.feature1212The event contract other contexts and the projector rely on: topic, key, subject, type, dataschema, CloudEvents source/time, field omission, double publication, null efficiency/idle never zero
features/handling_unit_standards.feature1313Engineered standards per handling unit and the declared team lift (ADR 0035)
features/performance_scoring.feature1317Scoring completed tasks and reading the scorecard
features/readiness_rules.feature78Readiness, liveness and graceful shutdown: dependency outage is 503 while liveness stays green, every failing dependency named, drain before dependencies, verdict caching
features/reports_rules.feature1733The labor-performance report read model: hour bucket, UNCLASSIFIED bucket, volume-weighted totals, half-open [from,to) window, invalid-report-query, task-type filter, freshness lag
features/rest_surface_rules.feature38What a browser may call (CORS preflight) and how a malformed window degrades
features/scorecard.feature11Reading an associate's performance scorecard
features/scorecard_rules.feature47Scorecard trend, coaching flag and per-task-type breakdown at their boundaries
features/scoring_rules.feature816Scoring completions and deriving idle gaps: efficiency, unscorable task types, idle cap, dedupe on the event id
features/standard_rules.feature1641Standard history, as-of scoring and the problem catalogue, including the RFC 7807 resource-not-found for an unknown route
features/standards.feature55Defining and reading engineered labor standards
features/standards_events_and_validation.feature1218Defining standards and the events that announce them
features/task_type_performance.feature22Reading fleet-wide TaskType performance
features/task_type_performance_data.feature99Reading fleet-wide performance for a task type
features/travel_component.feature55Declaring an optional travel component on a labor standard
features/trend_and_coaching.feature618Reading performance trends and coaching signals
features/utilization.feature44Reading idle-gap utilization over a trailing window
features/utilization_data.feature1722Measuring utilization from recorded idle gaps
features/utilization_rules.feature410Utilization windows and the open gap at their boundaries
19 files158249

The *_rules.feature files pin the rules written in the documentation; their steps are in steps_rules_test.go, steps_reports_rules_test.go and steps_wire_rules_test.go. The scenario "A request for a route that does not exist is a resource-not-found problem" (standard_rules.feature) pins the RFC 7807 404 for an unknown route (and internal/adapters/inbound/http/route_problems_test.go pins it, plus the 405 method-not-allowed, on both routers). It was a @known-bug until both routers got a chi NotFound/MethodNotAllowed handler; BDD_TAGS=@known-bug go test . -run TestFeatures -count=1 now selects no scenario.

A separate feature file, internal/adapters/inbound/mcp/testdata/features/mcp_tools.feature (15 scenarios), drives the MCP behavioral evals below.

Integration tests (testcontainers)​

  • Command: go test -tags=integration ./... -race -count=1. CI job: integration, with no service containers: each test starts its own Postgres and/or Kafka through testcontainers-go on the runner's Docker.
  • Narrow target: make integration-kafka-testcontainers runs TestConsumer_ProjectsRealBrokerMessages against an isolated Kafka container.
  • Files (all //go:build integration, 23 in total; besides the ones below, internal/application/usecases/usecases_wiring_integration_test.go and internal/adapters/inbound/mcp/streamable_http_integration_test.go):
    • Postgres repos: internal/adapters/outbound/postgres/{integration,standard_repo,performance_repo,idle_period_repo}_integration_test.go
    • outbox and relay: outbox_integration_test.go (including the attempt cap of ADR 0032: TestOutboxRelay_MaxAttempts_PoisonRowIsExcludedAndTheNextRowPublishes, TestOutboxRelay_WithoutMaxAttempts_RetriesWithoutBound), outbox_lag_integration_test.go, and trace continuity across the outbox to a real broker (outbox_trace_kafka_integration_test.go: TestOutboxTrace_TraceparentCrossesTheOutboxToKafka, TestOutboxTrace_RowWithoutTraceHeadersRelaysUnchanged)
    • sweeper: sweeper_integration_test.go
    • handling-unit standards and team lift (ADR 0035): internal/adapters/outbound/postgres/handling_unit_integration_test.go (round trip, the widened one-open index, the CHECK constraints, migration 0007 up and down with data, the outbox payloads) and internal/adapters/inbound/kafka/handling_integration_test.go (a real broker into real Postgres)
    • pool limits (statement_timeout really applied): pool_limits_integration_test.go
    • analytics store: internal/adapters/outbound/analyticsstore/postgres_integration_test.go
    • idempotency middleware, including concurrent same-key requests: internal/adapters/inbound/http/idempotency_integration_test.go, idempotency_conflict_integration_test.go
    • idempotency replay classes (ADR 0039): the unit tests in internal/adapters/inbound/http/replay_class_test.go (no Docker), the harness template over a real Postgres (idempotency_replay_classes_integration_test.go and its wiring file), and idempotency_retryable_integration_test.go (the loser's key row is absent and its retry under the same key executes)
    • Kafka consumers and DLQ (real broker), including DLQ topic auto-creation: internal/adapters/inbound/kafka/consumer_integration_test.go, consumer_dlq_integration_test.go, consumer_dlq_autocreate_integration_test.go, analytics_consumer_integration_test.go
    • integration publisher: internal/adapters/outbound/kafka/integration_publisher_integration_test.go
    • the real runtime end to end (ADR 0034): cmd/labor/e2e_integration_test.go (TestRunOnRealPostgresAndKafka) boots run() on a Postgres and a Kafka container with only the deployment's environment and drives REST and Kafka only; the NUL guard is pinned on real Postgres by TestNUL_IsAClientErrorAndDoesNotConsumeTheKey
  • Boot-config and sensor tests (no containers, run in make test/make arch-test): cmd/labor/bootconfig_test.go, cmd/labor-projector/config_test.go, cmd/mcp/wiring_test.go (every mandatory variable is a boot error that names it); TestRuntimeBinaryHasNoInMemoryAdapters and its TestRuntimeBinarySensorBites in internal/architecture (no non-test file under cmd/** imports internal/adapters/outbound/memory).
  • Guard rails: the fitness tests TestPostgresIntegrationTestsUseTestcontainers and TestKafkaIntegrationTestsUseTestcontainers fail the build if an integration test skips on DATABASE_URL or KAFKA_BROKERS, or hard-codes localhost:9092. A skip-gated test would silently prove nothing in CI.

Contract tests (Schemathesis)​

  • Command: make contract (scripts/contract-test.sh). CI job: contract. Needs st: python3 -m pip install 'schemathesis==4.28.0'.
  • How: builds cmd/labor, starts it on 127.0.0.1:18083 (CONTRACT_PORT) against a real Postgres and Kafka (DATABASE_URL and KAFKA_BROKERS are required; CI provides postgres:16 and confluent-local service containers, locally docker compose up -d --wait postgres kafka), waits for /readyz, then runs st run apis/openapi.yaml --max-examples 100 --workers 4 (CONTRACT_MAX_EXAMPLES overrides the example count).
  • Excluded operations: defineStandard (the cross-field rule travel ≤ expected cannot be expressed in OpenAPI 3.0.3), and getTaskTypeUtilization/getAssociateUtilization (the service ignores unknown query params on purpose). The script comments name the unit tests that cover these instead.
  • apis/openapi-reports.yaml has no contract run. It is linted by api-lint and covered by reports_handler_test.go.

MCP evals (E1–E3)​

  • Command: go test ./internal/adapters/inbound/mcp/... -race -run '^TestEval|^TestMCPEvalSuite' -v. CI job: evals-tests. The same tests also run in the test job.
  • E1, schemas and metadata (eval_governance_test.go): input schemas resolve and reject wrong types, every parameter has a description, the tool list matches testdata/tool_registry.golden, and tool names are unique across testdata/fleet_tool_snapshot.golden.
  • E2, wire conformance (eval_conformance_test.go, 9 tests): the initialize handshake, rejection of unknown tools, wrong-typed or extra arguments, unknown resources and prompts, discovery of the resource template and prompt, and the closed-session behaviour.
  • E3, behavioral (evalsuite_test.go, TestMCPEvalSuite): runs the 15 scenarios in testdata/features/mcp_tools.feature.
  • governance_test.go enforces the charter: at most 8 tools, verb_noun names, annotations and descriptions present (ADR 0030).
  • metrics_test.go pins the charter's invocation and denial counters (ADR 0033): TestToolMetrics_CountInvocationsByOutcomeAndDenialsByReason drives the real server over the in-memory transport with an SDK manual metric reader (ok, handler errors, schema denials, an unknown tool), TestToolMetrics_OtherMethodsAreNotCounted and TestClassify.

Mutation testing (gremlins)​

  • Config: .gremlins.yaml, with workers: 1, timeout-coefficient: 30, thresholds efficacy: 99 and mutant-coverage: 99. gremlins fails when the measured value is at or below the threshold, so effectively 100% is required.
  • make mutation-fast runs gremlins unleash ./internal/domain/performance. CI job mutation-fast runs on every push and PR and blocks merges.
  • make mutation runs gremlins unleash ./internal/domain --workers 1 --timeout-coefficient 30. CI job mutation runs only on the weekly schedule (Monday 06:00 UTC) or by workflow_dispatch. A scheduled failure opens or refreshes a harness:red issue through scripts/harness/red_issue.py.
  • gremlins v0.6.0 is pinned in the Makefile and CI.

Architecture fitness tests​

  • Command: make arch-test (go test ./internal/architecture/... -v). CI job: arch-test (ADR 0026).
TestEnforces
TestHexagonalArchitecturearch-go dependency rules: domain imports nothing, application only domain, analytics isolated from OLTP.
TestMCPAdapterDependencyRuleThe MCP adapter depends only on the application layer.
TestNoAuthMiddlewareReintroducedNo REST/MCP auth middleware comes back (ADR 0012).
TestNoSiblingContextOutboundCallsinternal/adapters/outbound never imports net/http as a client, so there are no synchronous calls to sibling contexts.
TestKafkaConsumerGroupNeverHardcodedInlineA kafka-go GroupID is never assigned an inline string literal. It must come from a named constant, a variable or a function call.
TestKafkaIntegrationTestsUseTestcontainers, TestPostgresIntegrationTestsUseTestcontainers (+ fixture self-test)Integration tests start their own containers.
TestNoStructTagsInDomain (+ fixture self-test)No JSON or db struct tags in internal/domain.
TestCloudEventsOnlyKafka code uses the CloudEvents SDK (no hand-built envelopes), and nothing mentions the retired EVENT_ENVELOPE_MODE toggle.
TestReplayConsumersSetCommitIntervalA full-replay consumer whose group id comes from a "unique group" function call must set CommitInterval.
TestEventCatalogueMatchesContract, TestEventCatalogueDetectorEvery CloudEvents type that apis/asyncapi.yaml declares for this service also appears in a CloudEvents ADR under docs/docs/adr/.
TestOutboxRelaysPassAttemptCap (+ TestOutboxRelayCapSensorFailsOnBadFixtures)Every non-test file under cmd/ that calls NewOutboxRelay passes WithMaxAttempts, so the relay attempt cap is always explicit (ADR 0032).
TestMCPOptionalToolInputsCarryOmitempty (+ TestMCPOptionalToolInputsSensorFailsOnBadFixtures)An MCP tool input field whose jsonschema description says it is optional (the word "optional", or "when/if omitted") carries omitempty in its json tag. Without it the MCP SDK marks the field required and a call that leaves it out is rejected before the handler runs (gap fix D16).
TestKafkaWritersSetRequiredAcks (+ TestKafkaWriterAcksSensorBites)Every 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.)

Other CI jobs​

JobRunsWhen
lintgolangci-lint v2.13.1 (.golangci.yml)push/PR
complexitygolangci-lint --enable-only gocyclo,gocognit,cyclop,funlen,nestif, plus an informational gocyclo reportpush/PR
guide-lintscripts/harness/guide_lint.py, repo_lint.py and their tests (make guide-lint, make harness-test)push/PR
api-lintSpectral on apis/openapi.yaml, apis/openapi-reports.yaml (.spectral.yaml) and apis/asyncapi.yaml (.spectral.asyncapi.yaml). make api-lint.push/PR
vulngovulncheck v1.7.0 (make vuln)push/PR
docs-api-driftIn docs/: npm ci, npm run clean-api-docs:all && npm run gen-api-docs:all, then fails on any diff under docs/api-reference/rest or rest-reportspush/PR
webIn web/: builds IQVO/warehouse-ui-kit@develop, then npm ci, npm run lint, npx tsc -b, npm test (vitest), npm run buildpush/PR
driftdeadcode, go mod tidy -diff, knip on web/, and a coverage-quality cross-check (scripts/coverage-quality.py). Advisory.schedule / dispatch
chart-testsrender_test.sh, render-assertions.sh and test_service_selectors.py under charts/labor-performance/tests/ (make chart-test)push/PR
helm-lintct lint --charts charts/labor-performancePRs into main only
trivy-scanBuilds the image and gates on CRITICAL/HIGH CVEs that have a fixPRs into main only
docker-publish, releaseGHCR image (cosign-signed, SPDX SBOM), git tag, Helm chart to oci://ghcr.io/iqvopush to main only

Separate workflows: codeql.yml (CodeQL), scorecard.yml (OpenSSF Scorecard), ai-review.yml, and docs.yml. docs.yml builds the Docusaurus site on every pull request that touches docs/**, apis/** or the workflow itself (build only, nothing is published), and builds and deploys it to GitHub Pages on pushes to main (gap fix D25).

Chart tests run in the chart-tests CI job on every push and PR (make chart-test locally; needs helm and Python 3 with PyYAML):

  • charts/labor-performance/tests/render_test.sh: the api Deployment mounts the chart ConfigMap with envFrom (gap fix D14), the OUTBOX_MAX_ATTEMPTS default and 0, a 0s housekeeping interval, the MCP probes are httpGet /healthz (D24), and no other workload mounts the api ConfigMap;
  • charts/labor-performance/tests/render-assertions.sh: the frontend workload is off by default, ClusterIP and never publicly exposed;
  • charts/labor-performance/tests/test_service_selectors.py: every Service selects exactly one component. It fails (no longer skips) when PyYAML is missing.

Git hooks​

lefthook.yml defines pre-commit (fmt-check, vet, lint) and pre-push (make check). Hooks are not tracked by git. Activate them once per clone or worktree with lefthook install.