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 control plane status helpers, patrol assertions and setup classifiers

rcourtmancba394e56b9e
diff --git a/cmd/pulse-control-plane/provider_msp_status_branchcov0723am_test.go b/cmd/pulse-control-plane/provider_msp_status_branchcov0723am_test.go
new file mode 100644
index 0000000000..842783fa6e
--- /dev/null
+++ b/cmd/pulse-control-plane/provider_msp_status_branchcov0723am_test.go
@@ -0,0 +1,350 @@
+package main
+
+import (
+ "bytes"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp"
+ cpDocker "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/docker"
+ "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
+)
+
+// TestBranchcov0723AmContainsProviderMSPStatusFailure exercises every branch
+// of containsProviderMSPStatusFailure. The source compares with == (exact,
+// case-sensitive equality), NOT strings.Contains; the cases below pin that.
+func TestBranchcov0723AmContainsProviderMSPStatusFailure(t *testing.T) {
+ cases := []struct {
+ name string
+ failures []string
+ want string
+ expected bool
+ }{
+ {"nil slice", nil, "anything", false},
+ {"empty slice", []string{}, "anything", false},
+ {"exact match first element", []string{"preflight: bad", "other"}, "preflight: bad", true},
+ {"exact match last element", []string{"other", "preflight: bad"}, "preflight: bad", true},
+ {"no match", []string{"a", "b", "c"}, "d", false},
+ {"case sensitive equality no match", []string{"Failure"}, "failure", false},
+ {"substring of an entry does not match", []string{"preflight: bad"}, "bad", false},
+ {"entry is substring of want does not match", []string{"bad"}, "preflight: bad", false},
+ {"whole entry exact match", []string{"preflight: bad"}, "preflight: bad", true},
+ {"empty want empty entry matches", []string{"a", ""}, "", true},
+ {"empty want no empty entry", []string{"a", "b"}, "", false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := containsProviderMSPStatusFailure(tc.failures, tc.want)
+ if got != tc.expected {
+ t.Fatalf("containsProviderMSPStatusFailure(%#v, %q) = %v, want %v", tc.failures, tc.want, got, tc.expected)
+ }
+ })
+ }
+}
+
+// TestBranchcov0723AmSortedProviderMSPStatusStates pins the real semantics:
+// states come from map keys, sorted ascending by state NAME (string value),
+// not by count. Zero-count entries appear because they are keys.
+func TestBranchcov0723AmSortedProviderMSPStatusStates(t *testing.T) {
+ t.Run("nil map returns empty slice", func(t *testing.T) {
+ got := sortedProviderMSPStatusStates(nil)
+ if len(got) != 0 {
+ t.Fatalf("nil map -> %v, want empty", got)
+ }
+ })
+ t.Run("empty map returns empty slice", func(t *testing.T) {
+ got := sortedProviderMSPStatusStates(map[registry.TenantState]int{})
+ if len(got) != 0 {
+ t.Fatalf("empty map -> %v, want empty", got)
+ }
+ })
+ t.Run("single entry", func(t *testing.T) {
+ got := sortedProviderMSPStatusStates(map[registry.TenantState]int{registry.TenantStateActive: 7})
+ if len(got) != 1 || got[0] != registry.TenantStateActive {
+ t.Fatalf("single entry -> %v, want [active]", got)
+ }
+ })
+ t.Run("ordering is by state name not count", func(t *testing.T) {
+ // Counts are deliberately out of alphabetical order to prove the
+ // sort key is the state name, not the count.
+ counts := map[registry.TenantState]int{
+ registry.TenantStateFailed: 9,
+ registry.TenantStateActive: 5,
+ registry.TenantStateProvisioning: 1,
+ registry.TenantStateDeleted: 3,
+ }
+ got := sortedProviderMSPStatusStates(counts)
+ want := []registry.TenantState{
+ registry.TenantStateActive,
+ registry.TenantStateDeleted,
+ registry.TenantStateFailed,
+ registry.TenantStateProvisioning,
+ }
+ if len(got) != len(want) {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("index %d got %v, want ordering %v", i, got, want)
+ }
+ }
+ })
+ t.Run("zero count entry is still listed", func(t *testing.T) {
+ got := sortedProviderMSPStatusStates(map[registry.TenantState]int{registry.TenantStateActive: 0})
+ if len(got) != 1 || got[0] != registry.TenantStateActive {
+ t.Fatalf("zero-count entry -> %v, want [active]", got)
+ }
+ })
+ t.Run("output is deterministic across random map iteration", func(t *testing.T) {
+ // Go map iteration order is randomised; the sort must make output
+ // stable. Run many times and assert identical result every time.
+ counts := map[registry.TenantState]int{
+ registry.TenantStateActive: 2,
+ registry.TenantStateFailed: 2,
+ registry.TenantStateProvisioning: 2,
+ registry.TenantStateSuspended: 2,
+ registry.TenantStateCanceled: 2,
+ registry.TenantStateDeleting: 2,
+ registry.TenantStateDeleted: 2,
+ }
+ first := sortedProviderMSPStatusStates(counts)
+ firstKey := statesKey(first)
+ for i := 0; i < 100; i++ {
+ got := sortedProviderMSPStatusStates(counts)
+ if k := statesKey(got); k != firstKey {
+ t.Fatalf("iteration %d produced %v, want deterministic %v", i, got, first)
+ }
+ }
+ })
+}
+
+func statesKey(states []registry.TenantState) string {
+ parts := make([]string, len(states))
+ for i, s := range states {
+ parts[i] = string(s)
+ }
+ return strings.Join(parts, ",")
+}
+
+// TestBranchcov0723AmProviderMSPRestoreDefaultDataDir covers the env-driven
+// default data dir resolver (a pure, filesystem-free helper).
+func TestBranchcov0723AmProviderMSPRestoreDefaultDataDir(t *testing.T) {
+ t.Run("env unset returns default", func(t *testing.T) {
+ t.Setenv("CP_DATA_DIR", "")
+ if got := providerMSPRestoreDefaultDataDir(); got != "/data" {
+ t.Fatalf("env unset -> %q, want /data", got)
+ }
+ })
+ t.Run("env whitespace only returns default", func(t *testing.T) {
+ t.Setenv("CP_DATA_DIR", " \t\n")
+ if got := providerMSPRestoreDefaultDataDir(); got != "/data" {
+ t.Fatalf("whitespace env -> %q, want /data", got)
+ }
+ })
+ t.Run("env value is trimmed", func(t *testing.T) {
+ t.Setenv("CP_DATA_DIR", " /var/pulse ")
+ if got := providerMSPRestoreDefaultDataDir(); got != "/var/pulse" {
+ t.Fatalf("trimmed env -> %q, want /var/pulse", got)
+ }
+ })
+}
+
+// TestBranchcov0723AmDefaultProviderMSPInstallProofRestoreTargetDataDir covers
+// the cfg/env precedence: cfg.DataDir wins when set, else env-derived base,
+// joined with the install-proof restore drill suffix.
+func TestBranchcov0723AmDefaultProviderMSPInstallProofRestoreTargetDataDir(t *testing.T) {
+ t.Run("nil cfg uses env base", func(t *testing.T) {
+ t.Setenv("CP_DATA_DIR", "")
+ got := defaultProviderMSPInstallProofRestoreTargetDataDir(nil)
+ if want := filepath.Join("/data", "install-proof-restore-drill"); got != want {
+ t.Fatalf("nil cfg -> %q, want %q", got, want)
+ }
+ })
+ t.Run("nil cfg honours env override", func(t *testing.T) {
+ t.Setenv("CP_DATA_DIR", "/custom")
+ got := defaultProviderMSPInstallProofRestoreTargetDataDir(nil)
+ if want := filepath.Join("/custom", "install-proof-restore-drill"); got != want {
+ t.Fatalf("nil cfg env -> %q, want %q", got, want)
+ }
+ })
+ t.Run("cfg DataDir overrides env", func(t *testing.T) {
+ t.Setenv("CP_DATA_DIR", "/from-env")
+ cfg := &cloudcp.CPConfig{DataDir: "/from-cfg"}
+ got := defaultProviderMSPInstallProofRestoreTargetDataDir(cfg)
+ if want := filepath.Join("/from-cfg", "install-proof-restore-drill"); got != want {
+ t.Fatalf("cfg override -> %q, want %q", got, want)
+ }
+ })
+ t.Run("cfg DataDir whitespace only falls back to env", func(t *testing.T) {
+ t.Setenv("CP_DATA_DIR", "/from-env")
+ cfg := &cloudcp.CPConfig{DataDir: " "}
+ got := defaultProviderMSPInstallProofRestoreTargetDataDir(cfg)
+ if want := filepath.Join("/from-env", "install-proof-restore-drill"); got != want {
+ t.Fatalf("whitespace cfg -> %q, want %q", got, want)
+ }
+ })
+ t.Run("cfg DataDir is trimmed", func(t *testing.T) {
+ t.Setenv("CP_DATA_DIR", "")
+ cfg := &cloudcp.CPConfig{DataDir: " /trimmed "}
+ got := defaultProviderMSPInstallProofRestoreTargetDataDir(cfg)
+ if want := filepath.Join("/trimmed", "install-proof-restore-drill"); got != want {
+ t.Fatalf("trimmed cfg -> %q, want %q", got, want)
+ }
+ })
+}
+
+// TestBranchcov0723AmPrintProviderMSPStatusReport covers the package's stdout
+// print helper for the status report. The package already has a convention for
+// capturing os.Stdout (captureStdoutForProviderMSPRecoverTest), which we reuse.
+func TestBranchcov0723AmPrintProviderMSPStatusReport(t *testing.T) {
+ t.Run("nil report prints ok=false", func(t *testing.T) {
+ var buf bytes.Buffer
+ restore := captureStdoutForProviderMSPRecoverTest(t, &buf)
+ printProviderMSPStatusReport(nil)
+ restore()
+ out := buf.String()
+ if !strings.Contains(out, "provider_msp_status_ok=false") {
+ t.Fatalf("nil report output missing ok=false:\n%s", out)
+ }
+ if strings.Contains(out, "provider_msp_status_ok=true") {
+ t.Fatalf("nil report should not print ok=true:\n%s", out)
+ }
+ })
+ t.Run("populated report prints all sections in expected order", func(t *testing.T) {
+ ts := time.Date(2026, 6, 2, 12, 0, 0, 0, time.UTC)
+ report := &providerMSPStatusReport{
+ OK: true,
+ Environment: "production",
+ ControlMode: "provider_hosted_msp",
+ BaseURL: "https://msp.example.com",
+ PlanVersion: "msp_growth",
+ PlanSource: "license-file",
+ LicenseID: "lic_test",
+ LicenseEmail: "[email protected]",
+ WorkspaceLimit: 15,
+ RegistryReady: true,
+ TotalTenants: 4,
+ HealthyTenants: 2,
+ UnhealthyTenants: 1,
+ FailedTenants: 1,
+ ProvisioningTenants: 1,
+ StuckProvisioningTimeout: 30 * time.Minute,
+ StuckProvisioningTenants: []string{"t-STUCK-1", "t-STUCK-2"},
+ CountsByState: map[registry.TenantState]int{
+ registry.TenantStateActive: 2,
+ registry.TenantStateFailed: 1,
+ registry.TenantStateProvisioning: 1,
+ },
+ Preflight: &providerMSPPreflightReport{
+ Docker: &cpDocker.RuntimePrerequisiteReport{
+ DockerReachable: true,
+ NetworkOK: true,
+ ImageRef: "pulse:test",
+ ImageAvailable: true,
+ ImagePulled: true,
+ },
+ Storage: &cloudcp.StorageGuardrailReport{
+ Enabled: true,
+ OK: true,
+ },
+ },
+ Backup: &providerMSPBackupStatus{
+ Directory: "/data/backups/provider-msp",
+ LatestPath: "/data/backups/provider-msp/latest.tar.gz",
+ LatestCreatedAt: ts,
+ LatestModifiedAt: ts,
+ LatestBytes: 4096,
+ Verified: true,
+ LicenseIncluded: true,
+ RegistryTenantCount: 2,
+ RuntimeTenantCount: 2,
+ },
+ BackupReadyForUpgrade: true,
+ Warnings: []string{"disk usage high"},
+ Failures: []string{"failed workspaces: 1"},
+ }
+ var buf bytes.Buffer
+ restore := captureStdoutForProviderMSPRecoverTest(t, &buf)
+ printProviderMSPStatusReport(report)
+ restore()
+ out := buf.String()
+ wants := []string{
+ "provider_msp_status_ok=true",
+ "environment=production",
+ "control_plane_mode=provider_hosted_msp",
+ "base_url=https://msp.example.com",
+ "plan_version=msp_growth",
+ "plan_source=license-file",
+ "license_id=lic_test",
+ "workspace_limit=15",
+ "registry_ready=true",
+ "total_tenants=4",
+ "healthy_tenants=2",
+ "unhealthy_tenants=1",
+ "failed_tenants=1",
+ "provisioning_tenants=1",
+ "stuck_provisioning_count=2",
+ "stuck_provisioning_tenant=t-STUCK-1",
+ "stuck_provisioning_tenant=t-STUCK-2",
+ // Sorted states (alphabetical by name): active, failed, provisioning.
+ "tenant_state=active count=2",
+ "tenant_state=failed count=1",
+ "tenant_state=provisioning count=1",
+ "docker_reachable=true",
+ "docker_network_ok=true",
+ "tenant_runtime_image=pulse:test",
+ "tenant_runtime_image_available=true",
+ "tenant_runtime_image_pulled=true",
+ "storage_guardrails_enabled=true",
+ "storage_guardrails_ok=true",
+ "backup_ready_for_upgrade=true",
+ "backup_directory=/data/backups/provider-msp",
+ "latest_backup_path=/data/backups/provider-msp/latest.tar.gz",
+ "latest_backup_created_at=",
+ "latest_backup_modified_at=",
+ "latest_backup_bytes=4096",
+ "latest_backup_verified=true",
+ "latest_backup_license_included=true",
+ "latest_backup_registry_tenants=2",
+ "latest_backup_runtime_tenants=2",
+ "warning=disk usage high",
+ "failure=failed workspaces: 1",
+ }
+ for _, w := range wants {
+ if !strings.Contains(out, w) {
+ t.Fatalf("output missing %q:\n%s", w, out)
+ }
+ }
+ // Assert the alphabetical ordering of states in the printed output.
+ activeIdx := strings.Index(out, "tenant_state=active")
+ failedIdx := strings.Index(out, "tenant_state=failed")
+ provisioningIdx := strings.Index(out, "tenant_state=provisioning")
+ if !(activeIdx < failedIdx && failedIdx < provisioningIdx) {
+ t.Fatalf("states not in alphabetical order: active=%d failed=%d provisioning=%d\n%s", activeIdx, failedIdx, provisioningIdx, out)
+ }
+ })
+ t.Run("report without preflight or backup omits those sections", func(t *testing.T) {
+ report := &providerMSPStatusReport{OK: false}
+ var buf bytes.Buffer
+ restore := captureStdoutForProviderMSPRecoverTest(t, &buf)
+ printProviderMSPStatusReport(report)
+ restore()
+ out := buf.String()
+ if !strings.Contains(out, "provider_msp_status_ok=false") {
+ t.Fatalf("missing ok=false:\n%s", out)
+ }
+ for _, absent := range []string{
+ "docker_reachable=",
+ "storage_guardrails_enabled=",
+ "backup_directory=",
+ "latest_backup_path=",
+ } {
+ if strings.Contains(out, absent) {
+ t.Fatalf("optional section %q should be absent:\n%s", absent, out)
+ }
+ }
+ })
+}
diff --git a/internal/ai/eval/patrol_assertions_branchcov0723am_test.go b/internal/ai/eval/patrol_assertions_branchcov0723am_test.go
new file mode 100644
index 0000000000..bb35664dd8
--- /dev/null
+++ b/internal/ai/eval/patrol_assertions_branchcov0723am_test.go
@@ -0,0 +1,235 @@
+package eval
+
+import (
+ "os"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+// TestBranchcov0723Am_PatrolAssertSignalCoverage exercises every branch of the
+// assertion closure returned by PatrolAssertSignalCoverage. Each subtest builds
+// its own PatrolRunResult so none depends on state mutated by another.
+func TestBranchcov0723Am_PatrolAssertSignalCoverage(t *testing.T) {
+ tests := []struct {
+ name string
+ minRate float64
+ result *PatrolRunResult
+ wantPassed bool
+ wantMsg string
+ }{
+ {
+ name: "nil result fails with no result available",
+ minRate: 0.5,
+ result: nil,
+ wantPassed: false,
+ wantMsg: "No result available",
+ },
+ {
+ name: "quality nil and no tool calls yields not measured",
+ minRate: 0.5,
+ result: &PatrolRunResult{
+ // Quality left nil so the assertion invokes EvaluatePatrolQuality,
+ // which returns CoverageKnown=false when no tool calls were captured.
+ ToolCalls: nil,
+ },
+ wantPassed: true,
+ wantMsg: "Signal coverage not measured (no tool calls captured)",
+ },
+ {
+ name: "coverage known false passes with not measured",
+ minRate: 0.5,
+ result: &PatrolRunResult{
+ Quality: &PatrolQualityReport{CoverageKnown: false},
+ },
+ wantPassed: true,
+ wantMsg: "Signal coverage not measured (no tool calls captured)",
+ },
+ {
+ name: "zero signals passes with no deterministic signals",
+ minRate: 0.5,
+ result: &PatrolRunResult{
+ Quality: &PatrolQualityReport{
+ CoverageKnown: true,
+ SignalsTotal: 0,
+ },
+ },
+ wantPassed: true,
+ wantMsg: "No deterministic signals detected",
+ },
+ {
+ name: "coverage above min passes",
+ minRate: 0.5,
+ result: &PatrolRunResult{
+ Quality: &PatrolQualityReport{
+ CoverageKnown: true,
+ SignalsTotal: 4,
+ SignalsMatched: 3,
+ SignalCoverage: 0.75,
+ },
+ },
+ wantPassed: true,
+ wantMsg: "Signal coverage 75% (3/4), min 50%",
+ },
+ {
+ // The comparison operator is >=, so coverage equal to min passes.
+ name: "coverage exactly at min passes via >= operator",
+ minRate: 0.5,
+ result: &PatrolRunResult{
+ Quality: &PatrolQualityReport{
+ CoverageKnown: true,
+ SignalsTotal: 4,
+ SignalsMatched: 2,
+ SignalCoverage: 0.5,
+ },
+ },
+ wantPassed: true,
+ wantMsg: "Signal coverage 50% (2/4), min 50%",
+ },
+ {
+ name: "coverage below min fails with below message",
+ minRate: 0.5,
+ result: &PatrolRunResult{
+ Quality: &PatrolQualityReport{
+ CoverageKnown: true,
+ SignalsTotal: 5,
+ SignalsMatched: 2,
+ SignalCoverage: 0.4,
+ },
+ },
+ wantPassed: false,
+ wantMsg: "Signal coverage 40% (2/5) below min 50%",
+ },
+ {
+ // minRate=0: any non-negative coverage satisfies >=, including 0%
+ // with SignalsTotal>0 (skips the SignalsTotal==0 early-return).
+ name: "minRate zero passes zero coverage with signals present",
+ minRate: 0,
+ result: &PatrolRunResult{
+ Quality: &PatrolQualityReport{
+ CoverageKnown: true,
+ SignalsTotal: 4,
+ SignalsMatched: 0,
+ SignalCoverage: 0,
+ },
+ },
+ wantPassed: true,
+ wantMsg: "Signal coverage 0% (0/4), min 0%",
+ },
+ {
+ name: "minRate one fails when coverage below one",
+ minRate: 1,
+ result: &PatrolRunResult{
+ Quality: &PatrolQualityReport{
+ CoverageKnown: true,
+ SignalsTotal: 2,
+ SignalsMatched: 1,
+ SignalCoverage: 0.5,
+ },
+ },
+ wantPassed: false,
+ wantMsg: "Signal coverage 50% (1/2) below min 100%",
+ },
+ {
+ name: "minRate one passes when coverage is full",
+ minRate: 1,
+ result: &PatrolRunResult{
+ Quality: &PatrolQualityReport{
+ CoverageKnown: true,
+ SignalsTotal: 2,
+ SignalsMatched: 2,
+ SignalCoverage: 1.0,
+ },
+ },
+ wantPassed: true,
+ wantMsg: "Signal coverage 100% (2/2), min 100%",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ assertion := PatrolAssertSignalCoverage(tc.minRate)
+ got := assertion(tc.result)
+ assert.Equal(t, tc.wantPassed, got.Passed, "Message: %s", got.Message)
+ assert.Equal(t, "signal_coverage", got.Name)
+ assert.Equal(t, tc.wantMsg, got.Message)
+ })
+ }
+}
+
+// TestBranchcov0723Am_ApprovalWriteCommand covers every branch of the pure
+// approvalWriteCommand helper, including the zero-value evalTargets.
+func TestBranchcov0723Am_ApprovalWriteCommand(t *testing.T) {
+ tests := []struct {
+ name string
+ t evalTargets
+ want string
+ }{
+ {
+ name: "zero value evalTargets yields default touch command",
+ t: evalTargets{},
+ want: "touch /tmp/pulse_eval_approval",
+ },
+ {
+ name: "literal true yields default touch command",
+ t: evalTargets{WriteCommand: "true"},
+ want: "touch /tmp/pulse_eval_approval",
+ },
+ {
+ name: "whitespace padded true trims to true and yields default",
+ t: evalTargets{WriteCommand: " true "},
+ want: "touch /tmp/pulse_eval_approval",
+ },
+ {
+ name: "whitespace only trims to empty and yields default",
+ t: evalTargets{WriteCommand: " "},
+ want: "touch /tmp/pulse_eval_approval",
+ },
+ {
+ name: "custom command returned unchanged when already trimmed",
+ t: evalTargets{WriteCommand: "echo hello"},
+ want: "echo hello",
+ },
+ {
+ name: "custom command returned trimmed",
+ t: evalTargets{WriteCommand: " echo hello "},
+ want: "echo hello",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := approvalWriteCommand(tc.t)
+ assert.Equal(t, tc.want, got)
+ })
+ }
+}
+
+// TestBranchcov0723Am_PatrolSignalCoverageMin covers the two arms of the pure
+// env-driven patrolSignalCoverageMin helper.
+func TestBranchcov0723Am_PatrolSignalCoverageMin(t *testing.T) {
+ t.Run("default when env unset", func(t *testing.T) {
+ ensureEnvUnset(t, "EVAL_PATROL_SIGNAL_COVERAGE_MIN")
+ assert.InDelta(t, 0.75, patrolSignalCoverageMin(), 1e-9)
+ })
+
+ t.Run("env value is returned when set", func(t *testing.T) {
+ t.Setenv("EVAL_PATROL_SIGNAL_COVERAGE_MIN", "0.9")
+ assert.InDelta(t, 0.9, patrolSignalCoverageMin(), 1e-9)
+ })
+}
+
+// ensureEnvUnset removes the env var for the duration of the test and restores
+// the prior value (if any) on cleanup.
+func ensureEnvUnset(t *testing.T, key string) {
+ t.Helper()
+ prev, hadPrev := os.LookupEnv(key)
+ if err := os.Unsetenv(key); err != nil {
+ t.Fatalf("unset %s: %v", key, err)
+ }
+ t.Cleanup(func() {
+ if hadPrev {
+ _ = os.Setenv(key, prev)
+ }
+ })
+}
diff --git a/internal/api/setup_and_adapters_branchcov0723am_test.go b/internal/api/setup_and_adapters_branchcov0723am_test.go
new file mode 100644
index 0000000000..d7997d6f8c
--- /dev/null
+++ b/internal/api/setup_and_adapters_branchcov0723am_test.go
@@ -0,0 +1,202 @@
+package api
+
+import (
+ "errors"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// This file raises branch/function coverage for a handful of pure (or
+// pure-over-argument) targets across setup_script_render.go,
+// router_routes_ai_relay.go, hosted_entitlement_refresh.go and
+// report_schedules.go. Each subtest drives concrete inputs and asserts the
+// concrete output value/error. No live stores, network or filesystem are
+// touched: the adapter methods under test ignore their receivers entirely.
+
+func TestBranchcov0723AmDeriveSetupScriptServerName(t *testing.T) {
+ cases := []struct {
+ name string
+ serverHost string
+ want string
+ }{
+ // Empty / whitespace inputs collapse to the documented fallback.
+ {"empty_string", "", "your-server"},
+ {"whitespace_only_trimmed_to_empty", " \t\n ", "your-server"},
+ // No scheme: the final return splits the host on ":" and keeps the name.
+ {"plain_host_no_port", "pve1.local", "pve1.local"},
+ {"plain_host_with_port_strips_port", "pve1.local:8006", "pve1.local"},
+ // Scheme present: the name is derived from the post-"://" segment.
+ {"scheme_host_no_port", "https://pve1.local", "pve1.local"},
+ {"scheme_host_with_port_strips_port", "https://pve1.local:8006", "pve1.local"},
+ // Trimming is applied BEFORE scheme detection, so surrounding whitespace
+ // does not defeat the "://" branch.
+ {"whitespace_trimmed_before_scheme_parse", " https://pve1.local:8006 ", "pve1.local"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := deriveSetupScriptServerName(tc.serverHost)
+ if got != tc.want {
+ t.Fatalf("deriveSetupScriptServerName(%q) = %q, want %q", tc.serverHost, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestBranchcov0723AmPatrolConfigAdapterIsValidAutonomyLevel(t *testing.T) {
+ // IsValidPatrolAutonomyLevel ignores the receiver entirely (it delegates to
+ // a pure package function), so a zero-valued adapter is safe to construct.
+ adapter := &patrolConfigAdapter{}
+
+ validLevels := []string{
+ config.PatrolAutonomyMonitor,
+ config.PatrolAutonomyApproval,
+ config.PatrolAutonomyAssisted,
+ config.PatrolAutonomyFull,
+ }
+ for _, level := range validLevels {
+ t.Run("valid/"+level, func(t *testing.T) {
+ if !adapter.IsValidPatrolAutonomyLevel(level) {
+ t.Fatalf("IsValidPatrolAutonomyLevel(%q) = false, want true", level)
+ }
+ })
+ }
+
+ invalidCases := []struct {
+ name string
+ level string
+ }{
+ {"empty", ""},
+ {"unknown_level", "supervised"},
+ {"wrong_case_upper", "FULL"},
+ {"wrong_case_capitalised", "Monitor"},
+ {"whitespace_padded", " monitor "},
+ }
+ for _, tc := range invalidCases {
+ t.Run("invalid/"+tc.name, func(t *testing.T) {
+ if adapter.IsValidPatrolAutonomyLevel(tc.level) {
+ t.Fatalf("IsValidPatrolAutonomyLevel(%q) = true, want false", tc.level)
+ }
+ })
+ }
+}
+
+func TestBranchcov0723AmApprovalStoreAdapterAssessRiskLevel(t *testing.T) {
+ // AssessRiskLevel delegates to a pure function and never dereferences the
+ // receiver, so a zero-valued adapter is safe.
+ adapter := &approvalStoreAdapter{}
+
+ cases := []struct {
+ name string
+ command string
+ targetType string
+ want string
+ }{
+ // High-risk command (rm -rf) matches a high-risk pattern regardless of
+ // the target type.
+ {"high_risk_command_non_node_target", "rm -rf /var/log", "container", "high"},
+ // Medium-risk command on a non-node target returns medium.
+ {"medium_risk_command_non_node_target", "systemctl restart nginx", "agent", "medium"},
+ // No pattern matches: default arm returns low.
+ {"low_risk_command_default_arm", "echo hello", "agent", "low"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := adapter.AssessRiskLevel(tc.command, tc.targetType)
+ if got != tc.want {
+ t.Fatalf("AssessRiskLevel(%q, %q) = %q, want %q", tc.command, tc.targetType, got, tc.want)
+ }
+ })
+ }
+
+ // Regression lock documenting SOURCE BUG: the `targetType == "node"`
+ // escalation block in approval.AssessRiskLevel is unreachable dead code.
+ // The preceding unconditional medium-pattern loop returns RiskMedium for
+ // any medium command before the node branch runs, and a non-medium command
+ // cannot match the node-branch loop either. As a result the target type has
+ // no observable effect, and the intended "node + medium => high" rule never
+ // fires. This locks in the *current* (buggy) behaviour so a future fix is a
+ // deliberate, visible change.
+ t.Run("node_target_does_not_escalate_medium_command_dead_branch", func(t *testing.T) {
+ got := adapter.AssessRiskLevel("systemctl restart nginx", "node")
+ const want = "medium" // would be "high" if the node escalation worked
+ if got != want {
+ t.Fatalf("AssessRiskLevel(%q, %q) = %q, want %q (node escalation is currently dead code)",
+ "systemctl restart nginx", "node", got, want)
+ }
+ })
+}
+
+func TestBranchcov0723AmHostedEntitlementRefreshError(t *testing.T) {
+ t.Run("populated_message_returned_verbatim", func(t *testing.T) {
+ err := &hostedEntitlementRefreshError{statusCode: 410, message: "lease revoked", permanent: true}
+ const want = "lease revoked"
+ if got := err.Error(); got != want {
+ t.Fatalf("Error() = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("whitespace_message_falls_back_to_status_format", func(t *testing.T) {
+ err := &hostedEntitlementRefreshError{statusCode: 503, message: " "}
+ const want = "hosted entitlement refresh failed with status 503"
+ if got := err.Error(); got != want {
+ t.Fatalf("Error() = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("zero_value_falls_back_to_status_zero", func(t *testing.T) {
+ err := &hostedEntitlementRefreshError{}
+ const want = "hosted entitlement refresh failed with status 0"
+ if got := err.Error(); got != want {
+ t.Fatalf("Error() = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("nil_receiver_returns_empty", func(t *testing.T) {
+ var err *hostedEntitlementRefreshError
+ if got := err.Error(); got != "" {
+ t.Fatalf("nil receiver Error() = %q, want %q", got, "")
+ }
+ })
+
+ // The type defines no Unwrap, so it does not wrap an underlying cause.
+ t.Run("does_not_wrap_cause", func(t *testing.T) {
+ err := &hostedEntitlementRefreshError{statusCode: 410, message: "lease revoked"}
+ if unwrapped := errors.Unwrap(err); unwrapped != nil {
+ t.Fatalf("errors.Unwrap() = %v, want nil (no wrapped cause)", unwrapped)
+ }
+ var target *hostedEntitlementRefreshError
+ if !errors.As(err, &target) {
+ t.Fatalf("errors.As to the same concrete pointer type should succeed")
+ }
+ })
+}
+
+func TestBranchcov0723AmReportScheduleValidationError(t *testing.T) {
+ t.Run("populated_value_returns_message", func(t *testing.T) {
+ err := reportScheduleValidationError{code: "invalid_name", message: "Schedule name is required"}
+ const want = "Schedule name is required"
+ if got := err.Error(); got != want {
+ t.Fatalf("Error() = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("zero_value_returns_empty", func(t *testing.T) {
+ var err reportScheduleValidationError
+ if got := err.Error(); got != "" {
+ t.Fatalf("zero value Error() = %q, want %q", got, "")
+ }
+ })
+
+ // Value-receiver error type with no Unwrap: it never wraps a cause.
+ t.Run("does_not_wrap_cause", func(t *testing.T) {
+ err := reportScheduleValidationError{code: "invalid_name", message: "boom"}
+ if unwrapped := errors.Unwrap(err); unwrapped != nil {
+ t.Fatalf("errors.Unwrap() = %v, want nil (no wrapped cause)", unwrapped)
+ }
+ var target reportScheduleValidationError
+ if !errors.As(err, &target) {
+ t.Fatalf("errors.As to the same concrete value type should succeed")
+ }
+ })
+}
diff --git a/internal/hostagent/proxmox_setup_classify_branchcov0723am_test.go b/internal/hostagent/proxmox_setup_classify_branchcov0723am_test.go
new file mode 100644
index 0000000000..c7cf07db1b
--- /dev/null
+++ b/internal/hostagent/proxmox_setup_classify_branchcov0723am_test.go
@@ -0,0 +1,144 @@
+package hostagent
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// These tests raise branch/function coverage for previously-uncovered
+// functions in the hostagent package without modifying any source file.
+//
+// Targets:
+// - tokenAlreadyExists (proxmox_setup.go:213) — pure two-channel classifier.
+// - observerBufferFileName (agent.go:879) — pure name builder.
+// - isAlreadyRegistered (proxmox_setup.go:1494) — filesystem predicate.
+//
+// Every subtest is independent (own t.TempDir() where the filesystem is
+// touched) and asserts concrete return values, not "did not panic".
+
+// TestBranchcov0723AmTokenAlreadyExists covers tokenAlreadyExists
+// (proxmox_setup.go:213). The function lowercases — but does NOT trim — both
+// fmt.Sprintf("%v", err) and output, then returns true if EITHER contains the
+// single phrase "already exists". Each row drives a distinct arm/normalisation
+// rule: nil err (which stringifies to "<nil>"), the err channel only, the
+// output channel only, both, case folding on each channel, a wrapped error
+// whose match is only reachable via fmt's flattening of %w, whitespace-padded
+// output (not trimmed, but the substring search still hits), and several
+// near-miss inputs that must return false.
+func TestBranchcov0723AmTokenAlreadyExists(t *testing.T) {
+ wrappedInner := errors.New("parameter 'token' already exists for this user")
+ wrappedErr := fmt.Errorf("token rotation step failed: %w", wrappedInner)
+
+ tests := []struct {
+ name string
+ err error
+ output string
+ want bool
+ }{
+ {"NilErrAndEmptyOutputIsFalse", nil, "", false},
+ {"PhraseInErrorOnlyMatches", errors.New("400 Bad Request: already exists"), "", true},
+ {"PhraseInOutputOnlyMatches", nil, "pveum stderr: token already exists", true},
+ {"PhraseInBothChannelsMatches", errors.New("already exists"), "already exists", true},
+ {"UpperCaseErrorFoldedByToLower", errors.New("ALREADY EXISTS"), "", true},
+ {"MixedCaseOutputFoldedByToLower", nil, "Token ALREADY Exists", true},
+ {
+ // The outer wrapper message contains no "already exists"; the match
+ // is only possible because fmt.Sprintf("%v", err) flattens %w.
+ name: "WrappedErrorCarryingPhraseMatchesViaFlattening",
+ err: wrappedErr,
+ output: "",
+ want: true,
+ },
+ {"PaddedOutputNotTrimmedButStillContainsPhrase", nil, " \t already exists \n ", true},
+ {"NearMatchMissingTrailingSIsFalse", errors.New("already exist"), "", false},
+ {"NearMissMisspelledIsFalse", nil, "alredy exists", false},
+ {"WordsPresentButPhraseAbsentIsFalse", nil, "the token exists, registered already", false},
+ {"SuperficiallySimilarUnrelatedMessageIsFalse", errors.New("permission denied"), "no changes made", false},
+ {"NilErrStringifiesToNilAndMisses", nil, "created token abc123", false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := tokenAlreadyExists(tt.err, tt.output)
+ if got != tt.want {
+ t.Errorf("tokenAlreadyExists(err=%v, output=%q) = %v, want %v", tt.err, tt.output, got, tt.want)
+ }
+ })
+ }
+}
+
+// TestBranchcov0723AmObserverBufferFileName covers observerBufferFileName
+// (agent.go:879), a pure name builder. It asserts the exact formatted string
+// and that the supplied id is interpolated verbatim (no sanitisation), which is
+// the real behavioural contract callers rely on.
+func TestBranchcov0723AmObserverBufferFileName(t *testing.T) {
+ tests := []struct {
+ name string
+ id string
+ want string
+ }{
+ {"TypicalID", "obs-1", "report-buffer-observer-obs-1.json"},
+ {"EmptyIDProducesEmptySegment", "", "report-buffer-observer-.json"},
+ {"IDSuffixedWithUUID", "9cf3a1b2-uuid", "report-buffer-observer-9cf3a1b2-uuid.json"},
+ {"IDInsertedVerbatimNoSanitisation", "a/b", "report-buffer-observer-a/b.json"},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := observerBufferFileName(tt.id); got != tt.want {
+ t.Errorf("observerBufferFileName(%q) = %q, want %q", tt.id, got, tt.want)
+ }
+ })
+ }
+}
+
+// TestBranchcov0723AmIsAlreadyRegistered covers isAlreadyRegistered
+// (proxmox_setup.go:1494), a predicate that reports whether the legacy state
+// marker file exists. Each subtest uses its own t.TempDir() and a collector
+// backed by os.Stat so the filesystem state is real but isolated. The false
+// arm (no marker), the true arm (legacy marker present), and a guard proving a
+// *different* state filename does not satisfy the predicate are all asserted.
+func TestBranchcov0723AmIsAlreadyRegistered(t *testing.T) {
+ newSetup := func(t *testing.T, stateDir string) *ProxmoxSetup {
+ t.Helper()
+ return &ProxmoxSetup{
+ stateDir: stateDir,
+ collector: &mockCollector{statFn: os.Stat},
+ }
+ }
+
+ t.Run("NoMarkerFileIsFalse", func(t *testing.T) {
+ dir := t.TempDir()
+ p := newSetup(t, dir)
+ if p.isAlreadyRegistered() {
+ t.Errorf("isAlreadyRegistered() = true in empty dir %q, want false", dir)
+ }
+ })
+
+ t.Run("LegacyMarkerPresentIsTrue", func(t *testing.T) {
+ dir := t.TempDir()
+ legacyPath := filepath.Join(dir, "proxmox-registered")
+ if err := os.WriteFile(legacyPath, []byte("2026-01-01T00:00:00Z"), 0600); err != nil {
+ t.Fatalf("write legacy marker: %v", err)
+ }
+ p := newSetup(t, dir)
+ if !p.isAlreadyRegistered() {
+ t.Errorf("isAlreadyRegistered() = false with marker at %q, want true", legacyPath)
+ }
+ })
+
+ t.Run("OnlyPerTypeMarkerDoesNotSatisfyLegacyPredicate", func(t *testing.T) {
+ // isAlreadyRegistered looks exclusively at the legacy
+ // "proxmox-registered" path; a per-type marker (e.g. the PVE one)
+ // must not cause it to report true.
+ dir := t.TempDir()
+ if err := os.WriteFile(filepath.Join(dir, "proxmox-pve-registered"), []byte("x"), 0600); err != nil {
+ t.Fatalf("write pve marker: %v", err)
+ }
+ p := newSetup(t, dir)
+ if p.isAlreadyRegistered() {
+ t.Errorf("isAlreadyRegistered() = true with only a per-type marker present, want false (legacy path only)")
+ }
+ })
+}
diff --git a/internal/monitoring/temperature_buffer_branchcov0723am_test.go b/internal/monitoring/temperature_buffer_branchcov0723am_test.go
new file mode 100644
index 0000000000..ad028f44c5
--- /dev/null
+++ b/internal/monitoring/temperature_buffer_branchcov0723am_test.go
@@ -0,0 +1,348 @@
+package monitoring
+
+import (
+ "math"
+ "math/rand"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// TestBranchcov0723Am_LimitedTemperatureBufferBytes exercises every branch of
+// limitedTemperatureBuffer.Write (the three return paths) and pins the
+// observable contract of Bytes: it returns the prefix of the input that fit
+// within maxBytes, keeping the FIRST bytes (head), and the returned slice
+// aliases the internal buffer.
+func TestBranchcov0723Am_LimitedTemperatureBufferBytes(t *testing.T) {
+ t.Run("empty buffer returns nil", func(t *testing.T) {
+ b := &limitedTemperatureBuffer{maxBytes: 16}
+ got := b.Bytes()
+ // bytes.Buffer.Bytes() on an untouched buffer returns nil (b.buf[nil][0:]).
+ assert.Nil(t, got, "empty buffer should expose no bytes")
+ assert.Len(t, got, 0)
+ })
+
+ t.Run("write under limit exposes exact bytes", func(t *testing.T) {
+ b := &limitedTemperatureBuffer{maxBytes: 16}
+ n, err := b.Write([]byte("hello"))
+ require.NoError(t, err, "in-budget Write must not error")
+ assert.Equal(t, 5, n, "in-budget Write reports full length")
+ assert.False(t, b.exceeded, "exceeded flag must stay false when under limit")
+ assert.Equal(t, "hello", string(b.Bytes()), "Bytes must return exactly what was written")
+ })
+
+ t.Run("single write over limit keeps the head prefix and flags exceeded", func(t *testing.T) {
+ const max = 5
+ b := &limitedTemperatureBuffer{maxBytes: max}
+ // "abcdefgh" is 8 bytes; only the first `max` fit.
+ n, err := b.Write([]byte("abcdefgh"))
+ require.ErrorIs(t, err, errTemperatureCommandOutputTooLarge, "over-budget Write must report the size-limit error")
+ assert.Equal(t, max, n, "over-budget Write reports only the bytes that fit")
+ assert.True(t, b.exceeded, "exceeded flag must flip true when truncating")
+ // Truncation semantics: the HEAD (first max bytes) is retained.
+ assert.Equal(t, "abcde", string(b.Bytes()), "Bytes must keep the first maxBytes bytes of the input")
+ })
+
+ t.Run("further write after limit is rejected without growing buffer", func(t *testing.T) {
+ b := &limitedTemperatureBuffer{maxBytes: 5}
+ _, _ = b.Write([]byte("abcdefgh")) // saturates the limit and flips exceeded
+ before := string(b.Bytes())
+ n, err := b.Write([]byte("XYZ"))
+ require.ErrorIs(t, err, errTemperatureCommandOutputTooLarge, "Write after the limit is reached must short-circuit with the size-limit error")
+ assert.Equal(t, 0, n, "no bytes may be appended once remaining <= 0")
+ assert.Equal(t, before, string(b.Bytes()), "buffer contents must not change after the limit is hit")
+ })
+
+ t.Run("several writes accumulating across the limit boundary", func(t *testing.T) {
+ b := &limitedTemperatureBuffer{maxBytes: 5}
+ // First two writes fit entirely ("abc" + "de" == 5 bytes).
+ n1, err1 := b.Write([]byte("abc"))
+ require.NoError(t, err1)
+ assert.Equal(t, 3, n1)
+ n2, err2 := b.Write([]byte("de"))
+ require.NoError(t, err2)
+ assert.Equal(t, 2, n2)
+ assert.False(t, b.exceeded, "exactly at limit is not yet exceeded")
+ assert.Equal(t, "abcde", string(b.Bytes()))
+
+ // Third write tips over the limit; nothing more fits.
+ n3, err3 := b.Write([]byte("fghi"))
+ require.ErrorIs(t, err3, errTemperatureCommandOutputTooLarge)
+ assert.Equal(t, 0, n3, "no bytes may be appended once the buffer is full")
+ assert.True(t, b.exceeded)
+ assert.Equal(t, "abcde", string(b.Bytes()), "head prefix is preserved when accumulating across the limit")
+ })
+
+ t.Run("write larger than remaining keeps head and reports only what fit", func(t *testing.T) {
+ b := &limitedTemperatureBuffer{maxBytes: 5}
+ _, _ = b.Write([]byte("abc")) // 3 bytes used, 2 remaining
+ // "defgh" is 5 bytes but only 2 fit; head retention means we keep "abcde".
+ n, err := b.Write([]byte("defgh"))
+ require.ErrorIs(t, err, errTemperatureCommandOutputTooLarge)
+ assert.Equal(t, 2, n, "partial write reports only the bytes that fit (maxBytes - current len)")
+ assert.True(t, b.exceeded)
+ assert.Equal(t, "abcde", string(b.Bytes()), "must keep the first maxBytes bytes across two writes")
+ })
+
+ t.Run("returned slice aliases the internal buffer", func(t *testing.T) {
+ // Documents a real aliasing property of bytes.Buffer.Bytes(): the
+ // returned slice shares storage with the buffer, so mutations leak.
+ // Reported as a suspected source-quality issue in GLM_REPORT_go-montemp.md.
+ b := &limitedTemperatureBuffer{maxBytes: 16}
+ _, err := b.Write([]byte("hello"))
+ require.NoError(t, err)
+
+ view := b.Bytes()
+ require.Len(t, view, 5)
+ view[0] = 'X' // mutate the returned slice in place
+
+ assert.Equal(t, "Xello", string(b.Bytes()), "Bytes() aliases the internal buffer; mutating the returned slice leaks (suspected bug)")
+ })
+}
+
+// TestBranchcov0723Am_GeneratePlateauSeries covers generatePlateauSeries
+// directly. The function is deterministic given a seeded *rand.Rand, so all
+// assertions are against concrete outputs.
+func TestBranchcov0723Am_GeneratePlateauSeries(t *testing.T) {
+ makeRng := func(seed int64) *rand.Rand { return rand.New(rand.NewSource(seed)) }
+
+ t.Run("points zero returns empty slice", func(t *testing.T) {
+ rng := makeRng(7)
+ got := generatePlateauSeries(50, 0, 0, 100, 100, rng)
+ // Loop body never executes when points == 0; raw is allocated empty.
+ assert.Len(t, got, 0, "points=0 must produce an empty series without panic")
+ })
+
+ t.Run("points negative panics at makeslice", func(t *testing.T) {
+ // Documents observed behaviour: generatePlateauSeries does not guard
+ // negative points, so `make([]float64, points)` panics. Reported as a
+ // suspected source bug in the report (callers like GenerateSeededSeries
+ // happen to gate on points <= 1, hiding this from production).
+ defer func() {
+ r := recover()
+ require.NotNil(t, r, "expected makeslice panic for negative points")
+ t.Logf("observed panic for negative points (suspected source bug): %v", r)
+ }()
+ rng := makeRng(7)
+ _ = generatePlateauSeries(50, -3, 0, 100, 100, rng)
+ })
+
+ t.Run("points one panics at integer divide by zero", func(t *testing.T) {
+ // Documents observed behaviour: with points < plateauCount (>=3),
+ // segmentLen = points/plateauCount == 0 and `i / segmentLen` panics.
+ // Reported as a suspected source bug; production callers gate on
+ // points <= 1, so the panic is currently unreachable in normal use.
+ defer func() {
+ r := recover()
+ require.NotNil(t, r, "expected divide-by-zero panic for points=1")
+ t.Logf("observed panic for points=1 (suspected source bug): %v", r)
+ }()
+ rng := makeRng(7)
+ _ = generatePlateauSeries(50, 1, 0, 100, 100, rng)
+ })
+
+ t.Run("normal run has correct length and stays within bounds", func(t *testing.T) {
+ const (
+ current = 50.0
+ points = 240
+ min = 0.0
+ max = 100.0
+ span = 100.0
+ )
+ rng := makeRng(123)
+ got := generatePlateauSeries(current, points, min, max, span, rng)
+ require.Len(t, got, points, "series length must equal requested points")
+
+ for i, v := range got {
+ if !(v >= min && v <= max) {
+ t.Fatalf("point %d out of bounds: %v (want within [%v,%v])", i, v, min, max)
+ }
+ if math.IsNaN(v) || math.IsInf(v, 0) {
+ t.Fatalf("point %d is non-finite: %v", i, v)
+ }
+ }
+ })
+
+ t.Run("identical seed produces identical series", func(t *testing.T) {
+ a := generatePlateauSeries(62.5, 200, 10, 90, 80, makeRng(42))
+ b := generatePlateauSeries(62.5, 200, 10, 90, 80, makeRng(42))
+ require.Len(t, a, 200)
+ require.Len(t, b, 200)
+ for i := range a {
+ if a[i] != b[i] {
+ t.Fatalf("determinism violated at index %d: %v != %v", i, a[i], b[i])
+ }
+ }
+ })
+
+ t.Run("different seeds produce different series", func(t *testing.T) {
+ a := generatePlateauSeries(62.5, 200, 10, 90, 80, makeRng(1))
+ b := generatePlateauSeries(62.5, 200, 10, 90, 80, makeRng(999))
+ require.Len(t, a, 200)
+ require.Len(t, b, 200)
+ diff := 0
+ for i := range a {
+ if a[i] != b[i] {
+ diff++
+ }
+ }
+ assert.Greater(t, diff, 0, "different seeds must yield different series; got identical output")
+ })
+
+ t.Run("min equals max collapses every value to that constant", func(t *testing.T) {
+ const c = 42.0
+ // span == 0 -> all offsets/noise terms vanish and clamp pins every level.
+ got := generatePlateauSeries(c, 120, c, c, 0, makeRng(5))
+ require.Len(t, got, 120)
+ for i, v := range got {
+ if v != c {
+ t.Fatalf("point %d = %v, want %v when min==max==current", i, v, c)
+ }
+ }
+ })
+
+ t.Run("current outside bounds leaks past max into output", func(t *testing.T) {
+ // generatePlateauSeries does NOT clamp `current` on entry (unlike its
+ // only caller GenerateSeededSeries). The final plateau level is set to
+ // `current + noise` without clamping, so out-of-range current leaks
+ // into the series. This pins that observed (un-clamped) behaviour.
+ const (
+ current = 150.0
+ min = 0.0
+ max = 100.0
+ span = 100.0
+ )
+ got := generatePlateauSeries(current, 200, min, max, span, makeRng(31))
+ require.Len(t, got, 200)
+
+ // Last point belongs to the final plateau and tracks `current` closely.
+ assert.Greater(t, got[len(got)-1], max,
+ "out-of-range current must leak into the un-clamped tail; got last=%v", got[len(got)-1])
+
+ // And at least one point must exceed max, proving the function does not
+ // clamp its own output.
+ anyOver := false
+ for _, v := range got {
+ if v > max {
+ anyOver = true
+ break
+ }
+ }
+ assert.True(t, anyOver, "expected at least one value > max when current > max (function does not clamp output)")
+ })
+}
+
+// TestBranchcov0723Am_MockNodeMetricsForChart covers
+// mockNodeMetricsForChart. The chart-timestamp path uses time.Now(), so only
+// structural invariants (key set, length, ordering, head/tail membership) are
+// asserted, never exact values.
+func TestBranchcov0723Am_MockNodeMetricsForChart(t *testing.T) {
+ const nodeID = "branchcov-node-723am"
+
+ expectAscending := func(t *testing.T, points []MetricPoint) {
+ t.Helper()
+ for i := 1; i < len(points); i++ {
+ if points[i].Timestamp.Before(points[i-1].Timestamp) {
+ t.Fatalf("points not in ascending timestamp order at index %d: %v before %v",
+ i, points[i].Timestamp, points[i-1].Timestamp)
+ }
+ }
+ }
+
+ expectKeysExact := func(t *testing.T, got map[string][]MetricPoint, want []string) {
+ t.Helper()
+ if len(got) != len(want) {
+ t.Fatalf("expected %d map entries (%v), got %d (%v)", len(want), want, len(got), keysOf(got))
+ }
+ for _, k := range want {
+ if _, ok := got[k]; !ok {
+ t.Fatalf("expected key %q missing from result; got keys %v", k, keysOf(got))
+ }
+ }
+ }
+
+ t.Run("nil metricTypes falls back to default node chart set", func(t *testing.T) {
+ got := mockNodeMetricsForChart(nodeID, nil, time.Hour)
+ expectKeysExact(t, got, mockNodeChartMetricTypes)
+ for k, pts := range got {
+ expectAscending(t, pts)
+ assert.NotEmpty(t, pts, "default metric %q should produce points for a known node", k)
+ }
+ })
+
+ t.Run("empty metricTypes falls back to default node chart set", func(t *testing.T) {
+ got := mockNodeMetricsForChart(nodeID, []string{}, time.Hour)
+ expectKeysExact(t, got, mockNodeChartMetricTypes)
+ })
+
+ t.Run("single requested metric type yields exactly one entry", func(t *testing.T) {
+ got := mockNodeMetricsForChart(nodeID, []string{"cpu"}, time.Hour)
+ expectKeysExact(t, got, []string{"cpu"})
+ require.NotEmpty(t, got["cpu"], "cpu series should not be empty for a known node/metric")
+ expectAscending(t, got["cpu"])
+ })
+
+ t.Run("several requested metric types yield one entry each and no extras", func(t *testing.T) {
+ want := []string{"cpu", "memory", "disk"}
+ got := mockNodeMetricsForChart(nodeID, want, time.Hour)
+ expectKeysExact(t, got, want)
+ for _, k := range want {
+ require.NotEmpty(t, got[k], "%s series should not be empty", k)
+ expectAscending(t, got[k])
+ }
+ })
+
+ t.Run("unknown metric type still produces a map entry with sampled points", func(t *testing.T) {
+ // Source has no allowlist for metric types: it forwards whatever the
+ // caller asked for to the canonical sampler, which assigns default
+ // bounds [0,100] for unknown metric names. Pin that contract.
+ got := mockNodeMetricsForChart(nodeID, []string{"bogulus_metric_723am"}, time.Hour)
+ expectKeysExact(t, got, []string{"bogulus_metric_723am"})
+ require.NotEmpty(t, got["bogulus_metric_723am"], "unknown metric type should still yield sampled points (default bounds)")
+ expectAscending(t, got["bogulus_metric_723am"])
+ })
+
+ t.Run("zero duration defaults to one hour window and preserves ordering", func(t *testing.T) {
+ got := mockNodeMetricsForChart(nodeID, []string{"cpu"}, 0)
+ expectKeysExact(t, got, []string{"cpu"})
+ require.NotEmpty(t, got["cpu"], "zero duration must not produce an empty series (clamped to 1h)")
+ expectAscending(t, got["cpu"])
+ })
+
+ t.Run("negative duration defaults to one hour window and preserves ordering", func(t *testing.T) {
+ got := mockNodeMetricsForChart(nodeID, []string{"cpu"}, -2*time.Hour)
+ expectKeysExact(t, got, []string{"cpu"})
+ require.NotEmpty(t, got["cpu"], "negative duration must not produce an empty series (clamped to 1h)")
+ expectAscending(t, got["cpu"])
+ })
+
+ t.Run("all returned series are time-ordered", func(t *testing.T) {
+ // Comprehensive ordering check across the default set + a custom type,
+ // exercising every codepath that materialises MetricPoint slices.
+ types := append([]string(nil), mockNodeChartMetricTypes...)
+ types = append(types, "temperature")
+ got := mockNodeMetricsForChart(nodeID, types, 2*time.Hour)
+ expectKeysExact(t, got, types)
+ for k, pts := range got {
+ expectAscending(t, pts)
+ assert.NotEmpty(t, pts, "metric %q produced no points", k)
+ }
+ })
+
+ t.Run("empty nodeID returns empty map even with valid metric types", func(t *testing.T) {
+ // Trimming empty nodeID short-circuits before any sampling.
+ got := mockNodeMetricsForChart(" ", []string{"cpu"}, time.Hour)
+ assert.Len(t, got, 0, "blank nodeID must return an empty map (no entries)")
+ })
+}
+
+// keysOf returns the key slice of a map for stable failure messages.
+func keysOf(m map[string][]MetricPoint) []string {
+ out := make([]string, 0, len(m))
+ for k := range m {
+ out = append(out, k)
+ }
+ return out
+}