Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Cover replay bundle loading, magic link expiry and subscription mapping
rcourtmanc757a73382e0
diff --git a/internal/ai/qualification/replay_load_branchcov0723am_test.go b/internal/ai/qualification/replay_load_branchcov0723am_test.gonew file mode 100644index 0000000000..9fdfb3c0b0--- /dev/null+++ b/internal/ai/qualification/replay_load_branchcov0723am_test.go@@ -0,0 +1,295 @@+package qualification++import (+ "encoding/json"+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"+ "time"+)++// qualreplay0723write is a tiny helper that writes payload to a fresh file+// inside the test's temp dir and returns its path. Every LoadReplayBundle+// fixture is produced from scratch in t.TempDir(); no checked-in fixtures are+// read.+func qualreplay0723write(t *testing.T, name string, payload []byte) string {+ t.Helper()+ path := filepath.Join(t.TempDir(), name)+ if err := os.WriteFile(path, payload, 0o600); err != nil {+ t.Fatalf("write fixture %q: %v", path, err)+ }+ return path+}++// TestBranchcov0723AmLoadReplayBundle covers every branch of LoadReplayBundle+// in replay.go: the os.ReadFile error path (both missing path and a directory+// where a file is expected), the json.Decode failure path (malformed JSON and+// an empty file yielding io.EOF), the trailing-data block (both the+// multiple-values arm where the second decode succeeds and the trailing-garbage+// arm where it fails), DisallowUnknownFields rejection, the NewReplaySession+// validation passthrough (unsupported schema, incomplete capture, malformed+// exchange), and the success path asserting every ReplayBundle field+// round-trips through disk + JSON.+func TestBranchcov0723AmLoadReplayBundle(t *testing.T) {+ validBundle := ReplayBundle{+ SchemaVersion: ReplaySchemaVersion,+ CapturedAt: time.Unix(1_700_000_000, 0).UTC(),+ RunID: "run-abc",+ ManifestID: "watch.test-fixture",+ ManifestDigest: "sha256:deadbeef",+ Model: "provider:test-model",+ GroundTruth: GroundTruth{+ SchemaVersion: "patrol.qualification.ground_truth/v1",+ ManifestID: "watch.test-fixture",+ ManifestDigest: "sha256:deadbeef",+ RunID: "run-abc",+ CreatedAt: time.Unix(1_699_999_999, 0).UTC(),+ Baseline: []PredicateObservation{{+ Predicate: Predicate{Probe: "docker.running", Target: "target", Operator: "eq", Value: json.RawMessage("true")},+ Observed: true, Passed: true, CheckedAt: time.Unix(1_699_999_998, 0).UTC(),+ }},+ Faults: []FaultTruth{{+ ID: "fault", CausalGroup: "fault", TargetAlias: "target", TargetName: "pulse-target",+ ResourceType: "app-container", Active: true, ConfirmedAt: time.Unix(1_699_999_997, 0).UTC(),+ Observations: []PredicateObservation{{+ Predicate: Predicate{Probe: "docker.running", Target: "target", Operator: "eq", Value: json.RawMessage("false")},+ Observed: false, Passed: true, CheckedAt: time.Unix(1_699_999_996, 0).UTC(),+ }},+ }},+ Negative: []NegativeTruth{{Alias: "noise", Name: "pulse-noise", Reason: "scraper sidecar"}},+ Resources: map[string]CollectedTruth{+ "target": {Alias: "target", Name: "pulse-target", ResourceID: "id-target", ResourceType: "app-container", Status: "running", ObservedAt: time.Unix(1_699_999_995, 0).UTC()},+ },+ },+ Exchanges: []ToolExchange{{+ Sequence: 1, ToolCallID: "call-1", ToolName: "get_resource",+ CanonicalInput: `{}`, Output: `{"status":"ok"}`, Success: true,+ }},+ AIAnalysis: "analysis text",+ Findings: []Finding{{+ ID: "f1", Key: "k1", Severity: "warning", Category: "reliability",+ ResourceID: "id-target", ResourceName: "pulse-target", ResourceType: "app-container",+ Title: "t", Description: "d", Recommendation: "r", Evidence: "e",+ DetectedAt: time.Unix(1_699_999_994, 0).UTC(), LastSeenAt: time.Unix(1_699_999_993, 0).UTC(),+ }},+ Replayable: true,+ }+ validPayload, err := json.Marshal(validBundle)+ if err != nil {+ t.Fatalf("marshal fixture: %v", err)+ }++ for _, tc := range []struct {+ name string+ path func(t *testing.T) string+ wantErr bool+ errSubstr string+ // result is only checked on the success path; it must equal validBundle.+ checkResult func(t *testing.T, got ReplayBundle)+ }{+ {+ name: "missing path surfaces os read error",+ path: func(t *testing.T) string {+ return filepath.Join(t.TempDir(), "does-not-exist.json")+ },+ wantErr: true,+ },+ {+ name: "directory where file is expected surfaces read error",+ path: func(t *testing.T) string {+ return t.TempDir() // a directory, not a file+ },+ wantErr: true,+ },+ {+ name: "invalid json returns decoder error",+ path: func(t *testing.T) string {+ return qualreplay0723write(t, "bundle.json", []byte("{not json"))+ },+ wantErr: true,+ },+ {+ name: "empty file returns decoder error",+ path: func(t *testing.T) string {+ return qualreplay0723write(t, "empty.json", []byte{})+ },+ wantErr: true,+ },+ {+ name: "trailing second value rejected as multiple json values",+ path: func(t *testing.T) string {+ // `{}` decodes into ReplayBundle with zero values; the trailing+ // `{}` decodes successfully, hitting the multiple-values arm.+ return qualreplay0723write(t, "multi.json", []byte("{}{}"))+ },+ wantErr: true,+ errSubstr: "multiple JSON values",+ },+ {+ name: "trailing garbage rejected with decode error",+ path: func(t *testing.T) string {+ // First `{}` decodes; ` junk` fails to decode, hitting the+ // trailing-garbage arm (err != nil && err != io.EOF).+ return qualreplay0723write(t, "garbage.json", []byte("{} junk"))+ },+ wantErr: true,+ },+ {+ name: "unknown field rejected by DisallowUnknownFields",+ path: func(t *testing.T) string {+ return qualreplay0723write(t, "unknown.json", []byte(`{"schema_version":"`+ReplaySchemaVersion+`","surprise_field":1}`))+ },+ wantErr: true,+ },+ {+ name: "missing required schema version surfaces replay session error",+ path: func(t *testing.T) string {+ // `{}` has no schema_version; NewReplaySession rejects it.+ return qualreplay0723write(t, "noschema.json", []byte("{}"))+ },+ wantErr: true,+ errSubstr: "unsupported replay schema",+ },+ {+ name: "wrong schema version surfaces replay session error",+ path: func(t *testing.T) string {+ return qualreplay0723write(t, "badschema.json", []byte(`{"schema_version":"wrong"}`))+ },+ wantErr: true,+ errSubstr: "unsupported replay schema",+ },+ {+ name: "non-empty replay issues block load via session validation",+ path: func(t *testing.T) string {+ bundle := validBundle+ bundle.Replayable = false+ bundle.ReplayIssues = []string{"tool call x input is not complete JSON: unexpected EOF"}+ payload, err := json.Marshal(bundle)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ return qualreplay0723write(t, "issues.json", payload)+ },+ wantErr: true,+ errSubstr: "replay capture is incomplete",+ },+ {+ name: "malformed exchange in bundle blocks load via session validation",+ path: func(t *testing.T) string {+ bundle := validBundle+ bundle.Exchanges = []ToolExchange{{Sequence: 1, ToolName: "", CanonicalInput: "{}"}}+ payload, err := json.Marshal(bundle)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ return qualreplay0723write(t, "badexch.json", payload)+ },+ wantErr: true,+ errSubstr: "invalid replay exchange at index 0",+ },+ {+ name: "valid bundle round-trips every field",+ path: func(t *testing.T) string {+ return qualreplay0723write(t, "valid.json", validPayload)+ },+ checkResult: func(t *testing.T, got ReplayBundle) {+ if !reflect.DeepEqual(got, validBundle) {+ t.Fatalf("round-trip mismatch:\n got = %+v\n want = %+v", got, validBundle)+ }+ },+ },+ } {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ got, err := LoadReplayBundle(tc.path(t))+ if tc.wantErr {+ if err == nil {+ t.Fatalf("LoadReplayBundle error = nil, want non-nil")+ }+ if tc.errSubstr != "" && !strings.Contains(err.Error(), tc.errSubstr) {+ t.Fatalf("LoadReplayBundle error = %q, want substring %q", err.Error(), tc.errSubstr)+ }+ return+ }+ if err != nil {+ t.Fatalf("LoadReplayBundle error = %v, want nil", err)+ }+ if tc.checkResult != nil {+ tc.checkResult(t, got)+ }+ })+ }+}++// TestBranchcov0723AmEnsureArtifactRoot covers every branch of+// EnsureArtifactRoot in runner.go: the empty-root early error, the fresh-path+// creation with the source's 0o700 permission, idempotence over an+// already-existing directory, and the failure when a parent path is a regular+// file rather than a directory. All filesystem activity is contained inside+// per-subtest t.TempDir() roots.+func TestBranchcov0723AmEnsureArtifactRoot(t *testing.T) {+ t.Run("empty root returns the dedicated error", func(t *testing.T) {+ err := EnsureArtifactRoot("")+ if err == nil {+ t.Fatalf("EnsureArtifactRoot(\"\") error = nil, want non-nil")+ }+ if !strings.Contains(err.Error(), "artifact root is empty") {+ t.Fatalf("EnsureArtifactRoot(\"\") error = %q, want substring %q", err.Error(), "artifact root is empty")+ }+ })++ t.Run("fresh path creates directory with expected permissions", func(t *testing.T) {+ root := filepath.Join(t.TempDir(), "fresh-artifacts")+ if err := EnsureArtifactRoot(root); err != nil {+ t.Fatalf("EnsureArtifactRoot(%q) error = %v, want nil", root, err)+ }+ info, err := os.Stat(root)+ if err != nil {+ t.Fatalf("stat created root: %v", err)+ }+ if !info.IsDir() {+ t.Fatalf("EnsureArtifactRoot(%q) did not create a directory: mode=%v", root, info.Mode())+ }+ if got := info.Mode() & os.ModePerm; got != 0o700 {+ t.Fatalf("EnsureArtifactRoot(%q) perm = %o, want 0o700", root, got)+ }+ })++ t.Run("already existing directory is idempotent", func(t *testing.T) {+ root := filepath.Join(t.TempDir(), "existing-artifacts")+ if err := os.MkdirAll(root, 0o755); err != nil {+ t.Fatalf("seed existing dir: %v", err)+ }+ if err := EnsureArtifactRoot(root); err != nil {+ t.Fatalf("EnsureArtifactRoot on existing dir error = %v, want nil", err)+ }+ info, err := os.Stat(root)+ if err != nil {+ t.Fatalf("stat existing root after call: %v", err)+ }+ if !info.IsDir() {+ t.Fatalf("EnsureArtifactRoot clobbered existing directory: mode=%v", info.Mode())+ }+ })++ t.Run("parent is a regular file returns mkdir error", func(t *testing.T) {+ parent := filepath.Join(t.TempDir(), "i-am-a-file")+ if err := os.WriteFile(parent, []byte("not a dir"), 0o600); err != nil {+ t.Fatalf("seed blocker file: %v", err)+ }+ target := filepath.Join(parent, "child")+ err := EnsureArtifactRoot(target)+ if err == nil {+ t.Fatalf("EnsureArtifactRoot(%q) error = nil, want non-nil", target)+ }+ // The target must not be usable as a directory: stat either fails+ // outright (ENOTDIR propagated through the regular-file parent) or+ // reports something that is not a directory.+ info, statErr := os.Stat(target)+ if statErr == nil && info.IsDir() {+ t.Fatalf("EnsureArtifactRoot(%q) unexpectedly created a usable directory", target)+ }+ })+}diff --git a/internal/api/magic_link_expiry_branchcov0723am_test.go b/internal/api/magic_link_expiry_branchcov0723am_test.gonew file mode 100644index 0000000000..47a874d927--- /dev/null+++ b/internal/api/magic_link_expiry_branchcov0723am_test.go@@ -0,0 +1,326 @@+package api++import (+ "database/sql"+ "encoding/hex"+ "testing"+ "time"+)++func countMagicLinkRowsBranchcov0723Am(t *testing.T, db *sql.DB) int {+ t.Helper()+ var n int+ if err := db.QueryRow(`SELECT COUNT(*) FROM magic_link_tokens`).Scan(&n); err != nil {+ t.Fatalf("count magic link rows: %v", err)+ }+ return n+}++func emailForHashBranchcov0723Am(t *testing.T, db *sql.DB, tokenHash []byte) string {+ t.Helper()+ var email string+ key := hex.EncodeToString(tokenHash)+ if err := db.QueryRow(`SELECT email FROM magic_link_tokens WHERE token_hash = ?`, key).Scan(&email); err != nil {+ t.Fatalf("lookup email for %x: %v", tokenHash, err)+ }+ return email+}++func TestBranchcov0723Am_InMemoryMagicLinkStore_DeleteExpired(t *testing.T) {+ base := time.Date(2026, 7, 23, 12, 0, 0, 0, time.UTC)+ expiredAt := base.Add(-1 * time.Hour)+ futureAt := base.Add(1 * time.Hour)++ t.Run("empty_store_is_noop", func(t *testing.T) {+ s := NewInMemoryMagicLinkStore()+ t.Cleanup(s.Stop)++ s.DeleteExpired(base)++ if got := len(s.tokens); got != 0 {+ t.Fatalf("empty store token count = %d, want 0", got)+ }+ })++ t.Run("all_valid_keeps_everything", func(t *testing.T) {+ s := NewInMemoryMagicLinkStore()+ t.Cleanup(s.Stop)++ h1 := []byte("hash-all-valid-1_______________")+ h2 := []byte("hash-all-valid-2_______________")+ if err := s.Put(h1, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: futureAt}); err != nil {+ t.Fatalf("Put h1: %v", err)+ }+ if err := s.Put(h2, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: base.Add(2 * time.Hour)}); err != nil {+ t.Fatalf("Put h2: %v", err)+ }++ s.DeleteExpired(base)++ if got := len(s.tokens); got != 2 {+ t.Fatalf("token count = %d, want 2 (all valid)", got)+ }+ if _, ok := s.tokens[hex.EncodeToString(h1)]; !ok {+ t.Fatalf("valid token h1 was wrongly removed")+ }+ if _, ok := s.tokens[hex.EncodeToString(h2)]; !ok {+ t.Fatalf("valid token h2 was wrongly removed")+ }+ })++ t.Run("all_expired_removes_everything", func(t *testing.T) {+ s := NewInMemoryMagicLinkStore()+ t.Cleanup(s.Stop)++ h1 := []byte("hash-all-expired-1_____________")+ h2 := []byte("hash-all-expired-2_____________")+ if err := s.Put(h1, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: expiredAt}); err != nil {+ t.Fatalf("Put h1: %v", err)+ }+ if err := s.Put(h2, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: base.Add(-2 * time.Hour)}); err != nil {+ t.Fatalf("Put h2: %v", err)+ }++ s.DeleteExpired(base)++ if got := len(s.tokens); got != 0 {+ t.Fatalf("token count = %d, want 0 (all expired)", got)+ }+ })++ t.Run("mix_removes_only_expired", func(t *testing.T) {+ s := NewInMemoryMagicLinkStore()+ t.Cleanup(s.Stop)++ hExp := []byte("hash-mix-expired_______________")+ hKeep1 := []byte("hash-mix-valid-1_______________")+ hKeep2 := []byte("hash-mix-valid-2_______________")+ if err := s.Put(hExp, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: expiredAt}); err != nil {+ t.Fatalf("Put hExp: %v", err)+ }+ if err := s.Put(hKeep1, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: futureAt}); err != nil {+ t.Fatalf("Put hKeep1: %v", err)+ }+ if err := s.Put(hKeep2, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: base.Add(2 * time.Hour)}); err != nil {+ t.Fatalf("Put hKeep2: %v", err)+ }++ s.DeleteExpired(base)++ if got := len(s.tokens); got != 2 {+ t.Fatalf("token count = %d, want 2", got)+ }+ if _, ok := s.tokens[hex.EncodeToString(hExp)]; ok {+ t.Fatalf("expired token hExp was wrongly kept")+ }+ kept1, ok := s.tokens[hex.EncodeToString(hKeep1)]+ if !ok {+ t.Fatalf("valid token hKeep1 was wrongly removed")+ }+ if kept1.Email != "[email protected]" {+ t.Fatalf("hKeep1 email = %q, want [email protected]", kept1.Email)+ }+ if _, ok := s.tokens[hex.EncodeToString(hKeep2)]; !ok {+ t.Fatalf("valid token hKeep2 was wrongly removed")+ }+ })++ t.Run("boundary_exactly_at_now_is_kept", func(t *testing.T) {+ s := NewInMemoryMagicLinkStore()+ t.Cleanup(s.Stop)++ hBoundary := []byte("hash-boundary-now______________")+ if err := s.Put(hBoundary, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: base}); err != nil {+ t.Fatalf("Put hBoundary: %v", err)+ }++ s.DeleteExpired(base)++ if got := len(s.tokens); got != 1 {+ t.Fatalf("token count = %d, want 1 (now.After(expires) is strict, equal is kept)", got)+ }+ tok, ok := s.tokens[hex.EncodeToString(hBoundary)]+ if !ok {+ t.Fatalf("boundary token (expires==now) was removed; operator is strictly After, so it must be kept")+ }+ if !tok.ExpiresAt.Equal(base) {+ t.Fatalf("ExpiresAt = %v, want %v", tok.ExpiresAt, base)+ }+ })++ t.Run("nil_entry_removed", func(t *testing.T) {+ s := NewInMemoryMagicLinkStore()+ t.Cleanup(s.Stop)++ hValid := []byte("hash-nil-valid_________________")+ if err := s.Put(hValid, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: futureAt}); err != nil {+ t.Fatalf("Put hValid: %v", err)+ }+ s.tokens[hex.EncodeToString([]byte("nil-key-entry_________________"))] = nil++ s.DeleteExpired(base)++ if got := len(s.tokens); got != 1 {+ t.Fatalf("token count = %d, want 1 (nil entry purged, valid kept)", got)+ }+ if _, ok := s.tokens[hex.EncodeToString(hValid)]; !ok {+ t.Fatalf("valid token should remain after nil-entry purge")+ }+ })++ t.Run("idempotent_on_repeat", func(t *testing.T) {+ s := NewInMemoryMagicLinkStore()+ t.Cleanup(s.Stop)++ hExp := []byte("hash-idempotent-expired________")+ hKeep := []byte("hash-idempotent-valid__________")+ if err := s.Put(hExp, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: expiredAt}); err != nil {+ t.Fatalf("Put hExp: %v", err)+ }+ if err := s.Put(hKeep, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: futureAt}); err != nil {+ t.Fatalf("Put hKeep: %v", err)+ }++ s.DeleteExpired(base)+ if got := len(s.tokens); got != 1 {+ t.Fatalf("after first delete: count = %d, want 1", got)+ }++ s.DeleteExpired(base)+ if got := len(s.tokens); got != 1 {+ t.Fatalf("after second delete: count = %d, want 1 (idempotent)", got)+ }+ if _, ok := s.tokens[hex.EncodeToString(hKeep)]; !ok {+ t.Fatalf("valid token must still be present after second delete")+ }+ })+}++func TestBranchcov0723Am_SQLiteMagicLinkStore_DeleteExpired(t *testing.T) {+ base := time.Date(2026, 7, 23, 12, 0, 0, 0, time.UTC)+ expiredAt := base.Add(-1 * time.Hour)+ futureAt := base.Add(1 * time.Hour)++ newStore := func(t *testing.T) *SQLiteMagicLinkStore {+ t.Helper()+ store, err := NewSQLiteMagicLinkStore(t.TempDir())+ if err != nil {+ t.Fatalf("NewSQLiteMagicLinkStore: %v", err)+ }+ t.Cleanup(func() { store.Stop() })+ return store+ }++ t.Run("nil_and_zero_value_receivers_are_noop", func(t *testing.T) {+ var nilPtr *SQLiteMagicLinkStore+ nilPtr.DeleteExpired(base)++ zero := &SQLiteMagicLinkStore{}+ zero.DeleteExpired(base)+ })++ t.Run("empty_store_is_noop", func(t *testing.T) {+ s := newStore(t)++ s.DeleteExpired(base)++ if got := countMagicLinkRowsBranchcov0723Am(t, s.db); got != 0 {+ t.Fatalf("empty store row count = %d, want 0", got)+ }+ })++ t.Run("all_valid_keeps_everything", func(t *testing.T) {+ s := newStore(t)+ h1 := []byte("sql-all-valid-1________________")+ h2 := []byte("sql-all-valid-2________________")+ if err := s.Put(h1, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: futureAt}); err != nil {+ t.Fatalf("Put h1: %v", err)+ }+ if err := s.Put(h2, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: base.Add(2 * time.Hour)}); err != nil {+ t.Fatalf("Put h2: %v", err)+ }++ s.DeleteExpired(base)++ if got := countMagicLinkRowsBranchcov0723Am(t, s.db); got != 2 {+ t.Fatalf("row count = %d, want 2 (all valid)", got)+ }+ })++ t.Run("all_expired_removes_everything", func(t *testing.T) {+ s := newStore(t)+ h1 := []byte("sql-all-expired-1______________")+ h2 := []byte("sql-all-expired-2______________")+ if err := s.Put(h1, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: expiredAt}); err != nil {+ t.Fatalf("Put h1: %v", err)+ }+ if err := s.Put(h2, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: base.Add(-2 * time.Hour)}); err != nil {+ t.Fatalf("Put h2: %v", err)+ }++ s.DeleteExpired(base)++ if got := countMagicLinkRowsBranchcov0723Am(t, s.db); got != 0 {+ t.Fatalf("row count = %d, want 0 (all expired)", got)+ }+ })++ t.Run("mix_removes_only_expired", func(t *testing.T) {+ s := newStore(t)+ hExp := []byte("sql-mix-expired________________")+ hKeep := []byte("sql-mix-valid__________________")+ if err := s.Put(hExp, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: expiredAt}); err != nil {+ t.Fatalf("Put hExp: %v", err)+ }+ if err := s.Put(hKeep, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: futureAt}); err != nil {+ t.Fatalf("Put hKeep: %v", err)+ }++ s.DeleteExpired(base)++ if got := countMagicLinkRowsBranchcov0723Am(t, s.db); got != 1 {+ t.Fatalf("row count = %d, want 1", got)+ }+ if got := emailForHashBranchcov0723Am(t, s.db, hKeep); got != "[email protected]" {+ t.Fatalf("remaining row email = %q, want [email protected] (valid token must survive)", got)+ }+ })++ t.Run("boundary_exactly_at_now_is_kept", func(t *testing.T) {+ s := newStore(t)+ hBoundary := []byte("sql-boundary-now_______________")+ if err := s.Put(hBoundary, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: base}); err != nil {+ t.Fatalf("Put hBoundary: %v", err)+ }++ s.DeleteExpired(base)++ if got := countMagicLinkRowsBranchcov0723Am(t, s.db); got != 1 {+ t.Fatalf("row count = %d, want 1 (SQL uses strict expires_at < now, equal is kept)", got)+ }+ })++ t.Run("idempotent_on_repeat", func(t *testing.T) {+ s := newStore(t)+ hExp := []byte("sql-idempotent-expired_________")+ hKeep := []byte("sql-idempotent-valid___________")+ if err := s.Put(hExp, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: expiredAt}); err != nil {+ t.Fatalf("Put hExp: %v", err)+ }+ if err := s.Put(hKeep, &MagicLinkToken{Email: "[email protected]", OrgID: "org-1", ExpiresAt: futureAt}); err != nil {+ t.Fatalf("Put hKeep: %v", err)+ }++ s.DeleteExpired(base)+ if got := countMagicLinkRowsBranchcov0723Am(t, s.db); got != 1 {+ t.Fatalf("after first delete: count = %d, want 1", got)+ }+ s.DeleteExpired(base)+ if got := countMagicLinkRowsBranchcov0723Am(t, s.db); got != 1 {+ t.Fatalf("after second delete: count = %d, want 1 (idempotent)", got)+ }+ if got := emailForHashBranchcov0723Am(t, s.db, hKeep); got != "[email protected]" {+ t.Fatalf("valid token email = %q, want [email protected] after second delete", got)+ }+ })+}diff --git a/internal/cloudcp/stripe/reconciler_map_branchcov0723am_test.go b/internal/cloudcp/stripe/reconciler_map_branchcov0723am_test.gonew file mode 100644index 0000000000..8142298c42--- /dev/null+++ b/internal/cloudcp/stripe/reconciler_map_branchcov0723am_test.go@@ -0,0 +1,317 @@+package stripe++import (+ "context"+ "errors"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/entitlements"+ stripelib "github.com/stripe/stripe-go/v82"+)++// TestBranchcov0723Am_MapStripeSubscription drives every branch of the pure+// mapper mapStripeSubscription with concrete stripe structs and asserts the+// concrete converted output. No network or API access is involved.+func TestBranchcov0723Am_MapStripeSubscription(t *testing.T) {+ // priceMeta is a sentinel metadata map reused across subtests so each+ // assertion checks identity, not a freshly-allocated equivalent.+ priceMeta := map[string]string{"tier": "pro"}++ t.Run("zero_value_src_uses_fallback_customer_and_empty_fields", func(t *testing.T) {+ var src stripelib.Subscription+ got := mapStripeSubscription(&src, "cus_fallback")++ if got.ID != "" {+ t.Fatalf("ID = %q, want empty", got.ID)+ }+ if got.Status != "" {+ t.Fatalf("Status = %q, want empty", got.Status)+ }+ if got.Metadata != nil {+ t.Fatalf("Metadata = %v, want nil", got.Metadata)+ }+ if got.Customer != "cus_fallback" {+ t.Fatalf("Customer = %q, want fallback cus_fallback", got.Customer)+ }+ if len(got.Items.Data) != 0 {+ t.Fatalf("Items.Data = %v, want empty", got.Items.Data)+ }+ })++ t.Run("nil_customer_with_empty_fallback_leaves_customer_blank", func(t *testing.T) {+ var src stripelib.Subscription+ got := mapStripeSubscription(&src, "")+ if got.Customer != "" {+ t.Fatalf("Customer = %q, want empty", got.Customer)+ }+ })++ t.Run("present_customer_id_wins_over_fallback_and_is_trimmed", func(t *testing.T) {+ src := stripelib.Subscription{+ Customer: &stripelib.Customer{ID: " cus_real "},+ }+ got := mapStripeSubscription(&src, "cus_fallback")+ if got.Customer != "cus_real" {+ t.Fatalf("Customer = %q, want trimmed cus_real", got.Customer)+ }+ })++ t.Run("present_customer_with_empty_id_falls_back", func(t *testing.T) {+ src := stripelib.Subscription{+ Customer: &stripelib.Customer{ID: " "},+ }+ got := mapStripeSubscription(&src, "cus_fallback")+ if got.Customer != "cus_fallback" {+ t.Fatalf("Customer = %q, want fallback cus_fallback", got.Customer)+ }+ })++ t.Run("id_and_status_are_trimmed_and_copied_verbatim", func(t *testing.T) {+ // The mapper does not translate statuses; it copies string(src.Status)+ // verbatim. Assert exact passthrough for a known and an unknown value.+ for _, tc := range []struct {+ name string+ rawID string+ rawStatus stripelib.SubscriptionStatus+ wantID string+ wantStatus string+ }{+ {"known_active_trimmed", " sub_active ", stripelib.SubscriptionStatusActive, "sub_active", "active"},+ {"unknown_status_passthrough", "sub_x", stripelib.SubscriptionStatus("bogus_state"), "sub_x", "bogus_state"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ src := stripelib.Subscription{ID: tc.rawID, Status: tc.rawStatus}+ got := mapStripeSubscription(&src, "")+ if got.ID != tc.wantID {+ t.Fatalf("ID = %q, want %q", got.ID, tc.wantID)+ }+ if got.Status != tc.wantStatus {+ t.Fatalf("Status = %q, want %q", got.Status, tc.wantStatus)+ }+ })+ }+ })++ t.Run("metadata_is_passed_through_by_reference", func(t *testing.T) {+ meta := map[string]string{"k": "v"}+ src := stripelib.Subscription{Metadata: meta}+ got := mapStripeSubscription(&src, "")+ if got.Metadata == nil || len(got.Metadata) != 1 || got.Metadata["k"] != "v" {+ t.Fatalf("Metadata = %v, want %v", got.Metadata, meta)+ }+ })++ t.Run("nil_items_leaves_output_items_empty", func(t *testing.T) {+ src := stripelib.Subscription{Items: nil}+ got := mapStripeSubscription(&src, "")+ if len(got.Items.Data) != 0 {+ t.Fatalf("Items.Data = %v, want empty", got.Items.Data)+ }+ })++ t.Run("empty_items_data_leaves_output_items_empty", func(t *testing.T) {+ src := stripelib.Subscription{Items: &stripelib.SubscriptionItemList{Data: nil}}+ got := mapStripeSubscription(&src, "")+ if len(got.Items.Data) != 0 {+ t.Fatalf("Items.Data = %v, want empty", got.Items.Data)+ }+ })++ t.Run("single_valid_item_is_extracted_with_trimmed_id_and_metadata", func(t *testing.T) {+ src := stripelib.Subscription{+ Items: &stripelib.SubscriptionItemList{+ Data: []*stripelib.SubscriptionItem{+ {Price: &stripelib.Price{ID: " price_1 ", Metadata: priceMeta}},+ },+ },+ }+ got := mapStripeSubscription(&src, "")+ if len(got.Items.Data) != 1 {+ t.Fatalf("len(Items.Data) = %d, want 1", len(got.Items.Data))+ }+ if got.Items.Data[0].Price.ID != "price_1" {+ t.Fatalf("Price.ID = %q, want trimmed price_1", got.Items.Data[0].Price.ID)+ }+ if got.Items.Data[0].Price.Metadata["tier"] != "pro" {+ t.Fatalf("Price.Metadata = %v, want %v", got.Items.Data[0].Price.Metadata, priceMeta)+ }+ })++ t.Run("multiple_valid_items_are_all_appended_in_order", func(t *testing.T) {+ src := stripelib.Subscription{+ Items: &stripelib.SubscriptionItemList{+ Data: []*stripelib.SubscriptionItem{+ {Price: &stripelib.Price{ID: "price_a"}},+ {Price: &stripelib.Price{ID: "price_b", Metadata: priceMeta}},+ },+ },+ }+ got := mapStripeSubscription(&src, "")+ // The mapper appends every valid item (it does not pick one).+ if len(got.Items.Data) != 2 {+ t.Fatalf("len(Items.Data) = %d, want 2", len(got.Items.Data))+ }+ if got.Items.Data[0].Price.ID != "price_a" {+ t.Fatalf("Items.Data[0].Price.ID = %q, want price_a", got.Items.Data[0].Price.ID)+ }+ if got.Items.Data[1].Price.ID != "price_b" {+ t.Fatalf("Items.Data[1].Price.ID = %q, want price_b", got.Items.Data[1].Price.ID)+ }+ if got.Items.Data[1].Price.Metadata["tier"] != "pro" {+ t.Fatalf("Items.Data[1].Price.Metadata = %v, want tier=pro", got.Items.Data[1].Price.Metadata)+ }+ })++ t.Run("nil_item_and_nil_price_are_skipped_valid_items_kept", func(t *testing.T) {+ src := stripelib.Subscription{+ Items: &stripelib.SubscriptionItemList{+ Data: []*stripelib.SubscriptionItem{+ nil,+ {Price: nil},+ {Price: &stripelib.Price{ID: "price_kept"}},+ },+ },+ }+ got := mapStripeSubscription(&src, "")+ if len(got.Items.Data) != 1 {+ t.Fatalf("len(Items.Data) = %d, want 1 after skipping nil item/price", len(got.Items.Data))+ }+ if got.Items.Data[0].Price.ID != "price_kept" {+ t.Fatalf("Items.Data[0].Price.ID = %q, want price_kept", got.Items.Data[0].Price.ID)+ }+ })++ t.Run("combined_populated_source", func(t *testing.T) {+ meta := map[string]string{"source": "reconciler"}+ src := stripelib.Subscription{+ ID: "sub_full",+ Status: stripelib.SubscriptionStatusActive,+ Customer: &stripelib.Customer{ID: "cus_full"},+ Metadata: meta,+ Items: &stripelib.SubscriptionItemList{+ Data: []*stripelib.SubscriptionItem{+ {Price: &stripelib.Price{ID: "price_full", Metadata: priceMeta}},+ },+ },+ }+ got := mapStripeSubscription(&src, "should_not_be_used")+ if got.ID != "sub_full" || got.Status != "active" || got.Customer != "cus_full" {+ t.Fatalf("header fields = %+v, want sub_full/active/cus_full", got)+ }+ if got.Metadata["source"] != "reconciler" {+ t.Fatalf("Metadata = %v, want source=reconciler", got.Metadata)+ }+ if len(got.Items.Data) != 1 || got.Items.Data[0].Price.ID != "price_full" {+ t.Fatalf("items = %+v, want single price_full", got.Items.Data)+ }+ })+}++// TestBranchcov0723Am_WithAdmissionCheck exercises the WithAdmissionCheck+// option: setting a real check, observing it via enforceAdmission, setting a+// nil check, last-option-wins override, and the nil-receiver guard.+func TestBranchcov0723Am_WithAdmissionCheck(t *testing.T) {+ sentinel := errors.New("admission denied: sentinel")++ t.Run("sets_check_invokable_from_provisioner", func(t *testing.T) {+ p := &Provisioner{}+ opt := WithAdmissionCheck(func(context.Context) error { return sentinel })+ if opt == nil {+ t.Fatal("WithAdmissionCheck returned a nil option")+ }+ opt(p)++ if p.admissionCheck == nil {+ t.Fatal("admissionCheck is nil after applying option")+ }+ if err := p.enforceAdmission(context.Background(), "op"); !errors.Is(err, sentinel) {+ t.Fatalf("enforceAdmission error = %v, want wrapping sentinel", err)+ }+ })++ t.Run("nil_check_clears_field_and_enforce_admission_is_noop", func(t *testing.T) {+ p := &Provisioner{admissionCheck: func(context.Context) error { return sentinel }}+ WithAdmissionCheck(nil)(p)+ if p.admissionCheck != nil {+ t.Fatalf("admissionCheck = %p, want nil after nil option", p.admissionCheck)+ }+ if err := p.enforceAdmission(context.Background(), "op"); err != nil {+ t.Fatalf("enforceAdmission error = %v, want nil when no check set", err)+ }+ })++ t.Run("later_option_overrides_earlier_one", func(t *testing.T) {+ p := &Provisioner{}+ first := WithAdmissionCheck(func(context.Context) error { return sentinel })+ second := WithAdmissionCheck(func(context.Context) error { return nil })+ first(p)+ second(p)+ // The last applied check should win: enforceAdmission returns nil.+ if err := p.enforceAdmission(context.Background(), "op"); err != nil {+ t.Fatalf("enforceAdmission error = %v, want nil (second check should win)", err)+ }+ })++ t.Run("nil_receiver_guard_does_not_panic", func(t *testing.T) {+ // The option short-circuits when the receiver is nil. Assert the+ // returned option is well-formed and that invoking it on a nil+ // *Provisioner completes safely.+ opt := WithAdmissionCheck(func(context.Context) error { return sentinel })+ if opt == nil {+ t.Fatal("WithAdmissionCheck returned a nil option")+ }+ opt(nil) // must not panic+ })+}++// TestBranchcov0723Am_WithHostedEntitlementService exercises the+// WithHostedEntitlementService option: setting a real service (pointer+// identity), nil service, override semantics, and the nil-receiver guard.+func TestBranchcov0723Am_WithHostedEntitlementService(t *testing.T) {+ // Reuse the in-package registry helper from provisioner_rollback_test.go.+ reg := newStripeTestRegistry(t)+ newSvc := func() *entitlements.Service {+ return entitlements.NewService(reg, "https://cloud.example.com", "")+ }++ t.Run("sets_service_by_pointer_identity", func(t *testing.T) {+ p := &Provisioner{}+ svc := newSvc()+ opt := WithHostedEntitlementService(svc)+ if opt == nil {+ t.Fatal("WithHostedEntitlementService returned a nil option")+ }+ opt(p)+ if p.hostedEntitlements != svc {+ t.Fatalf("hostedEntitlements = %p, want exact pointer %p", p.hostedEntitlements, svc)+ }+ })++ t.Run("nil_service_clears_field", func(t *testing.T) {+ // Start from a non-nil service to prove the option overwrites to nil.+ p := &Provisioner{hostedEntitlements: newSvc()}+ WithHostedEntitlementService(nil)(p)+ if p.hostedEntitlements != nil {+ t.Fatalf("hostedEntitlements = %p, want nil after nil option", p.hostedEntitlements)+ }+ })++ t.Run("later_option_overrides_earlier_one", func(t *testing.T) {+ p := &Provisioner{}+ first := newSvc()+ second := newSvc()+ WithHostedEntitlementService(first)(p)+ WithHostedEntitlementService(second)(p)+ if p.hostedEntitlements != second {+ t.Fatalf("hostedEntitlements = %p, want second service %p (last write wins)", p.hostedEntitlements, second)+ }+ })++ t.Run("nil_receiver_guard_does_not_panic", func(t *testing.T) {+ opt := WithHostedEntitlementService(newSvc())+ if opt == nil {+ t.Fatal("WithHostedEntitlementService returned a nil option")+ }+ opt(nil) // must not panic+ })+}