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
Add branch-coverage tests for unifiedresources helpers, smartctl targets, intent-policy manager
rcourtman4f6179368ad5
diff --git a/internal/alerts/intent_policy_manager_branchcov0721am_test.go b/internal/alerts/intent_policy_manager_branchcov0721am_test.gonew file mode 100644index 0000000000..b7ebf38e70--- /dev/null+++ b/internal/alerts/intent_policy_manager_branchcov0721am_test.go@@ -0,0 +1,308 @@+package alerts++import (+ "errors"+ "strings"+ "testing"+ "time"+)++// TestBranchcov0721amIntentPolicyManager raises branch coverage on three+// *Manager methods: UpdateIntentPolicies, GetIntentPolicies, and+// SetBackupIntentContextResolver. Each arm uses t.Run so the test name+// prefix matches the -run filter requested by the task brief.+func TestBranchcov0721amIntentPolicyManager(t *testing.T) {+ const wantSchema = CurrentAlertIntentPolicySchemaVersion++ // validBranchcov0721amDoc builds a document that is guaranteed to pass+ // ValidateAlertIntentPolicyDocument with the requested revision. The+ // shape mirrors the construction used in intent_policy_test.go.+ validBranchcov0721amDoc := func(revision int64) AlertIntentPolicyDocument {+ doc := NewAlertIntentPolicyDocument()+ doc.Revision = revision+ doc.Defaults[string(AlertIntentSignalOffline)] = AlertIntentRule{+ GraceSeconds: intPointer(45),+ HonorOperatorState: boolPointer(true),+ }+ return doc+ }++ // --- UpdateIntentPolicies: arm (a) invalid document ---+ t.Run("UpdateIntentPolicies_invalid_document_returns_validation_error", func(t *testing.T) {+ m := NewManagerWithDataDir(t.TempDir())+ t.Cleanup(m.Stop)++ invalid := NewAlertIntentPolicyDocument()+ invalid.SchemaVersion = wantSchema + 7 // unsupported schema triggers the validator+ if err := ValidateAlertIntentPolicyDocument(invalid); err == nil {+ t.Fatalf("precondition: expected doc to be invalid")+ }++ returned, err := m.UpdateIntentPolicies(invalid)+ if err == nil {+ t.Fatalf("expected validation error, got nil")+ }+ if !strings.Contains(err.Error(), "unsupported alert intent policy schema version") {+ t.Fatalf("expected schema-version validation error, got %v", err)+ }+ if returned.SchemaVersion != 0 || returned.Revision != 0 || returned.Defaults != nil || returned.ResourceTypes != nil || returned.Resources != nil {+ t.Fatalf("expected zero-value document on validation failure, got %+v", returned)+ }+ })++ // --- UpdateIntentPolicies: arm (b) nil manager ---+ t.Run("UpdateIntentPolicies_nil_manager_returns_nil_manager_error", func(t *testing.T) {+ var m *Manager+ returned, err := m.UpdateIntentPolicies(validBranchcov0721amDoc(0))+ if err == nil {+ t.Fatalf("expected error from nil manager, got nil")+ }+ if !strings.Contains(err.Error(), "alert manager is nil") {+ t.Fatalf("expected 'alert manager is nil' error, got %v", err)+ }+ if returned.SchemaVersion != 0 || returned.Revision != 0 {+ t.Fatalf("expected zero-value document from nil manager, got %+v", returned)+ }+ })++ // --- UpdateIntentPolicies: arm (c) revision conflict ---+ t.Run("UpdateIntentPolicies_revision_conflict_returns_sentinel_and_leaves_state", func(t *testing.T) {+ m := NewManagerWithDataDir(t.TempDir())+ t.Cleanup(m.Stop)++ seed := validBranchcov0721amDoc(7)+ if err := m.LoadIntentPolicies(seed); err != nil {+ t.Fatalf("LoadIntentPolicies error: %v", err)+ }+ currentRevision := m.GetIntentPolicies().Revision+ if currentRevision != 7 {+ t.Fatalf("expected loaded revision 7, got %d", currentRevision)+ }++ conflict := validBranchcov0721amDoc(currentRevision + 1) // wrong revision+ returned, err := m.UpdateIntentPolicies(conflict)+ if !errors.Is(err, ErrAlertIntentPolicyRevisionConflict) {+ t.Fatalf("expected errors.Is(err, ErrAlertIntentPolicyRevisionConflict), got %v", err)+ }+ if returned.SchemaVersion != 0 || returned.Revision != 0 {+ t.Fatalf("expected zero-value document on conflict, got %+v", returned)+ }+ // Stored policy state must be unchanged.+ if got := m.GetIntentPolicies().Revision; got != currentRevision {+ t.Fatalf("expected revision unchanged after conflict, got %d", got)+ }+ })++ // --- UpdateIntentPolicies: arm (d) success ---+ t.Run("UpdateIntentPolicies_success_bumps_revision_and_round_trips", func(t *testing.T) {+ m := NewManagerWithDataDir(t.TempDir())+ t.Cleanup(m.Stop)++ // Freeze the clock so the UpdatedAt stamp is observable & reproducible.+ frozen := time.Date(2026, 7, 21, 9, 0, 0, 0, time.UTC)+ m.now = func() time.Time { return frozen }++ seed := validBranchcov0721amDoc(3)+ if err := m.LoadIntentPolicies(seed); err != nil {+ t.Fatalf("LoadIntentPolicies error: %v", err)+ }+ currentRevision := m.GetIntentPolicies().Revision+ if currentRevision != 3 {+ t.Fatalf("expected loaded revision 3, got %d", currentRevision)+ }++ // Build the update payload with the matching revision but mutate the+ // policy body so the round-trip reflects the new content.+ update := validBranchcov0721amDoc(currentRevision)+ update.Defaults[string(AlertIntentSignalOffline)] = AlertIntentRule{+ GraceSeconds: intPointer(120),+ HonorOperatorState: boolPointer(false),+ }+ returned, err := m.UpdateIntentPolicies(update)+ if err != nil {+ t.Fatalf("UpdateIntentPolicies unexpected error: %v", err)+ }+ if returned.Revision != currentRevision+1 {+ t.Fatalf("expected returned revision %d, got %d", currentRevision+1, returned.Revision)+ }+ if returned.UpdatedAt == nil {+ t.Fatalf("expected UpdatedAt to be set on returned document")+ }+ if !returned.UpdatedAt.Equal(frozen) {+ t.Fatalf("expected UpdatedAt %v, got %v", frozen, *returned.UpdatedAt)+ }+ if returned.SchemaVersion != wantSchema {+ t.Fatalf("expected schema version %d, got %d", wantSchema, returned.SchemaVersion)+ }++ // Returned doc must equal the normalized shape of the update body+ // (with the bumped revision + UpdatedAt applied).+ expectedNormalized := NormalizeAlertIntentPolicyDocument(update)+ expectedNormalized.Revision = currentRevision + 1+ expectedUpdatedAt := frozen.UTC()+ expectedNormalized.UpdatedAt = &expectedUpdatedAt+ if !branchcov0721amDocsEqual(returned, expectedNormalized) {+ t.Fatalf("returned doc shape mismatch\n got=%+v\nwant=%+v", returned, expectedNormalized)+ }++ // A subsequent GetIntentPolicies must reflect the new revision and content.+ got := m.GetIntentPolicies()+ if got.Revision != currentRevision+1 {+ t.Fatalf("expected GetIntentPolicies revision %d, got %d", currentRevision+1, got.Revision)+ }+ rule, ok := got.Defaults[string(AlertIntentSignalOffline)]+ if !ok {+ t.Fatalf("expected defaults entry for %q after update", AlertIntentSignalOffline)+ }+ if rule.GraceSeconds == nil || *rule.GraceSeconds != 120 {+ t.Fatalf("expected grace seconds 120 after update, got %+v", rule)+ }+ if rule.HonorOperatorState == nil || *rule.HonorOperatorState != false {+ t.Fatalf("expected honorOperatorState false after update, got %+v", rule)+ }+ })++ // --- GetIntentPolicies: nil manager ---+ t.Run("GetIntentPolicies_nil_manager_returns_factory_default", func(t *testing.T) {+ var m *Manager+ got := m.GetIntentPolicies()+ expected := NewAlertIntentPolicyDocument()+ if !branchcov0721amDocsEqual(got, expected) {+ t.Fatalf("nil-manager GetIntentPolicies mismatch\n got=%+v\nwant=%+v", got, expected)+ }+ })++ // --- GetIntentPolicies: populated manager (round-trip after Load) ---+ t.Run("GetIntentPolicies_populated_manager_round_trips_stored_doc", func(t *testing.T) {+ m := NewManagerWithDataDir(t.TempDir())+ t.Cleanup(m.Stop)++ seed := validBranchcov0721amDoc(11)+ if err := m.LoadIntentPolicies(seed); err != nil {+ t.Fatalf("LoadIntentPolicies error: %v", err)+ }+ got := m.GetIntentPolicies()+ expected := NormalizeAlertIntentPolicyDocument(seed)+ if !branchcov0721amDocsEqual(got, expected) {+ t.Fatalf("populated GetIntentPolicies mismatch\n got=%+v\nwant=%+v", got, expected)+ }+ })++ // --- SetBackupIntentContextResolver: nil manager (no panic) ---+ t.Run("SetBackupIntentContextResolver_nil_manager_no_panic", func(t *testing.T) {+ var m *Manager+ m.SetBackupIntentContextResolver(func(resourceID, instance, node string, vmid int, now time.Time) (BackupIntentContext, bool) {+ return BackupIntentContext{Active: true, Evidence: "from-nil-arm"}, true+ })+ // Reaching here without panic is the assertion. Also verify the nil+ // manager still reports the factory-default policy.+ if got := m.GetIntentPolicies(); got.Revision != 0 || got.SchemaVersion != wantSchema {+ t.Fatalf("nil manager policy unexpectedly mutated: %+v", got)+ }+ })++ // --- SetBackupIntentContextResolver: non-nil manager (stores resolver) ---+ t.Run("SetBackupIntentContextResolver_non_nil_manager_stores_resolver", func(t *testing.T) {+ m := NewManagerWithDataDir(t.TempDir())+ t.Cleanup(m.Stop)++ var capturedResource, capturedInstance, capturedNode string+ var capturedVMID int+ var capturedNow time.Time+ resolver := func(resourceID, instance, node string, vmid int, now time.Time) (BackupIntentContext, bool) {+ capturedResource = resourceID+ capturedInstance = instance+ capturedNode = node+ capturedVMID = vmid+ capturedNow = now+ return BackupIntentContext{Active: true, Evidence: "nightly"}, true+ }+ m.SetBackupIntentContextResolver(resolver)++ // The setter must have written the resolver field.+ m.mu.RLock()+ stored := m.backupIntentResolver+ m.mu.RUnlock()+ if stored == nil {+ t.Fatalf("expected backup resolver to be stored on manager")+ }+ // Invoke the stored resolver to confirm it is the function we+ // registered (i.e. SetBackupIntentContextResolver wrote the field).+ frozen := time.Date(2026, 7, 21, 10, 0, 0, 0, time.UTC)+ ctx, ok := stored("vm:101", "qemu", "node-a", 101, frozen)+ if !ok || !ctx.Active || ctx.Evidence != "nightly" {+ t.Fatalf("stored resolver returned unexpected value: %+v ok=%v", ctx, ok)+ }+ if capturedResource != "vm:101" || capturedInstance != "qemu" || capturedNode != "node-a" || capturedVMID != 101 || !capturedNow.Equal(frozen) {+ t.Fatalf("stored resolver captured unexpected args: resource=%q instance=%q node=%q vmid=%d now=%v",+ capturedResource, capturedInstance, capturedNode, capturedVMID, capturedNow)+ }+ })+}++// branchcov0721amDocsEqual compares two documents field-by-field for the+// assertions above. Avoids reflect to keep dependencies minimal.+func branchcov0721amDocsEqual(a, b AlertIntentPolicyDocument) bool {+ if a.SchemaVersion != b.SchemaVersion || a.Revision != b.Revision {+ return false+ }+ if (a.UpdatedAt == nil) != (b.UpdatedAt == nil) {+ return false+ }+ if a.UpdatedAt != nil && !a.UpdatedAt.Equal(*b.UpdatedAt) {+ return false+ }+ if !branchcov0721amSignalRulesEqual(a.Defaults, b.Defaults) {+ return false+ }+ if len(a.ResourceTypes) != len(b.ResourceTypes) {+ return false+ }+ for k, av := range a.ResourceTypes {+ bv, ok := b.ResourceTypes[k]+ if !ok || !branchcov0721amSignalRulesEqual(av, bv) {+ return false+ }+ }+ if len(a.Resources) != len(b.Resources) {+ return false+ }+ for k, av := range a.Resources {+ bv, ok := b.Resources[k]+ if !ok || !branchcov0721amSignalRulesEqual(av, bv) {+ return false+ }+ }+ return true+}++func branchcov0721amSignalRulesEqual(a, b map[string]AlertIntentRule) bool {+ if len(a) != len(b) {+ return false+ }+ for k, av := range a {+ bv, ok := b[k]+ if !ok {+ return false+ }+ if (av.GraceSeconds == nil) != (bv.GraceSeconds == nil) {+ return false+ }+ if av.GraceSeconds != nil && *av.GraceSeconds != *bv.GraceSeconds {+ return false+ }+ if (av.HonorOperatorState == nil) != (bv.HonorOperatorState == nil) {+ return false+ }+ if av.HonorOperatorState != nil && *av.HonorOperatorState != *bv.HonorOperatorState {+ return false+ }+ if (av.BackupOffline == nil) != (bv.BackupOffline == nil) {+ return false+ }+ if av.BackupOffline != nil && *av.BackupOffline != *bv.BackupOffline {+ return false+ }+ }+ return true+}diff --git a/internal/hostagent/smartctl_targets_branchcov0721am_test.go b/internal/hostagent/smartctl_targets_branchcov0721am_test.gonew file mode 100644index 0000000000..0faf3e5626--- /dev/null+++ b/internal/hostagent/smartctl_targets_branchcov0721am_test.go@@ -0,0 +1,100 @@+package hostagent++import (+ "reflect"+ "testing"+)++// TestBranchcov0721amSmartctlTargets exercises smartctlTargetsFromDevices+// across its two branches (empty -> nil, non-empty -> ordered targets) and+// confirms exact values for each returned target, including duplicate paths.+func TestBranchcov0721amSmartctlTargets(t *testing.T) {+ t.Run("nil_input_returns_nil", func(t *testing.T) {+ got := smartctlTargetsFromDevices(nil)+ if got != nil {+ t.Fatalf("expected nil slice for nil input, got %#v (len=%d)", got, len(got))+ }+ })++ t.Run("empty_non_nil_slice_returns_nil", func(t *testing.T) {+ got := smartctlTargetsFromDevices([]string{})+ if got != nil {+ t.Fatalf("expected nil slice for empty input, got %#v (len=%d)", got, len(got))+ }+ })++ t.Run("single_device_single_target_path_set", func(t *testing.T) {+ got := smartctlTargetsFromDevices([]string{"/dev/sda"})+ expected := []smartctlTarget{{Path: "/dev/sda", DeviceType: ""}}+ if !reflect.DeepEqual(got, expected) {+ t.Fatalf("expected %#v, got %#v", expected, got)+ }+ if len(got) != 1 {+ t.Fatalf("expected len 1, got %d", len(got))+ }+ if got[0].Path != "/dev/sda" {+ t.Fatalf("expected Path /dev/sda, got %q", got[0].Path)+ }+ if got[0].DeviceType != "" {+ t.Fatalf("expected empty DeviceType, got %q", got[0].DeviceType)+ }+ })++ t.Run("multiple_devices_preserve_order", func(t *testing.T) {+ input := []string{"/dev/sda", "/dev/nvme0n1", "/dev/sdb"}+ got := smartctlTargetsFromDevices(input)+ expected := []smartctlTarget{+ {Path: "/dev/sda", DeviceType: ""},+ {Path: "/dev/nvme0n1", DeviceType: ""},+ {Path: "/dev/sdb", DeviceType: ""},+ }+ if len(got) != len(expected) {+ t.Fatalf("expected len %d, got %d", len(expected), len(got))+ }+ if !reflect.DeepEqual(got, expected) {+ t.Fatalf("expected %#v, got %#v", expected, got)+ }+ for i := range expected {+ if got[i].Path != expected[i].Path {+ t.Fatalf("index %d: expected Path %q, got %q", i, expected[i].Path, got[i].Path)+ }+ if got[i].DeviceType != "" {+ t.Fatalf("index %d: expected empty DeviceType, got %q", i, got[i].DeviceType)+ }+ }+ })++ t.Run("duplicate_paths_preserved_no_dedup", func(t *testing.T) {+ input := []string{"/dev/sda", "/dev/sda", "/dev/sda"}+ got := smartctlTargetsFromDevices(input)+ expected := []smartctlTarget{+ {Path: "/dev/sda", DeviceType: ""},+ {Path: "/dev/sda", DeviceType: ""},+ {Path: "/dev/sda", DeviceType: ""},+ }+ if len(got) != 3 {+ t.Fatalf("expected len 3 (no dedup), got %d", len(got))+ }+ if !reflect.DeepEqual(got, expected) {+ t.Fatalf("expected %#v, got %#v", expected, got)+ }+ for i, target := range got {+ if target.Path != "/dev/sda" {+ t.Fatalf("index %d: expected Path /dev/sda, got %q", i, target.Path)+ }+ if target.DeviceType != "" {+ t.Fatalf("index %d: expected empty DeviceType, got %q", i, target.DeviceType)+ }+ }+ })++ t.Run("empty_string_device_still_emits_target", func(t *testing.T) {+ // len(devices) != 0, so the function constructs a target even for an+ // empty-string path; this documents that no filtering occurs.+ got := smartctlTargetsFromDevices([]string{""})+ expected := []smartctlTarget{{Path: "", DeviceType: ""}}+ if !reflect.DeepEqual(got, expected) {+ t.Fatalf("expected %#v, got %#v", expected, got)+ }+ })+}diff --git a/internal/unifiedresources/purehelpers_branchcov0721am_test.go b/internal/unifiedresources/purehelpers_branchcov0721am_test.gonew file mode 100644index 0000000000..0ce6337bd3--- /dev/null+++ b/internal/unifiedresources/purehelpers_branchcov0721am_test.go@@ -0,0 +1,335 @@+package unifiedresources++import (+ "strings"+ "testing"+ "time"+)++// Branch-coverage tests for two currently-uncovered PURE functions:+// - ActionPolicyAuthorizationDigest (actions.go:240) — zeroes Digest,+// json.Marshal, sha256.Sum256, fmt.Sprintf("sha256:%x", sum).+// - normalizePair (store.go:4082) — CanonicalResourceID+// on both args, then returns them sorted ascending (swap when a>b).+//+// Every assertion pins a hand-computed expected value or invariant; none is a+// "no panic" assertion. The pinned SHA-256 digests below were derived+// independently (see comments) from the exact JSON payload the function+// produces, so they detect any drift in the marshalled field set, ordering, or+// hash formatting.++// baseLease0721am builds the non-trivial ActionPolicyAuthorizationLease used+// as the reference payload for the digest subtests. Field values are chosen to+// exercise every serializable field type (ints, strings, bools true AND false,+// a non-empty []string, a non-nil *AutoRemediationWindow, and two distinct+// time.Time values). The JSON this marshals to (with Digest="") is, verbatim:+//+// {"version":1,"orgId":"org-123","actionId":"action-abc","resourceId":"host-7",+// "capabilityName":"restart_service","planHash":"sha256:deadbeef",+// "capabilityPolicyVersion":"v2","autoAuthorization":"low_risk",+// "approvalPolicy":"none","tenantPolicyVersion":"tenant-v9",+// "effectiveAutonomyLevel":"guided","licenseAllowsAutoFix":true,+// "fullModeUnlocked":false,"emergencyStop":false,+// "resourcePolicyVersion":"res-v1",+// "capabilityNames":["restart_service","check_status"],+// "window":{"timezone":"UTC","startMinute":0,"endMinute":1440},+// "neverAutoRemediate":false,"issuedAt":"2026-07-21T12:30:00Z",+// "expiresAt":"2026-07-21T13:30:00Z","digest":""}+//+// sha256 of those bytes = 0dd5f9f1517d850c1a27d588163a8e4361027358bd5cabbca120c15a551687ff.+func baseLease0721am() ActionPolicyAuthorizationLease {+ return ActionPolicyAuthorizationLease{+ Version: 1,+ OrgID: "org-123",+ ActionID: "action-abc",+ ResourceID: "host-7",+ CapabilityName: "restart_service",+ PlanHash: "sha256:deadbeef",+ CapabilityPolicyVersion: "v2",+ AutoAuthorization: AutoAuthorizeLowRisk,+ ApprovalPolicy: ApprovalNone,+ TenantPolicyVersion: "tenant-v9",+ EffectiveAutonomyLevel: "guided",+ LicenseAllowsAutoFix: true,+ FullModeUnlocked: false,+ EmergencyStop: false,+ ResourcePolicyVersion: "res-v1",+ CapabilityNames: []string{"restart_service", "check_status"},+ Window: &AutoRemediationWindow{Timezone: "UTC", StartMinute: 0, EndMinute: 1440},+ NeverAutoRemediate: false,+ IssuedAt: time.Date(2026, 7, 21, 12, 30, 0, 0, time.UTC),+ ExpiresAt: time.Date(2026, 7, 21, 13, 30, 0, 0, time.UTC),+ Digest: "",+ }+}++func TestBranchcov0721amPureHelpers(t *testing.T) {+ // ----------------------------------------------------------------------+ // ActionPolicyAuthorizationDigest+ // ----------------------------------------------------------------------+ t.Run("ActionPolicyAuthorizationDigest", func(t *testing.T) {+ t.Parallel()++ t.Run("deterministic_same_lease_identical_digest_across_two_calls", func(t *testing.T) {+ t.Parallel()+ first := ActionPolicyAuthorizationDigest(baseLease0721am())+ second := ActionPolicyAuthorizationDigest(baseLease0721am())+ if first != second {+ t.Fatalf("digest not deterministic: call1=%q call2=%q", first, second)+ }+ })++ t.Run("digest_field_excluded_nonempty_digest_equals_empty_digest", func(t *testing.T) {+ t.Parallel()+ // The function zeroes lease.Digest before marshalling, so a lease+ // carrying any Digest value must produce the SAME digest as the+ // identical lease with Digest="". This is the key self-referential+ // invariant ValidateActionPolicyAuthorizationLease relies on.+ withDigest := baseLease0721am()+ withDigest.Digest = "sha256:PRECOMPUTED_PLACEHOLDER_THAT_MUST_BE_IGNORED"+ withoutDigest := baseLease0721am()+ withoutDigest.Digest = ""+ gotWith := ActionPolicyAuthorizationDigest(withDigest)+ gotWithout := ActionPolicyAuthorizationDigest(withoutDigest)+ if gotWith != gotWithout {+ t.Fatalf("Digest field was NOT excluded: withDigest=%q withoutDigest=%q", gotWith, gotWithout)+ }+ })++ t.Run("distinct_payloads_produce_distinct_digests_changing_OrgID", func(t *testing.T) {+ t.Parallel()+ // Changing OrgID mutates the marshalled payload, so the digest must+ // differ. Hand-computed digest for OrgID="org-999" (everything else+ // equal to baseLease0721am) =+ // 84bf1e7282dc57341417403b88778f521c6ff8716a3786e074ed46005124bebb.+ variant := baseLease0721am()+ variant.OrgID = "org-999"+ base := ActionPolicyAuthorizationDigest(baseLease0721am())+ got := ActionPolicyAuthorizationDigest(variant)+ if got == base {+ t.Fatalf("changing OrgID did not change digest: both=%q", got)+ }+ const wantOrgVariant = "sha256:84bf1e7282dc57341417403b88778f521c6ff8716a3786e074ed46005124bebb"+ if got != wantOrgVariant {+ t.Fatalf("OrgID-variant digest = %q, want %q", got, wantOrgVariant)+ }+ })++ t.Run("distinct_payloads_produce_distinct_digests_changing_ActionID", func(t *testing.T) {+ t.Parallel()+ // Changing ActionID must likewise change the digest. Hand-computed+ // digest for ActionID="action-xyz" (everything else equal) =+ // 4059812a4d6547d6f88c6ec6ad07141a303d9b13224fd35b35f27cc3183ee29d.+ variant := baseLease0721am()+ variant.ActionID = "action-xyz"+ base := ActionPolicyAuthorizationDigest(baseLease0721am())+ got := ActionPolicyAuthorizationDigest(variant)+ if got == base {+ t.Fatalf("changing ActionID did not change digest: both=%q", got)+ }+ const wantActionVariant = "sha256:4059812a4d6547d6f88c6ec6ad07141a303d9b13224fd35b35f27cc3183ee29d"+ if got != wantActionVariant {+ t.Fatalf("ActionID-variant digest = %q, want %q", got, wantActionVariant)+ }+ })++ t.Run("format_is_sha256_prefix_plus_64_lowercase_hex_chars", func(t *testing.T) {+ t.Parallel()+ got := ActionPolicyAuthorizationDigest(baseLease0721am())+ const prefix = "sha256:"+ if !strings.HasPrefix(got, prefix) {+ t.Fatalf("digest %q missing %q prefix", got, prefix)+ }+ hex := strings.TrimPrefix(got, prefix)+ if len(hex) != 64 {+ t.Fatalf("hex part length = %d, want 64 (digest=%q)", len(hex), got)+ }+ for i, r := range hex {+ isLowerHex := (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f')+ if !isLowerHex {+ t.Fatalf("hex part contains non-lowercase-hex rune %q at index %d (digest=%q)", r, i, got)+ }+ }+ })++ t.Run("pinned_exact_value_for_reference_lease", func(t *testing.T) {+ t.Parallel()+ // Pins the full digest for baseLease0721am so any future change to+ // the marshalled field set, ordering, or hash formatting is caught.+ // Value computed independently from the JSON payload documented on+ // baseLease0721am.+ got := ActionPolicyAuthorizationDigest(baseLease0721am())+ const want = "sha256:0dd5f9f1517d850c1a27d588163a8e4361027358bd5cabbca120c15a551687ff"+ if got != want {+ t.Fatalf("ActionPolicyAuthorizationDigest(baseLease0721am) = %q, want %q", got, want)+ }+ })++ t.Run("empty_lease_distinct_from_reference_and_well_formed", func(t *testing.T) {+ t.Parallel()+ // A zero-value lease is a different payload, so its digest must+ // differ from the reference lease and still be well-formed.+ empty := ActionPolicyAuthorizationLease{}+ got := ActionPolicyAuthorizationDigest(empty)+ ref := ActionPolicyAuthorizationDigest(baseLease0721am())+ if got == ref {+ t.Fatalf("empty-lease digest equals reference-lease digest: %q", got)+ }+ if !strings.HasPrefix(got, "sha256:") || len(got) != len("sha256:")+64 {+ t.Fatalf("empty-lease digest malformed: %q", got)+ }+ })+ })++ // ----------------------------------------------------------------------+ // normalizePair+ // ----------------------------------------------------------------------+ t.Run("normalizePair", func(t *testing.T) {+ t.Parallel()++ // normalizePair canonicalizes both args via CanonicalResourceID+ // (which is strings.TrimSpace, returning "" for empty/blank input)+ // and then returns them sorted ascending: swap when a>b, no swap+ // when a<=b. Each row below drives a specific branch and pins the+ // exact hand-computed (first, second) pair.+ cases := []struct {+ name string+ a, b string+ wantFirst string+ wantSec string+ }{+ {+ // No-swap branch (a<=b): "alpha" < "zeta" → returned as-is.+ name: "no_swap_branch_a_less_than_b",+ a: "alpha",+ b: "zeta",+ wantFirst: "alpha",+ wantSec: "zeta",+ },+ {+ // Swap branch (a>b): "zeta" > "alpha" → swapped on return.+ name: "swap_branch_a_greater_than_b",+ a: "zeta",+ b: "alpha",+ wantFirst: "alpha",+ wantSec: "zeta",+ },+ {+ // Equal case (a==b, a>b is false): no swap, both identical.+ name: "equal_inputs_no_swap",+ a: "same",+ b: "same",+ wantFirst: "same",+ wantSec: "same",+ },+ {+ // Canonicalization applied: CanonicalResourceID trims+ // surrounding whitespace, so the raw inputs " alpha " and+ // "\tzeta\t" produce the canonical ("alpha","zeta"). This+ // proves the output reflects the canonical form, not the raw+ // input, and the trimmed forms are then sorted.+ name: "canonicalization_trims_whitespace_then_sorts",+ a: " alpha ",+ b: "\tzeta\t",+ wantFirst: "alpha",+ wantSec: "zeta",+ },+ {+ // Canonicalization + swap: trimmed "zeta" > trimmed "alpha".+ name: "canonicalization_trims_whitespace_then_swaps",+ a: " zeta ",+ b: "\talpha\t",+ wantFirst: "alpha",+ wantSec: "zeta",+ },+ {+ // Both inputs blank-after-trim: CanonicalResourceID returns+ // "" for each, "" is not > "" so no swap → ("","").+ name: "both_inputs_blank_after_trim_yield_empty_pair",+ a: " ",+ b: "\t",+ wantFirst: "",+ wantSec: "",+ },+ {+ // One side blank after trim, the other not: "" < "host-1",+ // no swap, empty sorts first.+ name: "one_blank_one_present_empty_sorts_first",+ a: "host-1",+ b: " ",+ wantFirst: "",+ wantSec: "host-1",+ },+ {+ // Lexicographic ordering with a common prefix: "host-10" >+ // "host-2" under byte comparison (since '1' < '2'), so swap.+ name: "lexicographic_byte_order_host10_after_host2",+ a: "host-10",+ b: "host-2",+ wantFirst: "host-10",+ wantSec: "host-2",+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ gotFirst, gotSec := normalizePair(tc.a, tc.b)+ if gotFirst != tc.wantFirst || gotSec != tc.wantSec {+ t.Fatalf("normalizePair(%q, %q) = (%q, %q), want (%q, %q)",+ tc.a, tc.b, gotFirst, gotSec, tc.wantFirst, tc.wantSec)+ }+ // Output is always sorted ascending (first <= second).+ if gotFirst > gotSec {+ t.Fatalf("normalizePair output not sorted: first=%q > second=%q", gotFirst, gotSec)+ }+ })+ }++ // Ordering invariant: normalizePair(x,y) == normalizePair(y,x) for+ // any x,y. Driven across a set of input pairs that exercise both the+ // swap and no-swap branches, including whitespace inputs.+ t.Run("ordering_invariant_normalizePair_xy_equals_normalizePair_yx", func(t *testing.T) {+ t.Parallel()+ pairs := [][2]string{+ {"alpha", "zeta"},+ {"zeta", "alpha"},+ {"same", "same"},+ {" alpha ", "\tzeta\t"},+ {"host-10", "host-2"},+ {"", "host-1"},+ {" ", "\t"},+ }+ for _, p := range pairs {+ p := p+ t.Run(p[0]+"|"+p[1], func(t *testing.T) {+ t.Parallel()+ fa, sa := normalizePair(p[0], p[1])+ fb, sb := normalizePair(p[1], p[0])+ if fa != fb || sa != sb {+ t.Fatalf("ordering invariant violated: normalizePair(%q,%q)=(%q,%q) != normalizePair(%q,%q)=(%q,%q)",+ p[0], p[1], fa, sa, p[1], p[0], fb, sb)+ }+ })+ }+ })++ // Canonicalization is applied to BOTH arguments independently: even+ // when the raw inputs are already in sorted order, the returned+ // values must be the canonical (trimmed) forms, not the raw inputs.+ t.Run("canonicalization_reflects_canonical_form_not_raw_input", func(t *testing.T) {+ t.Parallel()+ gotFirst, gotSec := normalizePair(" alpha ", " bravo ")+ if gotFirst != "alpha" || gotSec != "bravo" {+ t.Fatalf("expected trimmed canonical forms (alpha, bravo), got (%q, %q)", gotFirst, gotSec)+ }+ // And the raw untrimmed inputs would NOT have satisfied the+ // sorted-output contract on their own here is asserted by+ // confirming the leading byte differs from the raw input.+ if gotFirst == " alpha " {+ t.Fatalf("normalizePair returned the RAW untrimmed input %q instead of the canonical form", gotFirst)+ }+ })+ })+}diff --git a/internal/unifiedresources/registry_k8sseed_branchcov0721am_test.go b/internal/unifiedresources/registry_k8sseed_branchcov0721am_test.gonew file mode 100644index 0000000000..f29658457d--- /dev/null+++ b/internal/unifiedresources/registry_k8sseed_branchcov0721am_test.go@@ -0,0 +1,200 @@+package unifiedresources++import (+ "testing"+)++// TestBranchcov0721amRegistryK8sSeed mechanically exercises every branch of the+// five pure unexported helpers in registry.go that the k8s seeding path relies+// on. Each subtest asserts exact expected values computed by hand from the+// source logic; it is intentionally exhaustive about nil/blank/whitespace+// guards so the branch coverage of these helpers goes to 100%. This file does+// not modify any source or pre-existing test.+func TestBranchcov0721amRegistryK8sSeed(t *testing.T) {+ t.Run("seededKubernetesClusterSourceID", func(t *testing.T) {+ cases := []struct {+ name string+ in *K8sData+ want string+ }{+ {name: "nil receiver", in: nil, want: ""},+ {name: "all zero value", in: &K8sData{}, want: ""},+ {name: "all whitespace only", in: &K8sData{+ ClusterID: " ",+ AgentID: "\t",+ SourceName: " \n ",+ ClusterName: " ",+ Context: " ",+ }, want: ""},+ {name: "ClusterID alone wins", in: &K8sData{ClusterID: "cid-1"}, want: "cid-1"},+ {name: "ClusterID wins over all later set", in: &K8sData{+ ClusterID: "cid-first", AgentID: "ag", SourceName: "sn",+ ClusterName: "cn", Context: "ctx",+ }, want: "cid-first"},+ {name: "AgentID wins when ClusterID blank", in: &K8sData{+ AgentID: " ag-1 ", ClusterName: "cn",+ }, want: "ag-1"},+ {name: "SourceName wins when ClusterID+AgentID blank", in: &K8sData{+ ClusterID: " ", AgentID: "", SourceName: "sn-1",+ }, want: "sn-1"},+ {name: "ClusterName wins when earlier blank", in: &K8sData{+ ClusterID: "", AgentID: " \t ", SourceName: "", ClusterName: "cn-1",+ }, want: "cn-1"},+ {name: "Context wins when all earlier blank", in: &K8sData{+ ClusterName: " ", Context: "ctx-1",+ }, want: "ctx-1"},+ {name: "trims surrounding whitespace from ClusterID", in: &K8sData{+ ClusterID: " cid-trim ",+ }, want: "cid-trim"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := seededKubernetesClusterSourceID(tc.in); got != tc.want {+ t.Fatalf("seededKubernetesClusterSourceID(%+v): want %q, got %q", tc.in, tc.want, got)+ }+ })+ }+ })++ t.Run("seededKubernetesNodeIdentity", func(t *testing.T) {+ cases := []struct {+ name string+ in *K8sData+ want string+ }{+ {name: "nil receiver", in: nil, want: ""},+ {name: "NodeUID present wins over NodeName", in: &K8sData{+ NodeUID: "uid-node-1", NodeName: "nm",+ }, want: "uid-node-1"},+ {name: "NodeUID whitespace falls back to NodeName", in: &K8sData{+ NodeUID: " ", NodeName: "nm-1",+ }, want: "nm-1"},+ {name: "NodeUID blank trims NodeName", in: &K8sData{+ NodeName: " nm-trim ",+ }, want: "nm-trim"},+ {name: "both blank", in: &K8sData{}, want: ""},+ {name: "both whitespace only", in: &K8sData{+ NodeUID: "\t", NodeName: " ",+ }, want: ""},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := seededKubernetesNodeIdentity(tc.in); got != tc.want {+ t.Fatalf("seededKubernetesNodeIdentity(%+v): want %q, got %q", tc.in, tc.want, got)+ }+ })+ }+ })++ t.Run("seededKubernetesPodIdentity", func(t *testing.T) {+ cases := []struct {+ name string+ res *Resource+ want string+ }{+ {name: "nil resource", res: nil, want: ""},+ {name: "nil Kubernetes", res: &Resource{Name: "n"}, want: ""},+ {name: "PodUID present wins", res: &Resource{+ Name: "pod", Kubernetes: &K8sData{PodUID: " pod-uid-1 ", Namespace: "ns"},+ }, want: "pod-uid-1"},+ {name: "PodUID blank -> namespace/name", res: &Resource{+ Name: " pod-nm ", Kubernetes: &K8sData{Namespace: " ns-1 "},+ }, want: "ns-1/pod-nm"},+ {name: "PodUID blank, name blank, ns set -> empty", res: &Resource{+ Kubernetes: &K8sData{Namespace: "ns-1"},+ }, want: ""},+ {name: "PodUID blank, ns blank, name set -> empty", res: &Resource{+ Name: "pod-nm", Kubernetes: &K8sData{},+ }, want: ""},+ {name: "PodUID blank, both blank -> empty", res: &Resource{+ Kubernetes: &K8sData{},+ }, want: ""},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := seededKubernetesPodIdentity(tc.res); got != tc.want {+ t.Fatalf("seededKubernetesPodIdentity: want %q, got %q", tc.want, got)+ }+ })+ }+ })++ t.Run("seededKubernetesDeploymentIdentity", func(t *testing.T) {+ cases := []struct {+ name string+ res *Resource+ want string+ }{+ {name: "nil resource", res: nil, want: ""},+ {name: "nil Kubernetes", res: &Resource{Name: "n"}, want: ""},+ {name: "DeploymentUID present wins", res: &Resource{+ Name: "dep", Kubernetes: &K8sData{DeploymentUID: " dep-uid-1 ", Namespace: "ns"},+ }, want: "dep-uid-1"},+ {name: "DeploymentUID blank -> namespace/name", res: &Resource{+ Name: " dep-nm ", Kubernetes: &K8sData{Namespace: " ns-1 "},+ }, want: "ns-1/dep-nm"},+ {name: "DeploymentUID blank, name blank, ns set -> empty", res: &Resource{+ Kubernetes: &K8sData{Namespace: "ns-1"},+ }, want: ""},+ {name: "DeploymentUID blank, ns blank, name set -> empty", res: &Resource{+ Name: "dep-nm", Kubernetes: &K8sData{},+ }, want: ""},+ {name: "DeploymentUID blank, both blank -> empty", res: &Resource{+ Kubernetes: &K8sData{},+ }, want: ""},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := seededKubernetesDeploymentIdentity(tc.res); got != tc.want {+ t.Fatalf("seededKubernetesDeploymentIdentity: want %q, got %q", tc.want, got)+ }+ })+ }+ })++ t.Run("seededKubernetesTypedSourceID", func(t *testing.T) {+ cases := []struct {+ name string+ clusterSourceID string+ kind string+ res *Resource+ uid string+ want string+ }{+ {name: "nil resource", clusterSourceID: "c", kind: "k", res: nil, uid: "u", want: ""},+ {name: "nil Kubernetes", clusterSourceID: "c", kind: "k", res: &Resource{Name: "n"}, uid: "u", want: ""},+ {name: "uid provided wins (trimmed)", clusterSourceID: "c-1", kind: "k8s-pod", res: &Resource{+ Name: "n", Kubernetes: &K8sData{Namespace: "ns"},+ }, uid: " uid-1 ", want: "c-1:k8s-pod:uid-1"},+ {name: "uid blank -> ns/name id", clusterSourceID: "c-1", kind: "k8s-pod", res: &Resource{+ Name: " nm ", Kubernetes: &K8sData{Namespace: " ns "},+ }, uid: "", want: "c-1:k8s-pod:ns/nm"},+ {name: "uid blank + ns blank -> name-only id", clusterSourceID: "c-1", kind: "k8s-pod", res: &Resource{+ Name: " nm ", Kubernetes: &K8sData{},+ }, uid: " ", want: "c-1:k8s-pod:nm"},+ {name: "uid blank + both ns/name blank -> empty id guard", clusterSourceID: "c-1", kind: "k8s-pod", res: &Resource{+ Kubernetes: &K8sData{},+ }, uid: "", want: ""},+ {name: "uid blank + ns set + name blank -> empty id guard", clusterSourceID: "c-1", kind: "k8s-pod", res: &Resource{+ Kubernetes: &K8sData{Namespace: "ns"},+ }, uid: "", want: ""},+ {name: "empty clusterSourceID guard", clusterSourceID: " ", kind: "k", res: &Resource{+ Name: "n", Kubernetes: &K8sData{},+ }, uid: "u", want: ""},+ {name: "empty kind guard", clusterSourceID: "c", kind: "", res: &Resource{+ Name: "n", Kubernetes: &K8sData{},+ }, uid: "u", want: ""},+ {name: "clusterSourceID and kind trimmed on success", clusterSourceID: " cluster-a ", kind: " k8s-node ", res: &Resource{+ Name: "ignored", Kubernetes: &K8sData{Namespace: "ignored-too"},+ }, uid: "uid-final", want: "cluster-a:k8s-node:uid-final"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := seededKubernetesTypedSourceID(tc.clusterSourceID, tc.kind, tc.res, tc.uid); got != tc.want {+ t.Fatalf("seededKubernetesTypedSourceID(%q,%q,%+v,%q): want %q, got %q",+ tc.clusterSourceID, tc.kind, tc.res, tc.uid, tc.want, got)+ }+ })+ }+ })+}diff --git a/internal/unifiedresources/registry_sourceid_branchcov0721am_test.go b/internal/unifiedresources/registry_sourceid_branchcov0721am_test.gonew file mode 100644index 0000000000..072cb4a272--- /dev/null+++ b/internal/unifiedresources/registry_sourceid_branchcov0721am_test.go@@ -0,0 +1,395 @@+package unifiedresources++import "testing"++// Branch-coverage tests for four currently-uncovered UNEXPORTED helpers in+// registry.go. Each target function is pure (no registry state, no I/O) so+// the tests exercise them directly with hand-computed expected values that+// pin the exact composition/format produced by the source.+//+// - seededVMwareSourceID — nil-guards + trimmed-ManagedObjectID empty guard+// + EntityType fallback to CanonicalResourceType(resource.Type) + optional+// ConnectionID prefix; final shape is ":"-joined.+// - proxmoxGuestFallbackSourceID — builds a non-blank-trimmed slice in+// (kind, instance, node) order, ALWAYS appends fmt.Sprintf("%d", vmid),+// then ":"-joins.+// - isDockerNetworkAttachmentRelationship — Type==RelAttachedTo &&+// TrimSpace(Discoverer)==dockerAdapterRelationshipDiscoverer.+// - physicalDiskTopologyCompatible — nil-guards + EqualFold checks for+// Controller and Target (each check skipped when either side is blank).+//+// Expected values are derived by hand from the source of each function in+// registry.go (see line references inline). No assertion is a "no panic"+// assertion: each subtest pins a specific string or boolean computed from+// the documented composition rules.++func TestBranchcov0721amRegistrySourceID(t *testing.T) {+ t.Run("seededVMwareSourceID", func(t *testing.T) {+ t.Parallel()++ // Each row drives one branch of seededVMwareSourceID+ // (registry.go:1122). The ":"-joined composition is:+ // [connectionID?] + [entityType?] + managedObjectID+ // where connectionID is included only when the trimmed+ // VMware.ConnectionID is non-empty, and entityType is either the+ // trimmed VMware.EntityType or — when that is blank — the+ // CanonicalResourceType(resource.Type) (i.e.+ // ToLower(TrimSpace(string(resource.Type)))).+ cases := []struct {+ name string+ resource *Resource+ want string+ skipEntityType bool // documents that entityType is intentionally absent+ }{+ {+ name: "nil_resource_returns_empty",+ resource: nil,+ want: "",+ },+ {+ name: "nil_VMware_payload_returns_empty",+ resource: &Resource{Type: ResourceTypeVM},+ want: "",+ },+ {+ name: "empty_managed_object_id_returns_empty",+ resource: &Resource{+ Type: ResourceTypeVM,+ VMware: &VMwareData{ManagedObjectID: "", EntityType: "host"},+ },+ want: "",+ },+ {+ name: "whitespace_only_managed_object_id_returns_empty",+ resource: &Resource{+ Type: ResourceTypeVM,+ VMware: &VMwareData{ManagedObjectID: " \t ", EntityType: "host"},+ },+ want: "",+ },+ {+ name: "entity_type_present_no_connection_id",+ resource: &Resource{+ Type: ResourceTypeVM,+ VMware: &VMwareData{ManagedObjectID: "mo-1", EntityType: "host"},+ },+ want: "host:mo-1",+ },+ {+ name: "entity_type_present_with_connection_id_prefix",+ resource: &Resource{+ Type: ResourceTypeVM,+ VMware: &VMwareData{ConnectionID: "conn-1", ManagedObjectID: "mo-1", EntityType: "host"},+ },+ want: "conn-1:host:mo-1",+ },+ {+ // EntityType blank → CanonicalResourceType("vm") = "vm".+ name: "blank_entity_type_falls_back_to_canonical_resource_type_vm",+ resource: &Resource{+ Type: ResourceTypeVM,+ VMware: &VMwareData{ManagedObjectID: "mo-1", EntityType: ""},+ },+ want: "vm:mo-1",+ },+ {+ // CanonicalResourceType = ToLower(TrimSpace(" VM ")) = "vm".+ name: "blank_entity_type_with_uppercase_whitespace_type_normalizes_to_vm",+ resource: &Resource{+ Type: ResourceType(" VM "),+ VMware: &VMwareData{ManagedObjectID: "mo-1", EntityType: " "},+ },+ want: "vm:mo-1",+ },+ {+ // CanonicalResourceType("VirtualMachine") = "virtualmachine".+ name: "blank_entity_type_with_long_type_name_normalizes_to_virtualmachine",+ resource: &Resource{+ Type: ResourceType("VirtualMachine"),+ VMware: &VMwareData{ManagedObjectID: "mo-9", EntityType: ""},+ },+ want: "virtualmachine:mo-9",+ },+ {+ // EntityType blank AND resource.Type empty → CanonicalResourceType+ // returns "" → the entityType slot is omitted entirely.+ name: "blank_entity_type_and_blank_type_omits_entity_type_slot",+ resource: &Resource{+ Type: ResourceType(""),+ VMware: &VMwareData{ManagedObjectID: "mo-2", EntityType: ""},+ },+ want: "mo-2",+ skipEntityType: true,+ },+ {+ // TrimSpace applied to all three composed fields:+ // ConnectionID " conn-1 " → "conn-1"+ // EntityType " host " → "host"+ // ManagedObjectID " mo-1 " → "mo-1"+ name: "all_composed_fields_are_trimmed",+ resource: &Resource{+ Type: ResourceTypeVM,+ VMware: &VMwareData{+ ConnectionID: " conn-1 ",+ ManagedObjectID: " mo-1 ",+ EntityType: " host ",+ },+ },+ want: "conn-1:host:mo-1",+ },+ {+ // ConnectionID whitespace-only is dropped → no prefix.+ name: "whitespace_only_connection_id_is_dropped",+ resource: &Resource{+ Type: ResourceTypeVM,+ VMware: &VMwareData{+ ConnectionID: " ",+ ManagedObjectID: "mo-1",+ EntityType: "host",+ },+ },+ want: "host:mo-1",+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ got := seededVMwareSourceID(tc.resource)+ if got != tc.want {+ t.Fatalf("seededVMwareSourceID(%+v) = %q, want %q", tc.resource, got, tc.want)+ }+ })+ }+ })++ t.Run("proxmoxGuestFallbackSourceID", func(t *testing.T) {+ t.Parallel()++ // Each row drives one of the three conditional appends in+ // proxmoxGuestFallbackSourceID (registry.go:4177). The final+ // element (Sprintf("%d", vmid)) is ALWAYS appended.+ cases := []struct {+ name string+ kind string+ instance string+ node string+ vmid int+ want string+ }{+ {+ name: "all_components_present",+ kind: "qemu",+ instance: "inst-1",+ node: "node-1",+ vmid: 100,+ want: "qemu:inst-1:node-1:100",+ },+ {+ name: "kind_blank_dropped",+ kind: "",+ instance: "inst-1",+ node: "node-1",+ vmid: 101,+ want: "inst-1:node-1:101",+ },+ {+ name: "instance_blank_dropped",+ kind: "qemu",+ instance: "",+ node: "node-1",+ vmid: 102,+ want: "qemu:node-1:102",+ },+ {+ name: "node_blank_dropped",+ kind: "qemu",+ instance: "inst-1",+ node: "",+ vmid: 103,+ want: "qemu:inst-1:103",+ },+ {+ name: "all_three_blank_yields_just_vmid",+ kind: "",+ instance: "",+ node: "",+ vmid: 104,+ want: "104",+ },+ {+ name: "whitespace_only_components_are_dropped",+ kind: " ",+ instance: "\t",+ node: " ",+ vmid: 105,+ want: "105",+ },+ {+ name: "components_are_trimmed_before_joining",+ kind: " qemu ",+ instance: " inst-1 ",+ node: " node-1 ",+ vmid: 200,+ want: "qemu:inst-1:node-1:200",+ },+ {+ // vmid is rendered with %d, so a zero value still appears.+ name: "zero_vmid_is_rendered",+ kind: "qemu", instance: "i", node: "n", vmid: 0,+ want: "qemu:i:n:0",+ },+ {+ // Negative vmid keeps its sign under %d formatting.+ name: "negative_vmid_keeps_sign",+ kind: "qemu", instance: "i", node: "n", vmid: -7,+ want: "qemu:i:n:-7",+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ got := proxmoxGuestFallbackSourceID(tc.kind, tc.instance, tc.node, tc.vmid)+ if got != tc.want {+ t.Fatalf("proxmoxGuestFallbackSourceID(%q, %q, %q, %d) = %q, want %q",+ tc.kind, tc.instance, tc.node, tc.vmid, got, tc.want)+ }+ })+ }+ })++ t.Run("isDockerNetworkAttachmentRelationship", func(t *testing.T) {+ t.Parallel()++ // Each row drives one arm of the && predicate in+ // isDockerNetworkAttachmentRelationship (registry.go:1948):+ // Type == RelAttachedTo && TrimSpace(Discoverer) == dockerAdapterRelationshipDiscoverer+ cases := []struct {+ name string+ relationship ResourceRelationship+ want bool+ }{+ {+ name: "both_type_and_discoverer_match",+ relationship: ResourceRelationship{Type: RelAttachedTo, Discoverer: dockerAdapterRelationshipDiscoverer},+ want: true,+ },+ {+ // TrimSpace is applied to the Discoverer side.+ name: "discoverer_with_surrounding_whitespace_matches",+ relationship: ResourceRelationship{Type: RelAttachedTo, Discoverer: " " + dockerAdapterRelationshipDiscoverer + " "},+ want: true,+ },+ {+ name: "wrong_relationship_type_returns_false",+ relationship: ResourceRelationship{Type: RelRunsOn, Discoverer: dockerAdapterRelationshipDiscoverer},+ want: false,+ },+ {+ name: "empty_relationship_type_returns_false",+ relationship: ResourceRelationship{Type: "", Discoverer: dockerAdapterRelationshipDiscoverer},+ want: false,+ },+ {+ name: "wrong_discoverer_returns_false",+ relationship: ResourceRelationship{Type: RelAttachedTo, Discoverer: "pulse_inference_engine"},+ want: false,+ },+ {+ name: "empty_discoverer_returns_false",+ relationship: ResourceRelationship{Type: RelAttachedTo, Discoverer: ""},+ want: false,+ },+ {+ // Whitespace-only Discoverer trims to "" which != constant.+ name: "whitespace_only_discoverer_returns_false",+ relationship: ResourceRelationship{Type: RelAttachedTo, Discoverer: " "},+ want: false,+ },+ {+ name: "both_wrong_returns_false",+ relationship: ResourceRelationship{Type: RelOwnedBy, Discoverer: "k8s_adapter"},+ want: false,+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ got := isDockerNetworkAttachmentRelationship(tc.relationship)+ if got != tc.want {+ t.Fatalf("isDockerNetworkAttachmentRelationship(type=%s, discoverer=%q) = %v, want %v",+ tc.relationship.Type, tc.relationship.Discoverer, got, tc.want)+ }+ })+ }+ })++ t.Run("physicalDiskTopologyCompatible", func(t *testing.T) {+ t.Parallel()++ // Each row drives one branch of physicalDiskTopologyCompatible+ // (registry.go:2658):+ // nil-guard OR controller-mismatch OR target-mismatch OR compatible.+ // Each comparison is skipped when EITHER side's field is blank,+ // and uses EqualFold(TrimSpace(left), TrimSpace(right)).+ sda := &PhysicalDiskMeta{Controller: "sda"}+ sdb := &PhysicalDiskMeta{Controller: "sdb"}+ sdaUpper := &PhysicalDiskMeta{Controller: "SDA"}+ sdaWithSpaces := &PhysicalDiskMeta{Controller: " sda "}+ controllerBlank := &PhysicalDiskMeta{Controller: ""}+ targetOne := &PhysicalDiskMeta{Target: "t1"}+ targetTwo := &PhysicalDiskMeta{Target: "t2"}+ targetOneUpper := &PhysicalDiskMeta{Target: "T1"}+ targetOneSpaces := &PhysicalDiskMeta{Target: " t1 "}+ bothFieldsMatch := &PhysicalDiskMeta{Controller: "sda", Target: "t1"}+ bothFieldsMatchAlt := &PhysicalDiskMeta{Controller: "SDA", Target: "T1"}+ empty := &PhysicalDiskMeta{}++ cases := []struct {+ name string+ left *PhysicalDiskMeta+ right *PhysicalDiskMeta+ want bool+ }{+ {name: "nil_left_returns_false", left: nil, right: sda, want: false},+ {name: "nil_right_returns_false", left: sda, right: nil, want: false},+ {name: "both_nil_returns_false", left: nil, right: nil, want: false},++ {name: "controller_mismatch_returns_false", left: sda, right: sdb, want: false},+ {name: "controller_case_insensitive_match_is_compatible", left: sda, right: sdaUpper, want: true},+ {name: "controller_match_with_inner_whitespace_is_compatible", left: sda, right: sdaWithSpaces, want: true},++ {name: "one_side_blank_controller_skips_controller_check", left: controllerBlank, right: sda, want: true},+ {name: "both_sides_blank_controller_skips_controller_check", left: controllerBlank, right: &PhysicalDiskMeta{Controller: " "}, want: true},++ {name: "target_mismatch_returns_false", left: targetOne, right: targetTwo, want: false},+ {name: "target_case_insensitive_match_is_compatible", left: targetOne, right: targetOneUpper, want: true},+ {name: "target_match_with_inner_whitespace_is_compatible", left: targetOne, right: targetOneSpaces, want: true},++ {name: "one_side_blank_target_skips_target_check", left: &PhysicalDiskMeta{Target: ""}, right: targetOne, want: true},++ {name: "controller_match_target_mismatch_returns_false", left: bothFieldsMatch, right: &PhysicalDiskMeta{Controller: "sda", Target: "t2"}, want: false},+ {name: "controller_mismatch_target_match_returns_false", left: bothFieldsMatch, right: &PhysicalDiskMeta{Controller: "sdb", Target: "t1"}, want: false},++ {name: "both_controller_and_target_match_case_insensitively", left: bothFieldsMatch, right: bothFieldsMatchAlt, want: true},+ {name: "both_sides_empty_compatible", left: empty, right: empty, want: true},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ got := physicalDiskTopologyCompatible(tc.left, tc.right)+ if got != tc.want {+ t.Fatalf("physicalDiskTopologyCompatible(left=%+v, right=%+v) = %v, want %v",+ tc.left, tc.right, got, tc.want)+ }+ })+ }+ })+}