testkit

package
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2026 License: Apache-2.0 Imports: 0 Imported by: 0

README

haistack-testkit (pkg/testkit)

Shared importable test support for HAIStack: FHIR fixtures, in-memory store fakes, sync and conflict scenario runners, OperationOutcome golden helpers, FHIRPath assertions, and AI executor harnesses.

This package is for tests only. Production code must not import pkg/testkit or any subpackage.

What it does

pkg/testkit consolidates helpers that were duplicated across package-local _test.go files into importable Go packages (not _test.go sources). Downstream tests can share:

Subpackage Role
fixtures Stable named presets (PatientJane, AppointmentBooked, …) as *types.ResourceEnvelope
factories Option-based builders for Patient, Appointment, Observation
storetest In-memory pkg/store implementations and a composed Backend
synctest Fake sync.Hub, device nodes, push/pull scenario runners
conflicttest Conflict detect/merge scenarios on top of sync fakes
golden Canonical OperationOutcome JSON comparison (inline goldens)
fhirpathtest FHIRPath evaluation and assertion wrappers
aitest Reusable ai.Executor harness with optional search/views/core
authztest Authorization scenario catalog (≥30 Go cases) plus YAML catalogues (ParseYAML / ScenariosFromYAML) that assert SMART scope ∩ policy
infernotest Inferno STU2 discovery + standalone SMART launch helpers and reference host

It does not:

  • Replace production persistence (pkg/sqlite, pkg/postgres, future pkg/store/memory)
  • Ship runtime behavior or production adapters
  • Delete existing package-local test helpers (migration is incremental)

When to use it

  • Writing sync tests without copying memHub / memResourceStore from pkg/sync/helpers_test.go
  • Writing store contract tests without copying mem stores from pkg/store/store_test.go
  • Building AI tool tests without copying pkg/ai/fixtures_test.go
  • Asserting OperationOutcome payloads from HTTP, client, core, or validate layers
  • Running FHIRPath expressions against shared patient/observation fixtures

Quick start — offline patient sync

import (
    "context"
    "testing"

    "github.com/degoke/haistack/pkg/testkit/fixtures"
    "github.com/degoke/haistack/pkg/testkit/synctest"
)

func TestOfflinePatientSync(t *testing.T) {
    ctx := context.Background()
    scenario := synctest.NewScenario(
        "tenant-a",
        synctest.FixedClock(synctest.At(2026, 7, 6, 12, 0, 0)),
    )

    patient := fixtures.PatientJane(t)
    result, err := synctest.OfflineCreateAndSync(ctx, scenario, patient)
    if err != nil {
        t.Fatal(err)
    }
    if result.PullSummary.Applied != 1 {
        t.Fatalf("pull = %+v", result.PullSummary)
    }
}

fixtures

Named presets return normalized envelopes via types.JSONCodec:

patient := fixtures.PatientJane(t)
appt := fixtures.AppointmentForPatient(t, patient.ID)
obs := fixtures.ObservationForPatient(t, patient.ID)

OfflinePatientCreate is an alias for the standard offline-create patient preset. Use EnvelopeFromProtoJSON when a test needs envelope.Proto populated.

factories

Builders accept functional options and return errors on invalid input:

patient, err := factories.NewPatient(
    factories.WithPatientID("pat-custom"),
    factories.WithFamilyName("Smith"),
    factories.WithTelecom("555-9999"),
)
appt, err := factories.NewAppointment(
    factories.WithPatientReference(patient.ID),
    factories.WithAppointmentStatus("booked"),
)

Prefer fixtures for stable cross-package scenarios; use factories when parameterizing ids, references, status, timestamps, or arbitrary FHIR metadata (WithPatientMeta, WithAppointmentMeta, and WithObservationMeta).

storetest

Backend bundles
device := storetest.NewDeviceBackend()  // lenient reads — sync device semantics
strict := storetest.NewStrictBackend()  // errors on missing resources

Backend exposes: Resources, History, Events, Cursors, Inbox, Conflicts, Search, Audit, and Jobs (jobs.NewInMemoryJobStore).

ListIDs is sorted and paged deterministically. WriteSessionProvider commits resource, history, search, and event snapshots together; Rollback discards them.

Strict vs lenient ResourceStore
Constructor Read when missing
NewResourceStore error
NewLenientResourceStore nil, nil

Match the constructor to the test: core/store tests use strict; sync device tests use lenient.

Seeding
ctx := context.Background()
_ = backend.Resources.Seed(ctx, patient, appt)

synctest

MemHub

NewMemHub() implements sync.Hub:

  • Idempotent push via processed event IDs (AckAlreadyProcessed)
  • Optional stale-base conflicts: hub.SetStaleOnMismatch(true)
  • Canonical event log: hub.CanonicalEvents()
Device and scenario
hub := synctest.NewMemHub()
device := synctest.NewDevice("device-a", "tenant-a", hub, clock)

_ = device.SeedLocalCreate(ctx, patient, clock())
push, _ := device.Push(ctx)

scenario := synctest.NewScenario("tenant-a", clock)
result, _ := synctest.OfflineCreateAndSync(ctx, scenario, patient, appt)

resolved, _ := synctest.ReferenceResolved(ctx, scenario.DeviceB, appt,
    "participant.0.actor", "Patient", "pat-jane")

ScenarioResult includes PushSummary, PullSummary, HubEvents, DeviceBResources, Conflicts, and AuditRecords.

conflicttest

scenario := conflicttest.NewScenario("tenant-a", clock)
edits, _ := conflicttest.DefaultConcurrentPatientEdits()

eval := scenario.Evaluate(
    conflicttest.LocalUpdate("Patient", "p1", edits.Base.VersionID, edits.LocalA.VersionID, edits.LocalA),
    edits.Base, edits.Cloud,
)

result, _ := scenario.RunTwoNodeStaleBaseConflict(ctx, edits)
merged, _ := scenario.RunAutoMergeResolution(ctx, edits)

Result exposes classification, merge metadata, push summary, conflict records, resolution push results, canonical events, and whether the path was auto-mergeable or review-required.

golden

Inline golden JSON only in v1 (no on-disk testdata workflow yet):

outcome := golden.DecodeOutcome(t, responseBody)
golden.AssertOutcomeCode(t, outcome, "not-found")
golden.AssertOutcomeMatchesGolden(t, outcome, `{
    "resourceType": "OperationOutcome",
    "issue": [{"severity":"error","code":"not-found"}]
}`)

AssertOutcomeEqual compares canonical JSON, ignoring whitespace differences. FormatMismatch produces readable diagnostics on failure.

fhirpathtest

eng := fhirpathtest.DefaultEngine(t)
patient := fixtures.PatientJane(t)

fhirpathtest.AssertString(t, eng, patient, "Patient.name.family", "Doe")
fhirpathtest.AssertEmpty(t, eng, patient, "Patient.address")

Uses pkg/fhirpath only — no duplicate engine logic.

aitest

h := aitest.NewHarness(t, aitest.Options{
    SeedPatients:            true,
    WithSearch:              true,
    AllowPatientRead:        true,
    AllowPatientSearch:      true,
    AllowPatientSummaryView: true,
})

// h.Executor, h.Resources, h.Audit, h.Approval, h.Deid are ready for assertions

Configuration is option-based: enable only the subsystems each test needs.

authztest

Documented authorization scenario catalog for CI (REST, patient compartment, SMART token semantics, view/AI/sync/module paths, scope-vs-policy conflicts):

import "github.com/degoke/haistack/pkg/testkit/authztest"

func TestAuthzScenarios(t *testing.T) {
    eng := authztest.DefaultEngine(t)
    authztest.RunAll(t, authztest.NewDefaultKit(eng))
}

AllScenarios() returns ≥30 named cases with Doc strings suitable for conformance matrices. OAuth success is not tested — only authorization outcomes.

Machine-readable YAML catalogues (used by research/policy-semantics) load through ParseYAML / ScenariosFromYAML and run with RunYAML (no Go BaseConfig kit). Every YAML principal must declare tenant and kind; every scenario must declare principal, scopes, action, resourceType, and policy. Omitting them is an error, not a fallback to TenantA / user / clinician / user/*.read / read / Patient / base. Those cases assert SMART.ScopeImplies ∩ pkg/auth policy. YAML view/AI actions call CanExecuteView / CanExecuteAITool on the auth engine; they do not load ViewDefinitions or run pkg/view / pkg/ai executors.

Migration

Existing helpers remain in place for incremental adoption:

Legacy location testkit replacement
pkg/sync/helpers_test.go synctest, storetest
pkg/store/store_test.go storetest
pkg/ai/fixtures_test.go aitest, fixtures
pkg/conflict/helpers_test.go conflicttest, factories

No production package should gain a dependency on pkg/testkit.

Where it fits

Package Role
types ResourceEnvelope, JSON codec, hashing
store Interface contracts implemented by storetest
jobs InMemoryJobStore reused by storetest.Backend
sync Hub/engine exercised by synctest
conflict Engine exercised by conflicttest
fhirpath Engine wrapped by fhirpathtest
ai Executor wired by aitest
testkit Shared test support (this tree)

Package docs

Each subpackage has a doc.go with godoc-oriented API notes. Start with doc.go for the tree overview.

Documentation

Overview

Package testkit implements haistack-testkit, the shared importable test-support library for HAIStack.

haistack-testkit consolidates FHIR resource fixtures, in-memory store fakes, sync and conflict scenario runners, OperationOutcome golden helpers, FHIRPath assertion wrappers, and AI executor harnesses that were previously duplicated across package-local _test.go files (for example pkg/sync/helpers_test.go, pkg/store/store_test.go, pkg/ai/fixtures_test.go).

Test-only boundary

This tree is for tests only. Production packages must not import pkg/testkit or any subpackage. Runtime persistence belongs in pkg/sqlite, pkg/postgres, and future pkg/store/memory adapters — not here.

Subpackages

  • fixtures — stable named presets (Patient, Appointment, Observation) as *types.ResourceEnvelope
  • factories — option-based envelope builders for MVP resource types
  • storetest — in-memory store.ResourceStore, HistoryStore, EventStore, and related fakes
  • synctest — fake sync.Hub, device nodes, and push/pull scenario runners
  • conflicttest — conflict detection and resolution scenarios on top of synctest
  • golden — canonical OperationOutcome JSON comparison (inline/embedded goldens)
  • parquettest — parquet export byte assertions for analytics/view/http tests
  • viewtest — patient_summary_view executor wiring for analytics/view/http integration tests
  • aitest — reusable ai.Executor harness with optional search, views, and core wiring (including shared resource/search stores and approval/model fakes)

Typical usage

Import only the subpackages a test needs:

import (
    "context"
    "testing"

    "github.com/degoke/haistack/pkg/testkit/fixtures"
    "github.com/degoke/haistack/pkg/testkit/synctest"
)

func TestOfflinePatientSync(t *testing.T) {
    ctx := context.Background()
    scenario := synctest.NewScenario("tenant-a", synctest.FixedClock(synctest.At(2026, 7, 6, 12, 0, 0)))
    patient := fixtures.PatientJane(t)
    result, err := synctest.OfflineCreateAndSync(ctx, scenario, patient)
    if err != nil {
        t.Fatal(err)
    }
    _ = result.PushSummary
    _ = result.PullSummary
}

Migration

Existing package-local test helpers are intentionally left in place. Downstream tests can migrate incrementally once pkg/testkit APIs prove stable. No production package should depend on this tree.

Dependencies

pkg/testkit may depend on pkg/types, pkg/store, pkg/sync, pkg/conflict, pkg/fhirpath, pkg/ai, pkg/search, pkg/view, pkg/core, pkg/validate, pkg/registry, pkg/proto, and pkg/jobs. There is no reverse dependency from production code back into pkg/testkit.

File layout

  • doc.go, keys.go, README.md — package overview
  • fixtures/ — named FHIR envelope presets
  • factories/ — option-based envelope builders
  • storetest/ — in-memory store implementations and Backend bundle
  • synctest/ — MemHub, Device, Scenario runners
  • conflicttest/ — conflict scenario utilities
  • golden/ — OperationOutcome comparison helpers
  • fhirpathtest/ — FHIRPath test assertions
  • aitest/ — AI executor harness and fakes

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ResourceKey

func ResourceKey(resourceType, id string) string

ResourceKey returns the canonical map key for a FHIR resource type and id.

Types

This section is empty.

Directories

Path Synopsis
Package aitest provides a reusable ai.Executor harness for tests, extracted from the pattern in pkg/ai/fixtures_test.go.
Package aitest provides a reusable ai.Executor harness for tests, extracted from the pattern in pkg/ai/fixtures_test.go.
Package authztest provides a reusable authorization scenario test kit for HAIStack.
Package authztest provides a reusable authorization scenario test kit for HAIStack.
Package conflicttest provides conflict scenario runners built on pkg/sync and pkg/conflict for tests.
Package conflicttest provides conflict scenario runners built on pkg/sync and pkg/conflict for tests.
Package factories builds normalized *types.ResourceEnvelope values for MVP resource types using a small options API.
Package factories builds normalized *types.ResourceEnvelope values for MVP resource types using a small options API.
Package fhirpathtest provides convenience wrappers around pkg/fhirpath for tests.
Package fhirpathtest provides convenience wrappers around pkg/fhirpath for tests.
Package fixtures provides stable, named FHIR resource presets as normalized *types.ResourceEnvelope values for tests.
Package fixtures provides stable, named FHIR resource presets as normalized *types.ResourceEnvelope values for tests.
Package golden provides comparison helpers for types.OperationOutcome in tests.
Package golden provides comparison helpers for types.OperationOutcome in tests.
Package infernotest provides helpers and a reference SMART host profile for Inferno conformance checks.
Package infernotest provides helpers and a reference SMART host profile for Inferno conformance checks.
Package parquettest provides helpers for asserting parquet export bytes in tests.
Package parquettest provides helpers for asserting parquet export bytes in tests.
Package storetest provides importable in-memory implementations of pkg/store interfaces used across HAIStack tests.
Package storetest provides importable in-memory implementations of pkg/store interfaces used across HAIStack tests.
Package synctest provides fake sync infrastructure and reusable push/pull scenario runners for tests.
Package synctest provides fake sync infrastructure and reusable push/pull scenario runners for tests.
Package viewtest builds view.Executor instances for integration tests.
Package viewtest builds view.Executor instances for integration tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL