Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Cover the connection and monitoring pure helpers left untested by the fresh drop

rcourtman567303778a60
diff --git a/internal/api/connections_aggregator_pmg_branchcov0722am_test.go b/internal/api/connections_aggregator_pmg_branchcov0722am_test.go
new file mode 100644
index 0000000000..cdfef7ac6a
--- /dev/null
+++ b/internal/api/connections_aggregator_pmg_branchcov0722am_test.go
@@ -0,0 +1,508 @@
+package api
+
+import (
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+)
+
+// This file adds branch coverage for buildPMGConnection
+// (internal/api/connections_aggregator.go), which previously had 0.0% test
+// coverage. Every top-level function is prefixed with TestBranchcov0722 so the
+// run can be scoped with -run "^TestBranchcov0722".
+//
+// buildPMGConnection derives a Connection row from a config.PMGInstance plus a
+// health map keyed "pmg::<name>". The arms exercised below are:
+// - the Disabled -> Enabled flip,
+// - each per-surface monitor scope flag (mailStats, queues, quarantine,
+// domainStats) toggled on and off,
+// - a health map that contains an entry for this instance and one that does
+// not,
+// - the status/last-seen derivation off a frozen `now` for every state arm
+// of deriveConnectionState reachable through the builder (paused, pending,
+// unauthorized, unreachable via first failure, unreachable via breaker,
+// stale, active),
+// - the Proxmox credential-kind derivation (token / password / unknown /
+// whitespace) surfaced through Fleet.CredentialHealth,
+// - the static identity fields (id, type, address, host aliases, source,
+// surfaces, capabilities).
+
+// frozenNow is the fixed reference time every subtest derives time-derived
+// fields against, so LastSeen / stale reasons / credential timestamps are
+// reproducible. It is UTC to avoid host-timezone bleed into formatted reasons.
+var frozenNow = time.Date(2026, 7, 22, 10, 0, 0, 0, time.UTC)
+
+// pmgHealthEntry builds an InstanceHealth with deterministic timestamps. The
+// shared healthEntry helper stamps errors with time.Now(), which would make
+// LastError.At (and the derived LastFailedAt) non-deterministic; this variant
+// takes an explicit error timestamp so derived values can be asserted exactly.
+func pmgHealthEntry(lastSuccess *time.Time, errAt *time.Time, errMessage, errCategory, breakerState string) monitoring.InstanceHealth {
+ ps := monitoring.InstancePollStatus{LastSuccess: lastSuccess}
+ if errMessage != "" {
+ detail := &monitoring.ErrorDetail{Message: errMessage, Category: errCategory}
+ if errAt != nil {
+ detail.At = *errAt
+ }
+ ps.LastError = detail
+ }
+ return monitoring.InstanceHealth{
+ PollStatus: ps,
+ Breaker: monitoring.InstanceBreaker{State: breakerState},
+ }
+}
+
+// wantPMGSurfaces is the always-on surface list the builder emits regardless of
+// the per-surface scope flags; asserting it stays constant distinguishes
+// "surfaces" (what can be collected) from "scope" (what is enabled).
+var wantPMGSurfaces = []string{"mailStats", "queues", "quarantine", "domainStats"}
+
+// TestBranchcov0722PMGConnectionDisabledFlip exercises the !inst.Disabled ->
+// Enabled flip and the fleet-governance consequences of pausing a PMG source.
+func TestBranchcov0722PMGConnectionDisabledFlip(t *testing.T) {
+ t.Run("disabled_instance_is_paused_and_not_enabled", func(t *testing.T) {
+ inst := config.PMGInstance{Name: "mail-relay", Host: "mail.lan", Disabled: true}
+ conn := buildPMGConnection(inst, nil, frozenNow)
+
+ if conn.Enabled {
+ t.Fatalf("Enabled = true, want false for Disabled instance")
+ }
+ if conn.State != ConnectionStatePaused {
+ t.Fatalf("State = %q, want %q", conn.State, ConnectionStatePaused)
+ }
+ if conn.StateReason != "paused by user" {
+ t.Fatalf("StateReason = %q, want %q", conn.StateReason, "paused by user")
+ }
+ fleet := conn.Fleet
+ if fleet.EnrollmentState != fleetStatePaused {
+ t.Fatalf("EnrollmentState = %q, want %q", fleet.EnrollmentState, fleetStatePaused)
+ }
+ if fleet.LivenessState != string(ConnectionStatePaused) {
+ t.Fatalf("LivenessState = %q, want %q", fleet.LivenessState, ConnectionStatePaused)
+ }
+ if fleet.AdapterHealth != fleetStatePaused {
+ t.Fatalf("AdapterHealth = %q, want %q", fleet.AdapterHealth, fleetStatePaused)
+ }
+ if fleet.ConfigRollout != fleetStatePaused {
+ t.Fatalf("ConfigRollout = %q, want %q", fleet.ConfigRollout, fleetStatePaused)
+ }
+ if fleet.CredentialStatus != fleetStatePaused {
+ t.Fatalf("CredentialStatus = %q, want %q", fleet.CredentialStatus, fleetStatePaused)
+ }
+ if fleet.ConfigDrift == nil || fleet.ConfigDrift.Status != fleetStatePaused {
+ t.Fatalf("ConfigDrift = %+v, want paused", fleet.ConfigDrift)
+ }
+ if fleet.Rollout == nil || fleet.Rollout.Status != fleetStatePaused || fleet.Rollout.Stage != fleetRolloutStagePaused {
+ t.Fatalf("Rollout = %+v, want status=%q stage=%q", fleet.Rollout, fleetStatePaused, fleetRolloutStagePaused)
+ }
+ if fleet.CredentialHealth == nil || fleet.CredentialHealth.Status != fleetStatePaused {
+ t.Fatalf("CredentialHealth = %+v, want status %q", fleet.CredentialHealth, fleetStatePaused)
+ }
+ })
+
+ t.Run("enabled_instance_is_not_paused", func(t *testing.T) {
+ inst := config.PMGInstance{Name: "mail-relay", Host: "mail.lan"}
+ conn := buildPMGConnection(inst, nil, frozenNow)
+
+ if !conn.Enabled {
+ t.Fatalf("Enabled = false, want true for non-Disabled instance")
+ }
+ // No health entry yet -> pending, not paused.
+ if conn.State != ConnectionStatePending {
+ t.Fatalf("State = %q, want %q", conn.State, ConnectionStatePending)
+ }
+ if conn.Fleet.EnrollmentState != fleetStateConfigured {
+ t.Fatalf("EnrollmentState = %q, want %q", conn.Fleet.EnrollmentState, fleetStateConfigured)
+ }
+ })
+}
+
+// TestBranchcov0722PMGConnectionScopeFlags exercises each per-surface monitor
+// scope flag toggled on and off. The surface list must stay constant; only the
+// scope map values follow the Monitor* flags.
+func TestBranchcov0722PMGConnectionScopeFlags(t *testing.T) {
+ cases := []struct {
+ name string
+ inst config.PMGInstance
+ wantOn map[string]bool
+ }{
+ {
+ name: "all_flags_off",
+ inst: config.PMGInstance{Name: "m", Host: "h.lan"},
+ wantOn: map[string]bool{
+ "mailStats": false, "queues": false, "quarantine": false, "domainStats": false,
+ },
+ },
+ {
+ name: "all_flags_on",
+ inst: config.PMGInstance{
+ Name: "m", Host: "h.lan",
+ MonitorMailStats: true, MonitorQueues: true, MonitorQuarantine: true, MonitorDomainStats: true,
+ },
+ wantOn: map[string]bool{
+ "mailStats": true, "queues": true, "quarantine": true, "domainStats": true,
+ },
+ },
+ {
+ name: "only_mail_stats",
+ inst: config.PMGInstance{Name: "m", Host: "h.lan", MonitorMailStats: true},
+ wantOn: map[string]bool{
+ "mailStats": true, "queues": false, "quarantine": false, "domainStats": false,
+ },
+ },
+ {
+ name: "only_queues",
+ inst: config.PMGInstance{Name: "m", Host: "h.lan", MonitorQueues: true},
+ wantOn: map[string]bool{
+ "mailStats": false, "queues": true, "quarantine": false, "domainStats": false,
+ },
+ },
+ {
+ name: "only_quarantine",
+ inst: config.PMGInstance{Name: "m", Host: "h.lan", MonitorQuarantine: true},
+ wantOn: map[string]bool{
+ "mailStats": false, "queues": false, "quarantine": true, "domainStats": false,
+ },
+ },
+ {
+ name: "only_domain_stats",
+ inst: config.PMGInstance{Name: "m", Host: "h.lan", MonitorDomainStats: true},
+ wantOn: map[string]bool{
+ "mailStats": false, "queues": false, "quarantine": false, "domainStats": true,
+ },
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ conn := buildPMGConnection(tc.inst, nil, frozenNow)
+
+ // Surfaces are always the full, ordered list regardless of scope.
+ if !reflect.DeepEqual(conn.Surfaces, wantPMGSurfaces) {
+ t.Fatalf("Surfaces = %+v, want %+v", conn.Surfaces, wantPMGSurfaces)
+ }
+ // The scope map must contain exactly the four PMG surfaces.
+ if len(conn.Scope) != len(wantPMGSurfaces) {
+ t.Fatalf("Scope has %d entries, want %d (%+v)", len(conn.Scope), len(wantPMGSurfaces), conn.Scope)
+ }
+ for _, surface := range wantPMGSurfaces {
+ got, ok := conn.Scope[surface]
+ if !ok {
+ t.Fatalf("Scope missing required surface %q (got %+v)", surface, conn.Scope)
+ }
+ if got != tc.wantOn[surface] {
+ t.Fatalf("Scope[%q] = %v, want %v", surface, got, tc.wantOn[surface])
+ }
+ }
+ // Scope is the only field these flags influence for PMG.
+ if !reflect.DeepEqual(conn.Scope, tc.wantOn) {
+ t.Fatalf("Scope = %+v, want %+v", conn.Scope, tc.wantOn)
+ }
+ })
+ }
+}
+
+// TestBranchcov0722PMGConnectionHealthLookup exercises the "pmg::<name>" health
+// map lookup: an entry for this instance drives state/last-seen, while a missing
+// entry (or an entry keyed for a different instance) leaves the connection
+// pending with no last-seen.
+func TestBranchcov0722PMGConnectionHealthLookup(t *testing.T) {
+ inst := config.PMGInstance{Name: "mail-relay", Host: "mail.lan"}
+ recentSuccess := frozenNow.Add(-30 * time.Second)
+
+ t.Run("health_entry_present_drives_active_state", func(t *testing.T) {
+ health := map[string]monitoring.InstanceHealth{
+ "pmg::mail-relay": pmgHealthEntry(&recentSuccess, nil, "", "", "closed"),
+ }
+ conn := buildPMGConnection(inst, health, frozenNow)
+ if conn.State != ConnectionStateActive {
+ t.Fatalf("State = %q, want %q", conn.State, ConnectionStateActive)
+ }
+ if conn.LastSeen == nil || !conn.LastSeen.Equal(recentSuccess) {
+ t.Fatalf("LastSeen = %+v, want %s", conn.LastSeen, recentSuccess)
+ }
+ if conn.LastError != nil {
+ t.Fatalf("LastError = %+v, want nil for healthy entry", conn.LastError)
+ }
+ })
+
+ t.Run("health_entry_missing_leaves_pending", func(t *testing.T) {
+ // Empty map, nil map, and a wrong-key map must all behave the same:
+ // no health resolved -> awaiting first poll.
+ for label, health := range map[string]map[string]monitoring.InstanceHealth{
+ "nil_map": nil,
+ "empty_map": {},
+ "wrong_key": {"pmg::other-relay": pmgHealthEntry(&recentSuccess, nil, "", "", "closed")},
+ } {
+ conn := buildPMGConnection(inst, health, frozenNow)
+ if conn.State != ConnectionStatePending {
+ t.Fatalf("%s: State = %q, want %q", label, conn.State, ConnectionStatePending)
+ }
+ if conn.StateReason != "awaiting first poll" {
+ t.Fatalf("%s: StateReason = %q, want %q", label, conn.StateReason, "awaiting first poll")
+ }
+ if conn.LastSeen != nil {
+ t.Fatalf("%s: LastSeen = %+v, want nil", label, conn.LastSeen)
+ }
+ if conn.LastError != nil {
+ t.Fatalf("%s: LastError = %+v, want nil", label, conn.LastError)
+ }
+ }
+ })
+}
+
+// TestBranchcov0722PMGConnectionStateDerivation drives every state arm of
+// deriveConnectionState that is reachable through buildPMGConnection, asserting
+// the exact state, reason, last-seen and last-error derived from the frozen
+// `now`. Health is always keyed under "pmg::mail-relay".
+func TestBranchcov0722PMGConnectionStateDerivation(t *testing.T) {
+ name := "mail-relay"
+ healthKey := "pmg::" + name
+ base := config.PMGInstance{Name: name, Host: "mail.lan"}
+
+ t.Run("paused_when_disabled", func(t *testing.T) {
+ // Disabled short-circuits before health is consulted; a present error
+ // must not promote a disabled source out of "paused".
+ errAt := frozenNow.Add(-1 * time.Minute)
+ inst := base
+ inst.Disabled = true
+ health := map[string]monitoring.InstanceHealth{
+ healthKey: pmgHealthEntry(ptrTime(frozenNow.Add(-30*time.Second)), &errAt, "401 Unauthorized", "auth", "closed"),
+ }
+ conn := buildPMGConnection(inst, health, frozenNow)
+ if conn.State != ConnectionStatePaused {
+ t.Fatalf("State = %q, want %q", conn.State, ConnectionStatePaused)
+ }
+ if conn.StateReason != "paused by user" {
+ t.Fatalf("StateReason = %q, want %q", conn.StateReason, "paused by user")
+ }
+ })
+
+ t.Run("pending_with_no_poll_history", func(t *testing.T) {
+ conn := buildPMGConnection(base, map[string]monitoring.InstanceHealth{
+ healthKey: pmgHealthEntry(nil, nil, "", "", "closed"),
+ }, frozenNow)
+ if conn.State != ConnectionStatePending {
+ t.Fatalf("State = %q, want %q", conn.State, ConnectionStatePending)
+ }
+ if conn.StateReason != "awaiting first poll" {
+ t.Fatalf("StateReason = %q, want %q", conn.StateReason, "awaiting first poll")
+ }
+ if conn.LastSeen != nil || conn.LastError != nil {
+ t.Fatalf("LastSeen/LastError = %+v/%+v, want nil/nil", conn.LastSeen, conn.LastError)
+ }
+ })
+
+ t.Run("unauthorized_on_auth_error", func(t *testing.T) {
+ errAt := frozenNow.Add(-2 * time.Minute)
+ health := map[string]monitoring.InstanceHealth{
+ healthKey: pmgHealthEntry(nil, &errAt, "403 Forbidden: token lacks scope", "auth", "closed"),
+ }
+ conn := buildPMGConnection(base, health, frozenNow)
+ if conn.State != ConnectionStateUnauthorized {
+ t.Fatalf("State = %q, want %q", conn.State, ConnectionStateUnauthorized)
+ }
+ if conn.StateReason != "403 Forbidden: token lacks scope" {
+ t.Fatalf("StateReason = %q, want the auth error message", conn.StateReason)
+ }
+ if conn.LastSeen != nil {
+ t.Fatalf("LastSeen = %+v, want nil when no successful poll recorded", conn.LastSeen)
+ }
+ if conn.LastError == nil ||
+ conn.LastError.Message != "403 Forbidden: token lacks scope" ||
+ conn.LastError.Category != "auth" ||
+ !conn.LastError.At.Equal(errAt) {
+ t.Fatalf("LastError = %+v, want message/category/At derived from health", conn.LastError)
+ }
+ // Fleet credential health records the failure timestamp for invalid creds.
+ if conn.Fleet.CredentialHealth == nil ||
+ conn.Fleet.CredentialHealth.LastFailedAt == nil ||
+ !conn.Fleet.CredentialHealth.LastFailedAt.Equal(errAt) {
+ t.Fatalf("CredentialHealth.LastFailedAt = %+v, want %s", conn.Fleet.CredentialHealth, errAt)
+ }
+ })
+
+ t.Run("unreachable_on_first_failure_without_success", func(t *testing.T) {
+ errAt := frozenNow.Add(-90 * time.Second)
+ health := map[string]monitoring.InstanceHealth{
+ healthKey: pmgHealthEntry(nil, &errAt, "connection refused", "network", "closed"),
+ }
+ conn := buildPMGConnection(base, health, frozenNow)
+ if conn.State != ConnectionStateUnreachable {
+ t.Fatalf("State = %q, want %q", conn.State, ConnectionStateUnreachable)
+ }
+ if conn.StateReason != "connection refused" {
+ t.Fatalf("StateReason = %q, want %q", conn.StateReason, "connection refused")
+ }
+ if conn.LastError == nil || conn.LastError.Message != "connection refused" {
+ t.Fatalf("LastError = %+v, want connection refused", conn.LastError)
+ }
+ })
+
+ t.Run("unreachable_when_breaker_open", func(t *testing.T) {
+ // A prior success exists (so it is not the first-failure arm) but the
+ // breaker has tripped open; no error message means the generic reason.
+ success := frozenNow.Add(-30 * time.Second)
+ health := map[string]monitoring.InstanceHealth{
+ healthKey: pmgHealthEntry(&success, nil, "", "", "open"),
+ }
+ conn := buildPMGConnection(base, health, frozenNow)
+ if conn.State != ConnectionStateUnreachable {
+ t.Fatalf("State = %q, want %q", conn.State, ConnectionStateUnreachable)
+ }
+ if conn.StateReason != "circuit breaker open" {
+ t.Fatalf("StateReason = %q, want %q", conn.StateReason, "circuit breaker open")
+ }
+ if conn.LastSeen == nil || !conn.LastSeen.Equal(success) {
+ t.Fatalf("LastSeen = %+v, want %s", conn.LastSeen, success)
+ }
+ })
+
+ t.Run("stale_when_last_success_beyond_threshold", func(t *testing.T) {
+ // connectionStaleThreshold is 2 minutes; 5 minutes ago must be stale.
+ staleSuccess := frozenNow.Add(-5 * time.Minute)
+ health := map[string]monitoring.InstanceHealth{
+ healthKey: pmgHealthEntry(&staleSuccess, nil, "", "", "closed"),
+ }
+ conn := buildPMGConnection(base, health, frozenNow)
+ if conn.State != ConnectionStateStale {
+ t.Fatalf("State = %q, want %q", conn.State, ConnectionStateStale)
+ }
+ wantReason := "no successful poll in 5m0s"
+ if conn.StateReason != wantReason {
+ t.Fatalf("StateReason = %q, want %q (derived from frozen now)", conn.StateReason, wantReason)
+ }
+ if conn.LastSeen == nil || !conn.LastSeen.Equal(staleSuccess) {
+ t.Fatalf("LastSeen = %+v, want %s", conn.LastSeen, staleSuccess)
+ }
+ })
+
+ t.Run("active_when_recent_success", func(t *testing.T) {
+ recentSuccess := frozenNow.Add(-30 * time.Second)
+ health := map[string]monitoring.InstanceHealth{
+ healthKey: pmgHealthEntry(&recentSuccess, nil, "", "", "closed"),
+ }
+ conn := buildPMGConnection(base, health, frozenNow)
+ if conn.State != ConnectionStateActive {
+ t.Fatalf("State = %q, want %q", conn.State, ConnectionStateActive)
+ }
+ if conn.StateReason != "" {
+ t.Fatalf("StateReason = %q, want empty for active connection", conn.StateReason)
+ }
+ if conn.LastSeen == nil || !conn.LastSeen.Equal(recentSuccess) {
+ t.Fatalf("LastSeen = %+v, want %s", conn.LastSeen, recentSuccess)
+ }
+ // Active platform connections record the last successful poll as the
+ // credential last-verified timestamp.
+ if conn.Fleet.CredentialHealth == nil ||
+ conn.Fleet.CredentialHealth.LastVerifiedAt == nil ||
+ !conn.Fleet.CredentialHealth.LastVerifiedAt.Equal(recentSuccess) {
+ t.Fatalf("CredentialHealth.LastVerifiedAt = %+v, want %s", conn.Fleet.CredentialHealth, recentSuccess)
+ }
+ })
+}
+
+// TestBranchcov0722PMGConnectionCredentialKind exercises the
+// connectionProxmoxCredentialKind derivation surfaced through
+// Fleet.CredentialHealth.Kind: token credentials win over password, password
+// wins over none, whitespace-only credentials count as none, and the kind does
+// not change the rotation status when there is no expiry.
+func TestBranchcov0722PMGConnectionCredentialKind(t *testing.T) {
+ cases := []struct {
+ name string
+ inst config.PMGInstance
+ wantKind string
+ }{
+ {name: "token_value", inst: config.PMGInstance{Name: "m", Host: "h.lan", TokenValue: "secret"}, wantKind: fleetCredentialKindToken},
+ {name: "token_name", inst: config.PMGInstance{Name: "m", Host: "h.lan", TokenName: "api"}, wantKind: fleetCredentialKindToken},
+ {name: "token_over_password", inst: config.PMGInstance{Name: "m", Host: "h.lan", User: "root@pam", Password: "hunter2", TokenName: "api"}, wantKind: fleetCredentialKindToken},
+ {name: "password_user", inst: config.PMGInstance{Name: "m", Host: "h.lan", User: "root@pam"}, wantKind: fleetCredentialKindPassword},
+ {name: "password_value", inst: config.PMGInstance{Name: "m", Host: "h.lan", Password: "hunter2"}, wantKind: fleetCredentialKindPassword},
+ {name: "no_credentials", inst: config.PMGInstance{Name: "m", Host: "h.lan"}, wantKind: fleetStateUnknown},
+ {name: "whitespace_only_token", inst: config.PMGInstance{Name: "m", Host: "h.lan", TokenName: " ", TokenValue: "\t"}, wantKind: fleetStateUnknown},
+ {name: "whitespace_only_password", inst: config.PMGInstance{Name: "m", Host: "h.lan", User: " ", Password: " "}, wantKind: fleetStateUnknown},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ conn := buildPMGConnection(tc.inst, nil, frozenNow)
+ ch := conn.Fleet.CredentialHealth
+ if ch == nil {
+ t.Fatalf("CredentialHealth is nil")
+ }
+ if ch.Kind != tc.wantKind {
+ t.Fatalf("Kind = %q, want %q", ch.Kind, tc.wantKind)
+ }
+ // No expiry is ever supplied for PMG credentials, so rotation stays
+ // healthy regardless of the derived kind.
+ if ch.Rotation != fleetCredentialRotationHealthy {
+ t.Fatalf("Rotation = %q, want %q (no expiry supplied)", ch.Rotation, fleetCredentialRotationHealthy)
+ }
+ if ch.ExpiresAt != nil {
+ t.Fatalf("ExpiresAt = %+v, want nil", ch.ExpiresAt)
+ }
+ })
+ }
+}
+
+// TestBranchcov0722PMGConnectionStaticFields asserts the identity fields the
+// builder hard-codes for PMG sources, independent of health/scope: the id
+// prefix, the type, the passthrough name/address, the normalised host aliases,
+// the manual source, the always-on capabilities, and that the fleet governance
+// for a non-agent platform type marks agent-only dimensions not-applicable.
+func TestBranchcov0722PMGConnectionStaticFields(t *testing.T) {
+ inst := config.PMGInstance{
+ Name: "mail-relay",
+ Host: "https://mail.lan:8006",
+ }
+ conn := buildPMGConnection(inst, nil, frozenNow)
+
+ if conn.ID != "pmg:mail-relay" {
+ t.Fatalf("ID = %q, want %q", conn.ID, "pmg:mail-relay")
+ }
+ if conn.Type != ConnectionTypePMG {
+ t.Fatalf("Type = %q, want %q", conn.Type, ConnectionTypePMG)
+ }
+ if conn.Name != "mail-relay" {
+ t.Fatalf("Name = %q, want %q", conn.Name, "mail-relay")
+ }
+ // Address is the raw Host, not URL-normalised.
+ if conn.Address != "https://mail.lan:8006" {
+ t.Fatalf("Address = %q, want the raw Host", conn.Address)
+ }
+ // Host aliases normalise the name (lowercased) and the URL (hostname only).
+ wantAliases := []string{"mail-relay", "mail.lan"}
+ if !reflect.DeepEqual(conn.HostAliases, wantAliases) {
+ t.Fatalf("HostAliases = %+v, want %+v", conn.HostAliases, wantAliases)
+ }
+ if conn.Source != ConnectionSourceManual {
+ t.Fatalf("Source = %q, want %q (PMG source is always manual)", conn.Source, ConnectionSourceManual)
+ }
+ if !reflect.DeepEqual(conn.Surfaces, wantPMGSurfaces) {
+ t.Fatalf("Surfaces = %+v, want %+v", conn.Surfaces, wantPMGSurfaces)
+ }
+ if !conn.Capabilities.SupportsPause || !conn.Capabilities.SupportsScope || !conn.Capabilities.SupportsTest {
+ t.Fatalf("Capabilities = %+v, want all three supports flags true", conn.Capabilities)
+ }
+
+ // Agent-only fleet dimensions are not applicable to a platform source.
+ fleet := conn.Fleet
+ if fleet.VersionDrift != fleetStateNotApplicable {
+ t.Fatalf("VersionDrift = %q, want %q", fleet.VersionDrift, fleetStateNotApplicable)
+ }
+ if fleet.UpdateStatus != fleetStateNotApplicable {
+ t.Fatalf("UpdateStatus = %q, want %q", fleet.UpdateStatus, fleetStateNotApplicable)
+ }
+ if fleet.RemoteControl != fleetStateNotApplicable {
+ t.Fatalf("RemoteControl = %q, want %q", fleet.RemoteControl, fleetStateNotApplicable)
+ }
+ if fleet.CommandPolicy == nil ||
+ fleet.CommandPolicy.Status != fleetStateNotApplicable ||
+ fleet.CommandPolicy.Desired != fleetCommandPolicyNotApplicable ||
+ fleet.CommandPolicy.Applied != fleetCommandPolicyNotApplicable ||
+ fleet.CommandPolicy.Enforcement != fleetCommandPolicyNotApplicable {
+ t.Fatalf("CommandPolicy = %+v, want all dimensions not-applicable", fleet.CommandPolicy)
+ }
+}
diff --git a/internal/api/connections_alerts_branchcov0722am_test.go b/internal/api/connections_alerts_branchcov0722am_test.go
new file mode 100644
index 0000000000..7cd66e131b
--- /dev/null
+++ b/internal/api/connections_alerts_branchcov0722am_test.go
@@ -0,0 +1,274 @@
+package api
+
+import (
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+)
+
+// This file exercises the previously-uncovered branch arms of three helpers
+// that sit on the boundary between the connections ledger and the alerts
+// package:
+// - connectionTypeForAlerts (connections_alerts.go)
+// - snapshotConnectionsForAlerts (connections_alerts.go)
+// - connectionHostIndex.uniqueMatch (connections_grouping.go)
+//
+// Every top-level function is prefixed with TestBranchcov0722 so the run can
+// be scoped with -run "^TestBranchcov0722".
+
+// TestBranchcov0722ConnectionTypeForAlerts covers every case arm of the
+// platform-type switch plus the default fallthrough that signals "drop this
+// row before invoking CheckConnection".
+func TestBranchcov0722ConnectionTypeForAlerts(t *testing.T) {
+ cases := []struct {
+ name string
+ input ConnectionType
+ want alerts.ConnectionType
+ wantOK bool
+ }{
+ {name: "pve", input: ConnectionTypePVE, want: alerts.ConnectionTypePVE, wantOK: true},
+ {name: "pbs", input: ConnectionTypePBS, want: alerts.ConnectionTypePBS, wantOK: true},
+ {name: "pmg", input: ConnectionTypePMG, want: alerts.ConnectionTypePMG, wantOK: true},
+ {name: "vmware", input: ConnectionTypeVMware, want: alerts.ConnectionTypeVMware, wantOK: true},
+ {name: "truenas", input: ConnectionTypeTrueNAS, want: alerts.ConnectionTypeTrueNAS, wantOK: true},
+ // Non-platform types share the default arm with truly unknown values;
+ // both must report ok==false so the caller skips them.
+ {name: "agent", input: ConnectionTypeAgent, want: "", wantOK: false},
+ {name: "docker", input: ConnectionTypeDocker, want: "", wantOK: false},
+ {name: "kubernetes", input: ConnectionTypeKubernetes, want: "", wantOK: false},
+ {name: "availability", input: ConnectionTypeAvailability, want: "", wantOK: false},
+ {name: "unknown", input: ConnectionType("nope"), want: "", wantOK: false},
+ {name: "zero", input: ConnectionType(""), want: "", wantOK: false},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, ok := connectionTypeForAlerts(tc.input)
+ if ok != tc.wantOK {
+ t.Fatalf("connectionTypeForAlerts(%q) ok = %v, want %v", tc.input, ok, tc.wantOK)
+ }
+ if got != tc.want {
+ t.Fatalf("connectionTypeForAlerts(%q) = %q, want %q", tc.input, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestBranchcov0722SnapshotConnectionsForAlerts asserts the real behaviour
+// of the snapshot translator: empty input returns a non-nil empty slice,
+// every platform connection maps its full field set, and non-platform
+// connections are dropped while the platform siblings survive.
+func TestBranchcov0722SnapshotConnectionsForAlerts(t *testing.T) {
+ t.Run("empty_input_returns_non_nil_empty_slice", func(t *testing.T) {
+ got := snapshotConnectionsForAlerts(nil)
+ if got == nil {
+ t.Fatalf("expected non-nil slice for nil input, got nil")
+ }
+ if len(got) != 0 {
+ t.Fatalf("expected empty slice, got length %d (%+v)", len(got), got)
+ }
+
+ gotEmpty := snapshotConnectionsForAlerts([]Connection{})
+ if gotEmpty == nil {
+ t.Fatalf("expected non-nil slice for empty input, got nil")
+ }
+ if len(gotEmpty) != 0 {
+ t.Fatalf("expected empty slice, got length %d (%+v)", len(gotEmpty), gotEmpty)
+ }
+ })
+
+ t.Run("all_platform_connections_map_with_full_field_set", func(t *testing.T) {
+ lastSeen := time.Date(2026, 7, 22, 9, 30, 0, 0, time.UTC)
+ errAt := time.Date(2026, 7, 22, 9, 25, 0, 0, time.UTC)
+ conns := []Connection{
+ {
+ ID: "pve:node-1",
+ Type: ConnectionTypePVE,
+ Name: "node-1",
+ State: ConnectionStateUnauthorized,
+ StateReason: "token rejected",
+ Enabled: true,
+ LastSeen: &lastSeen,
+ LastError: &ConnectionError{
+ At: errAt,
+ Message: "401 Unauthorized",
+ Category: "auth",
+ },
+ },
+ {
+ ID: "pbs:store-1",
+ Type: ConnectionTypePBS,
+ Name: "store-1",
+ State: ConnectionStateActive,
+ },
+ }
+
+ got := snapshotConnectionsForAlerts(conns)
+ if len(got) != 2 {
+ t.Fatalf("expected 2 snapshots, got %d (%+v)", len(got), got)
+ }
+
+ // Full field mapping for the rich row (with LastError + LastSeen).
+ wantPVE := alerts.ConnectionSnapshot{
+ ID: "pve:node-1",
+ Name: "node-1",
+ Type: alerts.ConnectionTypePVE,
+ State: alerts.ConnectionStateUnauthorized,
+ StateReason: "token rejected",
+ Enabled: true,
+ LastSeen: &lastSeen,
+ LastError: &alerts.ConnectionErrorSnapshot{
+ At: errAt,
+ Message: "401 Unauthorized",
+ Category: "auth",
+ },
+ }
+ if !reflect.DeepEqual(got[0], wantPVE) {
+ t.Fatalf("pve snapshot mismatch:\n got %+v\n want %+v", got[0], wantPVE)
+ }
+ // The LastSeen pointer is copied by reference, so the snapshot must
+ // point at the same *time.Time as the source connection.
+ if got[0].LastSeen != &lastSeen {
+ t.Fatalf("LastSeen pointer was not copied by reference: got %p, want %p", got[0].LastSeen, &lastSeen)
+ }
+
+ // Sparse row with no LastSeen / no LastError: those fields stay nil.
+ wantPBS := alerts.ConnectionSnapshot{
+ ID: "pbs:store-1",
+ Name: "store-1",
+ Type: alerts.ConnectionTypePBS,
+ State: alerts.ConnectionStateActive,
+ }
+ if !reflect.DeepEqual(got[1], wantPBS) {
+ t.Fatalf("pbs snapshot mismatch:\n got %+v\n want %+v", got[1], wantPBS)
+ }
+ if got[1].LastSeen != nil {
+ t.Fatalf("pbs snapshot LastSeen must be nil, got %+v", got[1].LastSeen)
+ }
+ if got[1].LastError != nil {
+ t.Fatalf("pbs snapshot LastError must be nil, got %+v", got[1].LastError)
+ }
+ })
+
+ t.Run("non_platform_types_are_skipped_but_platform_siblings_survive", func(t *testing.T) {
+ conns := []Connection{
+ {ID: "agent:a", Type: ConnectionTypeAgent, Name: "a", State: ConnectionStateActive},
+ {ID: "pve:keep", Type: ConnectionTypePVE, Name: "keep", State: ConnectionStateStale},
+ {ID: "docker:d", Type: ConnectionTypeDocker, Name: "d", State: ConnectionStateActive},
+ {ID: "avail:x", Type: ConnectionTypeAvailability, Name: "x", State: ConnectionStateActive},
+ {ID: "k8s:k", Type: ConnectionTypeKubernetes, Name: "k", State: ConnectionStateActive},
+ {ID: "vmware:vc", Type: ConnectionTypeVMware, Name: "vc", State: ConnectionStateUnreachable},
+ {ID: "unknown:u", Type: ConnectionType("nope"), Name: "u", State: ConnectionStateActive},
+ }
+
+ got := snapshotConnectionsForAlerts(conns)
+ if len(got) != 2 {
+ t.Fatalf("expected 2 platform snapshots, got %d (%+v)", len(got), got)
+ }
+
+ ids := make(map[string]alerts.ConnectionSnapshot, len(got))
+ for _, snap := range got {
+ ids[snap.ID] = snap
+ }
+
+ // The platform survivors must be present with their type mapped.
+ pve, ok := ids["pve:keep"]
+ if !ok {
+ t.Fatalf("pve:keep must survive the skip filter; got IDs %+v", ids)
+ }
+ if pve.Type != alerts.ConnectionTypePVE {
+ t.Fatalf("pve:keep type = %q, want %q", pve.Type, alerts.ConnectionTypePVE)
+ }
+ if pve.State != alerts.ConnectionStateStale {
+ t.Fatalf("pve:keep state = %q, want %q", pve.State, alerts.ConnectionStateStale)
+ }
+
+ vmw, ok := ids["vmware:vc"]
+ if !ok {
+ t.Fatalf("vmware:vc must survive the skip filter; got IDs %+v", ids)
+ }
+ if vmw.Type != alerts.ConnectionTypeVMware {
+ t.Fatalf("vmware:vc type = %q, want %q", vmw.Type, alerts.ConnectionTypeVMware)
+ }
+
+ // Every non-platform row must be absent.
+ for _, dropped := range []string{"agent:a", "docker:d", "avail:x", "k8s:k", "unknown:u"} {
+ if _, present := ids[dropped]; present {
+ t.Fatalf("non-platform connection %q must be skipped, but appeared in snapshots %+v", dropped, got)
+ }
+ }
+ })
+}
+
+// TestBranchcov0722UniqueMatch exercises connectionHostIndex.uniqueMatch across
+// every branch: empty/whitespace raw, missing type bucket, single hit, and
+// ambiguous (more than one) hit which must collapse to "" so the caller does
+// not silently pick a random primary.
+func TestBranchcov0722UniqueMatch(t *testing.T) {
+ t.Run("empty_raw_returns_empty", func(t *testing.T) {
+ idx := buildConnectionHostIndex([]Connection{
+ {ID: "truenas:tn1", Type: ConnectionTypeTrueNAS, Address: "nas.lab.local"},
+ })
+ if got := idx.uniqueMatch(ConnectionTypeTrueNAS, ""); got != "" {
+ t.Fatalf("uniqueMatch(empty) = %q, want %q", got, "")
+ }
+ })
+
+ t.Run("whitespace_only_raw_returns_empty", func(t *testing.T) {
+ idx := buildConnectionHostIndex([]Connection{
+ {ID: "truenas:tn1", Type: ConnectionTypeTrueNAS, Address: "nas.lab.local"},
+ })
+ if got := idx.uniqueMatch(ConnectionTypeTrueNAS, " \t "); got != "" {
+ t.Fatalf("uniqueMatch(whitespace) = %q, want %q", got, "")
+ }
+ })
+
+ t.Run("type_with_no_bucket_returns_empty", func(t *testing.T) {
+ // Index only knows about TrueNAS; asking for PVE must miss the bucket.
+ idx := buildConnectionHostIndex([]Connection{
+ {ID: "truenas:tn1", Type: ConnectionTypeTrueNAS, Address: "nas.lab.local"},
+ })
+ if got := idx.uniqueMatch(ConnectionTypePVE, "nas.lab.local"); got != "" {
+ t.Fatalf("uniqueMatch(missing-bucket) = %q, want %q", got, "")
+ }
+ })
+
+ t.Run("host_with_no_entries_returns_empty", func(t *testing.T) {
+ idx := buildConnectionHostIndex([]Connection{
+ {ID: "truenas:tn1", Type: ConnectionTypeTrueNAS, Address: "nas.lab.local"},
+ })
+ if got := idx.uniqueMatch(ConnectionTypeTrueNAS, "does-not-exist.lab.local"); got != "" {
+ t.Fatalf("uniqueMatch(no-entries) = %q, want %q", got, "")
+ }
+ })
+
+ t.Run("single_match_returns_connection_id", func(t *testing.T) {
+ idx := buildConnectionHostIndex([]Connection{
+ {ID: "truenas:tn1", Type: ConnectionTypeTrueNAS, Address: "nas.lab.local"},
+ // A second TrueNAS with a different host must not pollute the match.
+ {ID: "truenas:tn2", Type: ConnectionTypeTrueNAS, Address: "other.lab.local"},
+ })
+ got := idx.uniqueMatch(ConnectionTypeTrueNAS, "nas.lab.local")
+ if got != "truenas:tn1" {
+ t.Fatalf("uniqueMatch(single) = %q, want %q", got, "truenas:tn1")
+ }
+ })
+
+ // When two connections normalise to the same host string the match is
+ // ambiguous; uniqueMatch returns "" so primaryConnectionIDForResource
+ // does not silently pick whichever ID happened to be appended last.
+ // This mirrors directProxmoxHostAttachment's "more than one → no match"
+ // contract, and is the reason the helper is named unique*Match.
+ t.Run("ambiguous_match_returns_empty", func(t *testing.T) {
+ idx := buildConnectionHostIndex([]Connection{
+ {ID: "truenas:tn1", Type: ConnectionTypeTrueNAS, Address: "nas.lab.local"},
+ {ID: "truenas:tn2", Type: ConnectionTypeTrueNAS, Name: "nas.lab.local"},
+ })
+ got := idx.uniqueMatch(ConnectionTypeTrueNAS, "nas.lab.local")
+ if got != "" {
+ t.Fatalf("uniqueMatch(ambiguous) = %q, want %q (must not silently pick one of multiple matches)", got, "")
+ }
+ })
+}
diff --git a/internal/monitoring/availability_poller_purehelpers_branchcov0722am_test.go b/internal/monitoring/availability_poller_purehelpers_branchcov0722am_test.go
new file mode 100644
index 0000000000..96df0de52c
--- /dev/null
+++ b/internal/monitoring/availability_poller_purehelpers_branchcov0722am_test.go
@@ -0,0 +1,224 @@
+package monitoring
+
+import (
+ "reflect"
+ "runtime"
+ "strconv"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// This file is a purpose-built branch-coverage test set (selected via
+// `-run "^TestBranchcov0722"`) for three pure helpers in
+// availability_poller.go that previously had 0.0% coverage:
+//
+// - availabilityConnectionKey(targetID string) string
+// - (availabilityPollProvider).ConnectionHealthKey(_ *Monitor, instanceName string) string
+// - pingArgs(host string, timeoutMillis int) []string
+//
+// Every arm of each function is exercised directly here:
+//
+// - availabilityConnectionKey: empty + whitespace-only -> "", plain id and
+// whitespace-surrounded id -> "availability-"+trimmed id, and the
+// already-prefixed input which (because there is no idempotency guard)
+// gets the prefix appended a second time.
+// - ConnectionHealthKey: pure delegation to availabilityConnectionKey with a
+// nil *Monitor (the receiver ignores the monitor entirely).
+// - pingArgs: the timeoutMillis <= 0 fallback to the config default, the
+// runtime.GOOS switch (windows / darwin+BSD / default), and the default
+// arm's ceiling arithmetic ((ms+999)/1000) plus the clamp-to-1 guard.
+//
+// Conventions match sibling in-package tests in this directory (see
+// monitoring_infra_keys_branchcov0716_test.go and the connected-infrastructure
+// branch-cov set): stdlib `testing` only, table-driven subtests, t.Fatalf
+// assertions, no testify. Each case is value-in -> value-out.
+
+func TestBranchcov0722AvailabilityConnectionKey(t *testing.T) {
+ cases := []struct {
+ name string
+ targetID string
+ want string
+ }{
+ // Arm: trimmed value is empty -> "".
+ {"empty input returns empty", "", ""},
+ {"whitespace-only input returns empty", " \t\n", ""},
+
+ // Arm: non-empty trimmed value -> "availability-" + trimmed id.
+ {"plain id is prefixed", "router-1", "availability-router-1"},
+ {"leading and trailing whitespace trimmed before prefixing", " router-1 ", "availability-router-1"},
+ {"internal whitespace preserved", "zone a / rack 2", "availability-zone a / rack 2"},
+ {"unicode id preserved", "café-设备", "availability-café-设备"},
+
+ // Behavioural note (NOT a bug fix): the function performs no
+ // idempotency check, so an id that already carries the prefix gets it
+ // appended again. This asserts the real, observed behaviour.
+ {"already-prefixed id is prefixed again", "availability-foo", "availability-availability-foo"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := availabilityConnectionKey(tc.targetID); got != tc.want {
+ t.Fatalf("availabilityConnectionKey(%q) = %q, want %q", tc.targetID, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722ConnectionHealthKey(t *testing.T) {
+ provider := availabilityPollProvider{}
+
+ cases := []struct {
+ name string
+ instanceName string
+ want string
+ }{
+ // Arm: empty / whitespace-only instance name -> "" (via the underlying
+ // availabilityConnectionKey trim+empty check). The *Monitor argument is
+ // ignored, so a nil monitor exercises the function with no receiver
+ // state dependency.
+ {"empty instance name returns empty with nil monitor", "", ""},
+ {"whitespace-only instance name returns empty with nil monitor", " ", ""},
+
+ // Arm: non-empty name -> "availability-" + trimmed name.
+ {"plain name delegated and prefixed", "sensor-7", "availability-sensor-7"},
+ {"whitespace trimmed before delegation", " sensor-7 ", "availability-sensor-7"},
+ {"already-prefixed name doubles through delegation", "availability-x", "availability-availability-x"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ // The receiver is a value type and the *Monitor parameter is
+ // discarded, so passing nil is both safe and the cleanest way to
+ // prove the method never touches monitor state.
+ if got := provider.ConnectionHealthKey(nil, tc.instanceName); got != tc.want {
+ t.Fatalf("ConnectionHealthKey(nil, %q) = %q, want %q", tc.instanceName, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722PingArgs(t *testing.T) {
+ const host = "probe.example.test"
+
+ t.Run("positive timeout reaches the platform arm verbatim", func(t *testing.T) {
+ got := pingArgs(host, 5000)
+ switch runtime.GOOS {
+ case "windows":
+ want := []string{"-n", "1", "-w", "5000", host}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("pingArgs(%q, 5000) on windows = %v, want %v", host, got, want)
+ }
+ case "darwin", "freebsd", "openbsd", "netbsd":
+ want := []string{"-n", "-c", "1", "-W", "5000", host}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("pingArgs(%q, 5000) on %s = %v, want %v", host, runtime.GOOS, got, want)
+ }
+ default:
+ // Default arm: (5000 + 999) / 1000 = 5 whole seconds.
+ want := []string{"-n", "-c", "1", "-W", "5", host}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("pingArgs(%q, 5000) on %s = %v, want %v", host, runtime.GOOS, got, want)
+ }
+ }
+ })
+
+ t.Run("zero or negative timeout falls back to config default", func(t *testing.T) {
+ defaultMillis := config.DefaultAvailabilityTimeoutMillis
+ for _, ms := range []int{0, -1, -99999} {
+ got := pingArgs(host, ms)
+ switch runtime.GOOS {
+ case "windows":
+ want := []string{"-n", "1", "-w", strconv.Itoa(defaultMillis), host}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("pingArgs(%q, %d) on windows = %v, want %v", host, ms, got, want)
+ }
+ case "darwin", "freebsd", "openbsd", "netbsd":
+ want := []string{"-n", "-c", "1", "-W", strconv.Itoa(defaultMillis), host}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("pingArgs(%q, %d) on %s = %v, want %v", host, ms, runtime.GOOS, got, want)
+ }
+ default:
+ secs := (defaultMillis + 999) / 1000
+ want := []string{"-n", "-c", "1", "-W", strconv.Itoa(secs), host}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("pingArgs(%q, %d) on %s = %v, want %v", host, ms, runtime.GOOS, got, want)
+ }
+ }
+ }
+ })
+
+}
+
+// TestBranchcov0722PingArgsDefaultArmCeilingArithmetic targets the
+// non-Windows / non-BSD ("default") arm of the runtime.GOOS switch, which is
+// the only arm that performs the (ms+999)/1000 ceiling division and the
+// clamp-to-1 guard. pingArgs reads runtime.GOOS directly, so this arm can only
+// be reached on platforms such as linux; on windows/darwin/BSD the test skips
+// honestly rather than asserting behaviour it cannot reach.
+func TestBranchcov0722PingArgsDefaultArmCeilingArithmetic(t *testing.T) {
+ switch runtime.GOOS {
+ case "windows", "darwin", "freebsd", "openbsd", "netbsd":
+ t.Skipf("ceiling arithmetic lives only in the default (linux-like) pingArgs arm; skipping on %s", runtime.GOOS)
+ }
+
+ const host = "probe.example.test"
+ cases := []struct {
+ name string
+ timeoutMs int
+ wantSeconds int
+ }{
+ // Ceiling division: any sub-second value rounds up to 1 second.
+ {"one millisecond rounds up to one second", 1, 1},
+ {"just under a second rounds up to one second", 999, 1},
+ // Exact second boundary stays put.
+ {"exact one thousand millis is one second", 1000, 1},
+ // Fractional seconds round up to the next whole second.
+ {"one thousand one millis rounds up to two seconds", 1001, 2},
+ {"fifteen hundred millis rounds up to two seconds", 1500, 2},
+ {"five thousand nine hundred ninety nine rounds up to five seconds", 5999, 5},
+ // NOTE: the `if timeoutSeconds <= 0 { timeoutSeconds = 1 }` clamp is
+ // unreachable here. The non-positive fallback guarantees timeoutMillis
+ // is at least DefaultAvailabilityTimeoutMillis (2000) before this arm,
+ // and any positive value yields (ms+999)/1000 >= 1. No table case can
+ // exercise the clamp; this is documented in the report, not "fixed".
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := pingArgs(host, tc.timeoutMs)
+ // Default arm shape: ["-n", "-c", "1", "-W", <seconds>, host].
+ want := []string{"-n", "-c", "1", "-W", strconv.Itoa(tc.wantSeconds), host}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("pingArgs(%q, %d) = %v, want %v", host, tc.timeoutMs, got, want)
+ }
+ })
+ }
+}
+
+// TestBranchcov0722PingArgsCloneIndependence asserts that the returned slice
+// is freshly allocated on every call: mutating one result must not corrupt a
+// previously returned or subsequently returned slice, and vice versa. (pingArgs
+// takes only immutable inputs — a string and an int — so the relevant
+// invariant is that distinct calls do not alias backing arrays.)
+func TestBranchcov0722PingArgsCloneIndependence(t *testing.T) {
+ first := pingArgs("alpha", 1000)
+ second := pingArgs("beta", 2000)
+
+ snapshot := append([]string(nil), first...)
+ for i := range second {
+ second[i] = "MUTATED"
+ }
+ if !reflect.DeepEqual(first, snapshot) {
+ t.Fatalf("mutating a pingArgs result corrupted a distinct result: first = %v, want %v", first, snapshot)
+ }
+
+ third := pingArgs("gamma", 3000)
+ snapshotThird := append([]string(nil), third...)
+ for i := range first {
+ first[i] = "MUTATED"
+ }
+ if !reflect.DeepEqual(third, snapshotThird) {
+ t.Fatalf("mutating an earlier pingArgs result corrupted a later result: third = %v, want %v", third, snapshotThird)
+ }
+}
diff --git a/internal/monitoring/connected_infrastructure_groupkey_branchcov0722am_test.go b/internal/monitoring/connected_infrastructure_groupkey_branchcov0722am_test.go
new file mode 100644
index 0000000000..f53692e38b
--- /dev/null
+++ b/internal/monitoring/connected_infrastructure_groupkey_branchcov0722am_test.go
@@ -0,0 +1,262 @@
+package monitoring
+
+import (
+ "testing"
+
+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// This file is a purpose-built branch-coverage test set (selected via
+// `-run "^TestBranchcov0722"`) for connectedInfrastructureGroupKey in
+// connected_infrastructure.go. The function had 0.0% coverage because the
+// production callers go through resolver.GroupIDForResource first and only
+// reach this fallback key builder for a minority of resources.
+//
+// Every arm of the function is exercised directly here:
+//
+// - the "kubernetes" surfaceKind arm (ClusterID present, whitespace-only,
+// and a nil Kubernetes block -> resource-ID fallback)
+// - the machine-ID arm via connectedInfrastructureMachineID (Agent, Docker
+// and Identity precedence, whitespace trimming)
+// - the hostname arm via connectedInfrastructureHostname (lower-casing of
+// the returned key plus the agent -> docker -> pbs -> pmg -> truenas ->
+// canonical -> Name candidate order)
+// - the Canonical PrimaryID arm (including a whitespace-only PrimaryID
+// falling through)
+// - the final "resource:" fallback when nothing else matches
+//
+// Conventions match sibling in-package tests in this directory: stdlib
+// `testing` only, table-driven subtests, no testify. Each case is value-in ->
+// value-out and builds a unifiedresources.Resource fixture inline, exactly
+// like connected_infrastructure_test.go.
+func TestBranchcov0722GroupKeyKubernetesSurface(t *testing.T) {
+ cases := []struct {
+ name string
+ resource unifiedresources.Resource
+ want string
+ }{
+ // Arm: surfaceKind == "kubernetes" AND Kubernetes != nil AND the
+ // trimmed ClusterID is non-empty -> "kubernetes:" + trimmed ClusterID.
+ {"non-empty cluster id is trimmed",
+ unifiedresources.Resource{
+ ID: "k8s-resource",
+ Kubernetes: &unifiedresources.K8sData{ClusterID: " cluster-1 "},
+ }, "kubernetes:cluster-1"},
+
+ // Arm: surfaceKind == "kubernetes" but ClusterID is whitespace-only
+ // (trimmed value empty) -> falls back to the resource-ID form.
+ {"whitespace-only cluster id falls back to resource id",
+ unifiedresources.Resource{
+ ID: "k8s-resource",
+ Kubernetes: &unifiedresources.K8sData{ClusterID: " "},
+ }, "kubernetes:k8s-resource"},
+
+ // Arm: surfaceKind == "kubernetes" but the Kubernetes block is nil
+ // -> falls back to the resource-ID form.
+ {"nil kubernetes block falls back to resource id",
+ unifiedresources.Resource{
+ ID: "k8s-resource",
+ }, "kubernetes:k8s-resource"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := connectedInfrastructureGroupKey(tc.resource, "kubernetes")
+ if got != tc.want {
+ t.Fatalf("connectedInfrastructureGroupKey(_, \"kubernetes\") = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722GroupKeyMachineIDArm(t *testing.T) {
+ cases := []struct {
+ name string
+ resource unifiedresources.Resource
+ want string
+ }{
+ // Arm: connectedInfrastructureMachineID returns a non-empty value
+ // -> "machine:" + machineID. Agent.MachineID wins and is trimmed.
+ {"agent machine id wins and is trimmed",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Agent: &unifiedresources.AgentData{MachineID: " agent-machine "},
+ }, "machine:agent-machine"},
+
+ // Precedence: Docker.MachineID when Agent is nil.
+ {"docker machine id when agent absent",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Docker: &unifiedresources.DockerData{MachineID: "docker-machine"},
+ }, "machine:docker-machine"},
+
+ // Precedence: Identity.MachineID when Agent and Docker are both nil.
+ {"identity machine id when agent and docker absent",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Identity: unifiedresources.ResourceIdentity{MachineID: "identity-machine"},
+ }, "machine:identity-machine"},
+
+ // Precedence: Agent wins over Docker AND Identity when all three set.
+ {"agent wins over docker and identity",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Agent: &unifiedresources.AgentData{MachineID: "agent-machine"},
+ Docker: &unifiedresources.DockerData{MachineID: "docker-machine"},
+ Identity: unifiedresources.ResourceIdentity{MachineID: "identity-machine"},
+ }, "machine:agent-machine"},
+
+ // Precedence: Docker wins over Identity when Agent is nil.
+ {"docker wins over identity",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Docker: &unifiedresources.DockerData{MachineID: "docker-machine"},
+ Identity: unifiedresources.ResourceIdentity{MachineID: "identity-machine"},
+ }, "machine:docker-machine"},
+
+ // Branch: Agent present but MachineID whitespace-only -> falls
+ // through to Docker (whitespace is treated as empty by the trim
+ // check) and then to Identity.
+ {"agent with whitespace-only machine id falls through to identity",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Agent: &unifiedresources.AgentData{MachineID: " "},
+ Identity: unifiedresources.ResourceIdentity{MachineID: "identity-machine"},
+ }, "machine:identity-machine"},
+
+ // NOTE: the all-empty fallthrough (machineID returns "" so the
+ // function moves to the hostname/primary/resource arms) is exercised
+ // by the hostname and fallback tests below, whose fixtures deliberately
+ // leave every MachineID unset.
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := connectedInfrastructureGroupKey(tc.resource, "agent")
+ if got != tc.want {
+ t.Fatalf("connectedInfrastructureGroupKey(_, \"agent\") = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722GroupKeyHostnameArm(t *testing.T) {
+ cases := []struct {
+ name string
+ resource unifiedresources.Resource
+ want string
+ }{
+ // Arm: connectedInfrastructureHostname returns a non-empty value
+ // -> "host:" + lower-cased hostname. Agent.Hostname is the highest
+ // precedence candidate and is lower-cased in the returned key.
+ {"agent hostname lowercased",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Agent: &unifiedresources.AgentData{Hostname: "Agent.Local"},
+ }, "host:agent.local"},
+
+ // Precedence: Docker.Hostname when Agent is absent.
+ {"docker hostname when agent absent",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Docker: &unifiedresources.DockerData{Hostname: "Docker.Local"},
+ }, "host:docker.local"},
+
+ // Precedence: Docker.DisplayName when Docker.Hostname is empty
+ // (the docker candidate helper tries Hostname then DisplayName).
+ {"docker display name when docker hostname empty",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Docker: &unifiedresources.DockerData{DisplayName: "Docker-Display"},
+ }, "host:docker-display"},
+
+ // Precedence: PBS.Hostname.
+ {"pbs hostname",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ PBS: &unifiedresources.PBSData{Hostname: "PBS.Local"},
+ }, "host:pbs.local"},
+
+ // Precedence: PMG.Hostname.
+ {"pmg hostname",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ PMG: &unifiedresources.PMGData{Hostname: "PMG.Local"},
+ }, "host:pmg.local"},
+
+ // Precedence: TrueNAS.Hostname.
+ {"truenas hostname",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ TrueNAS: &unifiedresources.TrueNASData{Hostname: "TrueNAS.Local"},
+ }, "host:truenas.local"},
+
+ // Precedence: Canonical.Hostname.
+ {"canonical hostname",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Canonical: &unifiedresources.CanonicalIdentity{Hostname: "Canonical.Local"},
+ }, "host:canonical.local"},
+
+ // Final candidate: resource.Name, trimmed and lower-cased.
+ {"resource name fallback trimmed and lowercased",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Name: " Named-Host ",
+ }, "host:named-host"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := connectedInfrastructureGroupKey(tc.resource, "agent")
+ if got != tc.want {
+ t.Fatalf("connectedInfrastructureGroupKey(_, \"agent\") = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0722GroupKeyPrimaryAndResourceFallback(t *testing.T) {
+ cases := []struct {
+ name string
+ resource unifiedresources.Resource
+ want string
+ }{
+ // Arm: Canonical != nil AND trimmed PrimaryID != "" ->
+ // "primary:" + trimmed PrimaryID. The fixture leaves every
+ // MachineID/hostname unset so the earlier arms are skipped.
+ {"canonical primary id trimmed",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Canonical: &unifiedresources.CanonicalIdentity{PrimaryID: " primary-1 "},
+ }, "primary:primary-1"},
+
+ // Arm: Canonical.PrimaryID is whitespace-only (trimmed empty) ->
+ // falls through to the resource fallback.
+ {"whitespace-only primary id falls through to resource",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ Canonical: &unifiedresources.CanonicalIdentity{PrimaryID: " "},
+ }, "resource:host-resource"},
+
+ // Arm: Canonical is nil -> falls through to the resource fallback.
+ {"nil canonical falls through to resource",
+ unifiedresources.Resource{
+ ID: "host-resource",
+ }, "resource:host-resource"},
+
+ // Final fallback: nothing matches -> "resource:" + resource.ID.
+ // A zero-value resource yields the bare "resource:" prefix.
+ {"zero resource returns bare resource prefix",
+ unifiedresources.Resource{}, "resource:"},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := connectedInfrastructureGroupKey(tc.resource, "agent")
+ if got != tc.want {
+ t.Fatalf("connectedInfrastructureGroupKey(_, \"agent\") = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/monitoring/purehelpers_branchcov0722am_test.go b/internal/monitoring/purehelpers_branchcov0722am_test.go
new file mode 100644
index 0000000000..42bf1d0d12
--- /dev/null
+++ b/internal/monitoring/purehelpers_branchcov0722am_test.go
@@ -0,0 +1,374 @@
+package monitoring
+
+import (
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ unifiedresources "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// This file is a purpose-built branch-coverage test set (selected via
+// `-run "^TestBranchcov0722"`) for three pure helpers in package monitoring
+// that previously had 0.0% coverage:
+//
+// - hostThermalStateFromReadStateView(in *unifiedresources.HostThermalState) *models.HostThermalState — monitor.go
+// - latestMetricPoint(points []MetricPoint) (MetricPoint, bool) — mock_chart_history.go
+// - MemorySourceTrust(source string) string — memory_source_catalog.go
+//
+// Every arm of each function is exercised directly here:
+//
+// - hostThermalStateFromReadStateView: the nil-input -> nil arm, the fully
+// populated mapping arm (every scalar, pointer and map field), nil nested
+// pointers -> nil, and a nil/empty LimitsPercent map -> nil (because
+// cloneStringIntMap returns nil when len(src)==0). Clone independence is
+// asserted for the three cloned *int fields and the cloned map in both
+// directions.
+// - latestMetricPoint: the empty/nil slice -> (zero, false) arm, the single
+// point arm (loop body never runs), and the multi-point arm. The function
+// selects by newest Timestamp (NOT last element), so out-of-order input
+// and exact-timestamp ties (first wins) are asserted against real
+// behaviour.
+// - MemorySourceTrust: every key in memorySourceCatalog (via direct
+// iteration so no new catalog entry can slip through untested), an
+// unknown source, the empty string, a whitespace-only string, and the
+// DescribeMemorySource lower-case+trim normalisation path.
+//
+// Conventions match sibling in-package tests in this directory (see
+// availability_poller_purehelpers_branchcov0722am_test.go,
+// connected_infrastructure_groupkey_branchcov0722am_test.go and
+// canonical_guardrails_test.go): stdlib `testing` only, table-driven subtests,
+// t.Fatalf assertions, no testify. Each case is value-in -> value-out.
+
+// thermalIntAddr is a tiny helper so fixtures can take the address of a literal
+// int without allocating a named variable each time.
+func thermalIntAddr(v int) *int { return &v }
+
+func TestBranchcov0722HostThermalStateFromReadStateView(t *testing.T) {
+ t.Run("nil input returns nil", func(t *testing.T) {
+ if got := hostThermalStateFromReadStateView(nil); got != nil {
+ t.Fatalf("hostThermalStateFromReadStateView(nil) = %+v, want nil", got)
+ }
+ })
+
+ t.Run("fully populated input maps every field", func(t *testing.T) {
+ in := &unifiedresources.HostThermalState{
+ Source: "ipmi",
+ Pressure: "critical",
+ ThermalWarningLevel: thermalIntAddr(7),
+ PerformanceWarningLevel: thermalIntAddr(4),
+ CPUPowerStatus: thermalIntAddr(2),
+ LimitsPercent: map[string]int{
+ "cpu": 85,
+ "psu": 90,
+ },
+ }
+
+ got := hostThermalStateFromReadStateView(in)
+ if got == nil {
+ t.Fatal("expected a projected HostThermalState, got nil")
+ }
+
+ // Structural equality against an explicitly constructed expected
+ // value validates that every field is mapped. reflect.DeepEqual
+ // dereferences pointers and compares maps by content, so distinct
+ // allocations with equal values compare equal here.
+ want := &models.HostThermalState{
+ Source: "ipmi",
+ Pressure: "critical",
+ ThermalWarningLevel: thermalIntAddr(7),
+ PerformanceWarningLevel: thermalIntAddr(4),
+ CPUPowerStatus: thermalIntAddr(2),
+ LimitsPercent: map[string]int{
+ "cpu": 85,
+ "psu": 90,
+ },
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("projected state = %+v, want %+v", got, want)
+ }
+
+ // Explicit pointer-value checks keep the mapping intent legible
+ // independent of the DeepEqual implementation detail above.
+ if got.ThermalWarningLevel == nil || *got.ThermalWarningLevel != 7 {
+ t.Fatalf("ThermalWarningLevel = %v, want pointer to 7", got.ThermalWarningLevel)
+ }
+ if got.PerformanceWarningLevel == nil || *got.PerformanceWarningLevel != 4 {
+ t.Fatalf("PerformanceWarningLevel = %v, want pointer to 4", got.PerformanceWarningLevel)
+ }
+ if got.CPUPowerStatus == nil || *got.CPUPowerStatus != 2 {
+ t.Fatalf("CPUPowerStatus = %v, want pointer to 2", got.CPUPowerStatus)
+ }
+ })
+
+ t.Run("nil nested pointers map to nil", func(t *testing.T) {
+ // Every pointer field nil; LimitsPercent nil. cloneIntPtr(nil)
+ // returns nil for each, so the projection must carry nil through.
+ in := &unifiedresources.HostThermalState{
+ Source: "agent",
+ Pressure: "ok",
+ ThermalWarningLevel: nil,
+ PerformanceWarningLevel: nil,
+ CPUPowerStatus: nil,
+ LimitsPercent: nil,
+ }
+ got := hostThermalStateFromReadStateView(in)
+ if got == nil {
+ t.Fatal("expected a projected HostThermalState, got nil")
+ }
+ if got.Source != "agent" || got.Pressure != "ok" {
+ t.Fatalf("scalar fields not mapped: %+v", got)
+ }
+ if got.ThermalWarningLevel != nil || got.PerformanceWarningLevel != nil || got.CPUPowerStatus != nil {
+ t.Fatalf("nil pointer fields not preserved as nil: %+v", got)
+ }
+ if got.LimitsPercent != nil {
+ t.Fatalf("nil LimitsPercent must project to nil map, got %v", got.LimitsPercent)
+ }
+ })
+
+ t.Run("empty LimitsPercent map projects to nil", func(t *testing.T) {
+ // cloneStringIntMap returns nil when len(src)==0 (it does not
+ // preserve a non-nil empty map). This asserts that real behaviour.
+ in := &unifiedresources.HostThermalState{
+ Source: "agent",
+ LimitsPercent: map[string]int{},
+ }
+ got := hostThermalStateFromReadStateView(in)
+ if got == nil {
+ t.Fatal("expected a projected HostThermalState, got nil")
+ }
+ if got.LimitsPercent != nil {
+ t.Fatalf("empty LimitsPercent must project to nil (cloneStringIntMap len==0 arm), got %v", got.LimitsPercent)
+ }
+ })
+}
+
+// TestBranchcov0722HostThermalStateCloneIndependence asserts that mutating the
+// returned pointer fields and map never affects the input, and vice versa.
+// This is exactly the guarantee cloneIntPtr / cloneStringIntMap provide; the
+// test pins it at the public-mapper boundary so a future refactor that drops
+// the clone is caught.
+func TestBranchcov0722HostThermalStateCloneIndependence(t *testing.T) {
+ t.Run("mutating returned pointers does not affect input", func(t *testing.T) {
+ in := &unifiedresources.HostThermalState{
+ ThermalWarningLevel: thermalIntAddr(10),
+ PerformanceWarningLevel: thermalIntAddr(20),
+ CPUPowerStatus: thermalIntAddr(30),
+ }
+ out := hostThermalStateFromReadStateView(in)
+
+ *out.ThermalWarningLevel = 9999
+ *out.PerformanceWarningLevel = 9999
+ *out.CPUPowerStatus = 9999
+
+ if *in.ThermalWarningLevel != 10 || *in.PerformanceWarningLevel != 20 || *in.CPUPowerStatus != 30 {
+ t.Fatalf("mutating returned pointer fields corrupted the input: tw=%d pw=%d cpu=%d",
+ *in.ThermalWarningLevel, *in.PerformanceWarningLevel, *in.CPUPowerStatus)
+ }
+ })
+
+ t.Run("mutating input pointers does not affect returned", func(t *testing.T) {
+ in := &unifiedresources.HostThermalState{
+ ThermalWarningLevel: thermalIntAddr(10),
+ PerformanceWarningLevel: thermalIntAddr(20),
+ CPUPowerStatus: thermalIntAddr(30),
+ }
+ out := hostThermalStateFromReadStateView(in)
+
+ *in.ThermalWarningLevel = 9999
+ *in.PerformanceWarningLevel = 9999
+ *in.CPUPowerStatus = 9999
+
+ if *out.ThermalWarningLevel != 10 || *out.PerformanceWarningLevel != 20 || *out.CPUPowerStatus != 30 {
+ t.Fatalf("mutating input pointer fields corrupted the returned projection: tw=%d pw=%d cpu=%d",
+ *out.ThermalWarningLevel, *out.PerformanceWarningLevel, *out.CPUPowerStatus)
+ }
+ })
+
+ t.Run("mutating returned map does not affect input", func(t *testing.T) {
+ in := &unifiedresources.HostThermalState{
+ LimitsPercent: map[string]int{"cpu": 80, "psu": 90},
+ }
+ out := hostThermalStateFromReadStateView(in)
+
+ delete(out.LimitsPercent, "cpu")
+ out.LimitsPercent["psu"] = 1
+ out.LimitsPercent["new"] = 2
+
+ if len(in.LimitsPercent) != 2 || in.LimitsPercent["cpu"] != 80 || in.LimitsPercent["psu"] != 90 {
+ t.Fatalf("mutating returned LimitsPercent corrupted the input: %v", in.LimitsPercent)
+ }
+ })
+
+ t.Run("mutating input map does not affect returned", func(t *testing.T) {
+ in := &unifiedresources.HostThermalState{
+ LimitsPercent: map[string]int{"cpu": 80, "psu": 90},
+ }
+ out := hostThermalStateFromReadStateView(in)
+
+ delete(in.LimitsPercent, "cpu")
+ in.LimitsPercent["psu"] = 1
+ in.LimitsPercent["new"] = 2
+
+ if len(out.LimitsPercent) != 2 || out.LimitsPercent["cpu"] != 80 || out.LimitsPercent["psu"] != 90 {
+ t.Fatalf("mutating input LimitsPercent corrupted the returned projection: %v", out.LimitsPercent)
+ }
+ })
+}
+
+func TestBranchcov0722LatestMetricPoint(t *testing.T) {
+ base := time.Date(2026, 7, 22, 9, 0, 0, 0, time.UTC)
+
+ t.Run("nil slice returns zero value and false", func(t *testing.T) {
+ got, ok := latestMetricPoint(nil)
+ if ok {
+ t.Fatal("expected ok=false for nil slice")
+ }
+ if !reflect.DeepEqual(got, MetricPoint{}) {
+ t.Fatalf("nil slice point = %+v, want zero MetricPoint", got)
+ }
+ })
+
+ t.Run("empty slice returns zero value and false", func(t *testing.T) {
+ got, ok := latestMetricPoint([]MetricPoint{})
+ if ok {
+ t.Fatal("expected ok=false for empty slice")
+ }
+ if !reflect.DeepEqual(got, MetricPoint{}) {
+ t.Fatalf("empty slice point = %+v, want zero MetricPoint", got)
+ }
+ })
+
+ t.Run("single point returns it and true", func(t *testing.T) {
+ // Single point: the for-loop body (i:=1; i<len) never executes, so
+ // the seed value is returned verbatim.
+ want := MetricPoint{Value: 42.5, Timestamp: base}
+ got, ok := latestMetricPoint([]MetricPoint{want})
+ if !ok {
+ t.Fatal("expected ok=true for single point")
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("single point = %+v, want %+v", got, want)
+ }
+ })
+
+ t.Run("multiple in-order points return the newest", func(t *testing.T) {
+ // Timestamps strictly increasing; the last element is also the newest.
+ points := []MetricPoint{
+ {Value: 1, Timestamp: base},
+ {Value: 2, Timestamp: base.Add(time.Minute)},
+ {Value: 3, Timestamp: base.Add(2 * time.Minute)},
+ }
+ got, ok := latestMetricPoint(points)
+ if !ok {
+ t.Fatal("expected ok=true for multiple points")
+ }
+ if got.Value != 3 || !got.Timestamp.Equal(base.Add(2*time.Minute)) {
+ t.Fatalf("latest point = %+v, want value 3 at %+v", got, base.Add(2*time.Minute))
+ }
+ })
+
+ t.Run("out-of-order points still select newest by timestamp not position", func(t *testing.T) {
+ // Newest timestamp sits in the middle; a naive "last element" reader
+ // would fail this. The function compares Timestamp.After, so the
+ // middle point must win.
+ newest := MetricPoint{Value: 99, Timestamp: base.Add(time.Hour)}
+ points := []MetricPoint{
+ {Value: 1, Timestamp: base},
+ newest,
+ {Value: 2, Timestamp: base.Add(time.Minute)},
+ }
+ got, ok := latestMetricPoint(points)
+ if !ok {
+ t.Fatal("expected ok=true for out-of-order points")
+ }
+ if !reflect.DeepEqual(got, newest) {
+ t.Fatalf("out-of-order latest = %+v, want %+v", got, newest)
+ }
+ })
+
+ t.Run("equal timestamps keep the first encountered", func(t *testing.T) {
+ // points[i].Timestamp.After(latest.Timestamp) is strict: an equal
+ // timestamp does not replace the seed, so the earliest equal point
+ // wins. Asserts real behaviour.
+ ts := base.Add(time.Minute)
+ first := MetricPoint{Value: 1, Timestamp: ts}
+ points := []MetricPoint{
+ first,
+ {Value: 2, Timestamp: ts},
+ {Value: 3, Timestamp: ts},
+ }
+ got, ok := latestMetricPoint(points)
+ if !ok {
+ t.Fatal("expected ok=true for equal-timestamp points")
+ }
+ if !reflect.DeepEqual(got, first) {
+ t.Fatalf("equal-timestamp latest = %+v, want first %+v", got, first)
+ }
+ })
+}
+
+func TestBranchcov0722MemorySourceTrust(t *testing.T) {
+ t.Run("every catalog entry returns its declared trust", func(t *testing.T) {
+ // Iterate the package-level catalog directly so no recognised
+ // source can ever slip through untested. A minimum count guards
+ // against an accidentally emptied catalog making the loop vacuous.
+ if len(memorySourceCatalog) < 10 {
+ t.Fatalf("memorySourceCatalog unexpectedly small: %d entries", len(memorySourceCatalog))
+ }
+ for source, desc := range memorySourceCatalog {
+ source, desc := source, desc
+ t.Run(source, func(t *testing.T) {
+ if got := MemorySourceTrust(source); got != desc.Trust {
+ t.Fatalf("MemorySourceTrust(%q) = %q, want %q", source, got, desc.Trust)
+ }
+ })
+ }
+ })
+
+ cases := []struct {
+ name string
+ source string
+ want string
+ }{
+ // Arm: recognised "preferred" trust sources.
+ {"available-field is preferred", "available-field", "preferred"},
+ {"meminfo-available alias is preferred", "meminfo-available", "preferred"},
+ // Arm: recognised "derived" trust sources.
+ {"derived-free-buffers-cached is derived", "derived-free-buffers-cached", "derived"},
+ {"calculated alias is derived", "calculated", "derived"},
+ // Arm: recognised "fallback" trust sources.
+ {"unknown catalog key is fallback", "unknown", "fallback"},
+ {"agent is fallback", "agent", "fallback"},
+ {"powered-off is fallback", "powered-off", "fallback"},
+
+ // Arm: unknown source (not in catalog) -> DescribeMemorySource
+ // returns Trust:"fallback" with Fallback:false.
+ {"unrecognized source falls back", "not-a-real-source", "fallback"},
+
+ // Arm: empty string is a real catalog key ("") -> "fallback".
+ {"empty string is fallback", "", "fallback"},
+
+ // Arm: whitespace-only string trims to "" which is a catalog key
+ // -> "fallback".
+ {"whitespace-only string is fallback", " \t\n", "fallback"},
+
+ // Arm: DescribeMemorySource lower-cases + trims before lookup, so
+ // a mixed-case, whitespace-padded recognised source must still
+ // resolve to its catalog trust. MemorySourceTrust inherits that
+ // normalisation.
+ {"mixed case with surrounding whitespace normalises to preferred", " AvailAbLe-FiElD ", "preferred"},
+ {"uppercase derived alias normalises to derived", "CALCULATED", "derived"},
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ if got := MemorySourceTrust(tc.source); got != tc.want {
+ t.Fatalf("MemorySourceTrust(%q) = %q, want %q", tc.source, got, tc.want)
+ }
+ })
+ }
+}