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 Unraid merge, setup classifier and retry helpers left untested

rcourtman743ba7e5a397
diff --git a/internal/ai/tools/purehelpers_branchcov0722am_test.go b/internal/ai/tools/purehelpers_branchcov0722am_test.go
new file mode 100644
index 0000000000..73cbecae80
--- /dev/null
+++ b/internal/ai/tools/purehelpers_branchcov0722am_test.go
@@ -0,0 +1,112 @@
+package tools
+
+import (
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/approval"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/stretchr/testify/assert"
+)
+
+// This file raises branch coverage for two pure helpers that were previously
+// 0.0% covered:
+// - dockerRuntimeCommand (tools_docker.go) — switch on a normalised runtime
+// string with a nil-host guard and a default arm.
+// - approvalDecisionActor (action_audit.go) — precedence chain of
+// req.DecidedBy -> fallback -> approvalAuditActor constant.
+//
+// Both helpers are pure (no I/O) and return exact strings, so every case
+// asserts the concrete return value. approvalAuditActor is defined in
+// action_audit.go as approval.RequesterPulseAssistant ("pulse_assistant"); the
+// default-arm cases assert that literal so a constant change would surface here.
+
+// TestBranchcov0722R2DockerRuntimeCommand covers every branch arm of
+// dockerRuntimeCommand: the nil-host guard, both recognised switch cases
+// ("podman", "docker"), the surrounding-whitespace + mixed-case normalisation
+// path (TrimSpace + ToLower), an unrecognised runtime falling through to the
+// default, and an empty runtime falling through to the default. Every arm is
+// asserted against the exact command string it returns.
+func TestBranchcov0722R2DockerRuntimeCommand(t *testing.T) {
+ tests := []struct {
+ name string
+ host *models.DockerHost
+ want string
+ }{
+ // --- nil-host guard: default command returned. ---
+ {name: "nil_host_returns_docker", host: nil, want: "docker"},
+
+ // --- recognised switch arms (exact, already-canonical input). ---
+ {name: "podman_runtime_returns_podman", host: &models.DockerHost{Runtime: "podman"}, want: "podman"},
+ {name: "docker_runtime_returns_docker", host: &models.DockerHost{Runtime: "docker"}, want: "docker"},
+
+ // --- normalisation: TrimSpace + ToLower route mixed input to a case. ---
+ {name: "podman_with_whitespace_and_mixed_case", host: &models.DockerHost{Runtime: " PoDmAn "}, want: "podman"},
+ {name: "docker_with_whitespace_and_upper_case", host: &models.DockerHost{Runtime: "\tDOCKER\n"}, want: "docker"},
+
+ // --- default arm: unrecognised runtime falls through to "docker". ---
+ {name: "unrecognised_runtime_falls_through", host: &models.DockerHost{Runtime: "containerd"}, want: "docker"},
+
+ // --- default arm: empty runtime falls through to "docker". ---
+ {name: "empty_runtime_falls_through", host: &models.DockerHost{Runtime: ""}, want: "docker"},
+ {name: "whitespace_only_runtime_falls_through", host: &models.DockerHost{Runtime: " "}, want: "docker"},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := dockerRuntimeCommand(tc.host)
+ assert.Equal(t, tc.want, got, "dockerRuntimeCommand mismatch")
+ })
+ }
+}
+
+// TestBranchcov0722R2ApprovalDecisionActor covers every branch arm of
+// approvalDecisionActor. The function implements a three-step precedence chain:
+// 1. req.DecidedBy (trimmed, if req != nil and non-empty) wins;
+// 2. otherwise the fallback argument (trimmed, if non-empty);
+// 3. otherwise the package constant approvalAuditActor ("pulse_assistant").
+//
+// Note: the function inspects ONLY req.DecidedBy — there are no further
+// candidate fields. Cases below exercise each precedence step, the
+// whitespace-only fall-through for both DecidedBy and fallback, trimming of the
+// returned value, and the all-empty path (including an empty fallback).
+func TestBranchcov0722R2ApprovalDecisionActor(t *testing.T) {
+ // approvalAuditActor is approval.RequesterPulseAssistant == "pulse_assistant".
+ const wantDefaultActor = "pulse_assistant"
+ assert.Equal(t, wantDefaultActor, approvalAuditActor,
+ "precondition: approvalAuditActor must equal %q", wantDefaultActor)
+ assert.Equal(t, wantDefaultActor, approval.RequesterPulseAssistant,
+ "precondition: approvalAuditActor tracks approval.RequesterPulseAssistant")
+
+ tests := []struct {
+ name string
+ req *approval.ApprovalRequest
+ fallback string
+ want string
+ }{
+ // --- nil request: falls straight through to fallback / constant. ---
+ {name: "nil_req_uses_fallback", req: nil, fallback: "alice", want: "alice"},
+ {name: "nil_req_empty_fallback_uses_constant", req: nil, fallback: "", want: wantDefaultActor},
+ {name: "nil_req_whitespace_fallback_uses_constant", req: nil, fallback: " ", want: wantDefaultActor},
+
+ // --- DecidedBy wins (step 1), including over a populated fallback. ---
+ {name: "decidedby_wins", req: &approval.ApprovalRequest{DecidedBy: "bob"}, fallback: "", want: "bob"},
+ {name: "decidedby_wins_over_fallback", req: &approval.ApprovalRequest{DecidedBy: "bob"}, fallback: "alice", want: "bob"},
+ {name: "decidedby_is_trimmed", req: &approval.ApprovalRequest{DecidedBy: " bob "}, fallback: "", want: "bob"},
+
+ // --- DecidedBy whitespace-only/empty falls through to fallback (step 2). ---
+ {name: "whitespace_decidedby_falls_to_fallback", req: &approval.ApprovalRequest{DecidedBy: " "}, fallback: "alice", want: "alice"},
+ {name: "empty_decidedby_falls_to_fallback", req: &approval.ApprovalRequest{DecidedBy: ""}, fallback: "alice", want: "alice"},
+ {name: "fallback_is_trimmed_when_used", req: &approval.ApprovalRequest{DecidedBy: ""}, fallback: " alice ", want: "alice"},
+
+ // --- all candidates empty: constant is the final default (step 3). ---
+ {name: "empty_decidedby_empty_fallback_uses_constant", req: &approval.ApprovalRequest{DecidedBy: ""}, fallback: "", want: wantDefaultActor},
+ {name: "whitespace_decidedby_whitespace_fallback_uses_constant", req: &approval.ApprovalRequest{DecidedBy: " "}, fallback: " ", want: wantDefaultActor},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := approvalDecisionActor(tc.req, tc.fallback)
+ assert.Equal(t, tc.want, got, "approvalDecisionActor mismatch")
+ })
+ }
+}
diff --git a/internal/hostagent/setup_classifiers_branchcov0722am_test.go b/internal/hostagent/setup_classifiers_branchcov0722am_test.go
new file mode 100644
index 0000000000..44c10a95f2
--- /dev/null
+++ b/internal/hostagent/setup_classifiers_branchcov0722am_test.go
@@ -0,0 +1,255 @@
+package hostagent
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+
+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
+)
+
+// These tests target four previously-uncovered functions in the hostagent
+// package, asserting each function's real branch behaviour (every matched
+// substring with case/whitespace variations, nil/empty inputs, the mutation
+// contract for the SMART annotator, and errors.Is/errors.As traversal through
+// the error wrappers) without modifying any source file.
+//
+// NOTE: the task brief lists "(*clientError).Unwrap()" at proxmox_setup.go:1208,
+// but the type at that line is permanentError, not clientError. clientError
+// (proxmox_setup.go:1192) only defines Error(); it has no Unwrap() method, so
+// it cannot be unwrapped. The Unwrap() arms are therefore exercised against
+// permanentError, which is the type that actually owns them. See the report for
+// details.
+
+// branchcovTestErr is a concrete error type used to verify errors.As traversal
+// through a *permanentError wrapper.
+type branchcovTestErr struct{ msg string }
+
+func (e *branchcovTestErr) Error() string { return e.msg }
+
+// TestBranchcov0722R2IsAlreadyExistsOutput covers isAlreadyExistsOutput
+// (proxmox_setup.go:1487). The function lowercases + trims its input and then
+// tests for the single substring "already exists", so every arm below drives
+// that one match against the normalisation rules plus the no-match path.
+func TestBranchcov0722R2IsAlreadyExistsOutput(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want bool
+ }{
+ {"exact match", "already exists", true},
+ {"uppercase normalised by ToLower", "ALREADY EXISTS", true},
+ {"mixed case normalised by ToLower", "Already Exists", true},
+ {"leading and trailing whitespace trimmed", " already exists ", true},
+ {"tabs and newlines trimmed", "\talready exists\n", true},
+ {"substring embedded in longer output", "create VM failed: vm 100 already exists on node pve1", true},
+ {"only the substring", "already exists", true},
+ {"empty string is no match", "", false},
+ {"whitespace only trims to empty", " ", false},
+ {"unrelated output", "created successfully", false},
+ {"near match missing trailing s", "already exist", false},
+ {"near match misspelled", "alredy exists", false},
+ {"contains words but not the phrase", "exists already without the phrase", false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := isAlreadyExistsOutput(tt.in); got != tt.want {
+ t.Errorf("isAlreadyExistsOutput(%q) = %v, want %v", tt.in, got, tt.want)
+ }
+ })
+ }
+}
+
+// TestBranchcov0722R2ClientErrorError covers clientError.Error()
+// (proxmox_setup.go:1198), asserting the exact formatted message for a
+// representative status code + body and for an empty body. It also verifies
+// that *clientError is reachable via errors.As when wrapped, which is how the
+// caller at proxmox_setup.go:1473 decides to skip retries.
+func TestBranchcov0722R2ClientErrorError(t *testing.T) {
+ t.Run("FormatsStatusCodeAndBody", func(t *testing.T) {
+ ce := &clientError{statusCode: 404, body: `{"errors":["no such object"]}`}
+ want := `auto-register returned HTTP 404: {"errors":["no such object"]}`
+ if got := ce.Error(); got != want {
+ t.Errorf("Error() = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("EmptyBody", func(t *testing.T) {
+ ce := &clientError{statusCode: 400, body: ""}
+ want := "auto-register returned HTTP 400: "
+ if got := ce.Error(); got != want {
+ t.Errorf("Error() = %q, want %q", got, want)
+ }
+ })
+
+ t.Run("ErrorsAsExtractsWrappedClientError", func(t *testing.T) {
+ ce := &clientError{statusCode: 401, body: "unauthorized"}
+ wrapped := fmt.Errorf("registration failed: %w", ce)
+ var got *clientError
+ if !errors.As(wrapped, &got) {
+ t.Fatal("errors.As failed to extract *clientError from wrapped error")
+ }
+ if got.statusCode != 401 || got.body != "unauthorized" {
+ t.Errorf("extracted *clientError = {statusCode:%d, body:%q}, want {401, unauthorized}", got.statusCode, got.body)
+ }
+ })
+
+ t.Run("ClientErrorHasNoUnwrapSoChainTerminates", func(t *testing.T) {
+ // clientError defines no Unwrap() method; its error chain must end at
+ // itself, so errors.Is against an unrelated sentinel is false.
+ ce := &clientError{statusCode: 403}
+ if errors.Is(ce, errors.New("unrelated")) {
+ t.Errorf("errors.Is(ce, unrelated) = true; want false (no Unwrap, no match)")
+ }
+ })
+}
+
+// TestBranchcov0722R2PermanentErrorUnwrap covers permanentError.Error()
+// (proxmox_setup.go:1207) and permanentError.Unwrap() (proxmox_setup.go:1208),
+// which is the only Unwrap() defined in this file. Both arms are exercised:
+// a present wrapped error and a nil wrapped error. errors.Is / errors.As are
+// asserted through the wrapper rather than by pointer comparison alone.
+func TestBranchcov0722R2PermanentErrorUnwrap(t *testing.T) {
+ t.Run("WrappedErrorPresent", func(t *testing.T) {
+ inner := &branchcovTestErr{msg: "malformed registration URL"}
+ pe := &permanentError{err: inner}
+
+ if got := pe.Unwrap(); got != inner {
+ t.Errorf("Unwrap() = %v, want %v", got, inner)
+ }
+ if got := pe.Error(); got != inner.msg {
+ t.Errorf("Error() = %q, want %q (delegates to wrapped error)", got, inner.msg)
+ }
+
+ // errors.Is walks Unwrap to locate the sentinel.
+ if !errors.Is(pe, inner) {
+ t.Errorf("errors.Is(pe, inner) = false; want true")
+ }
+
+ // errors.As extracts the concrete wrapped type through the chain.
+ var target *branchcovTestErr
+ if !errors.As(pe, &target) {
+ t.Fatal("errors.As failed to extract wrapped *branchcovTestErr")
+ }
+ if target != inner {
+ t.Errorf("errors.As extracted %p, want %p", target, inner)
+ }
+ })
+
+ t.Run("NilWrappedError", func(t *testing.T) {
+ pe := &permanentError{err: nil}
+
+ if got := pe.Unwrap(); got != nil {
+ t.Errorf("Unwrap() = %v, want nil", got)
+ }
+
+ // With a nil wrapped error the chain terminates, so errors.Is against
+ // any non-nil target is false. (Error() is deliberately not called:
+ // permanentError.Error delegates to err.Error(), which would panic on
+ // a nil err.)
+ if errors.Is(pe, errors.New("anything")) {
+ t.Errorf("errors.Is(pe, anything) = true; want false (chain is nil)")
+ }
+ })
+}
+
+// TestBranchcov0722R2AnnotateSMARTWithZFSPools covers annotateSMARTWithZFSPools
+// (zfs.go:145). Because the function mutates the caller's backing array in
+// place, every assertion is made on the original slice. The early-return arms
+// (nil/empty pools, nil/empty smartData), the pre-populated guard, the matching
+// arm and the non-matching arm are all driven, and the device-name normalisation
+// the source performs (lowercasing + /dev/ prefix stripping) is asserted
+// explicitly.
+func TestBranchcov0722R2AnnotateSMARTWithZFSPools(t *testing.T) {
+ t.Run("NilPoolsLeavesSliceUntouched", func(t *testing.T) {
+ data := []agentshost.DiskSMART{{Device: "sda"}, {Device: "sdb"}}
+ annotateSMARTWithZFSPools(data, nil)
+ if data[0].Pool != "" || data[1].Pool != "" {
+ t.Fatalf("nil pools mutated slice: %+v", data)
+ }
+ })
+
+ t.Run("EmptyPoolsLeavesSliceUntouched", func(t *testing.T) {
+ data := []agentshost.DiskSMART{{Device: "sda", Pool: ""}}
+ annotateSMARTWithZFSPools(data, map[string]string{})
+ if data[0].Pool != "" {
+ t.Fatalf("empty pools mutated slice: %+v", data)
+ }
+ })
+
+ t.Run("NilSmartDataIsNoOp", func(t *testing.T) {
+ annotateSMARTWithZFSPools(nil, map[string]string{"sda": "tank"})
+ // Reaching here without panicking is the assertion.
+ })
+
+ t.Run("EmptySmartDataIsNoOp", func(t *testing.T) {
+ annotateSMARTWithZFSPools([]agentshost.DiskSMART{}, map[string]string{"sda": "tank"})
+ // Reaching here without panicking is the assertion.
+ })
+
+ t.Run("PrePopulatedPoolIsLeftUntouched", func(t *testing.T) {
+ // The function skips entries whose Pool is already non-empty, so a
+ // caller that pre-populated Pool from another source is not clobbered
+ // even when the device matches a pool.
+ data := []agentshost.DiskSMART{{Device: "sda", Pool: "unraid"}}
+ annotateSMARTWithZFSPools(data, map[string]string{"sda": "tank"})
+ if data[0].Pool != "unraid" {
+ t.Errorf("pre-populated Pool was overwritten: got %q, want unraid", data[0].Pool)
+ }
+ })
+
+ t.Run("MatchingDeviceStampsPoolField", func(t *testing.T) {
+ data := []agentshost.DiskSMART{{Device: "sda"}}
+ annotateSMARTWithZFSPools(data, map[string]string{"sda": "tank"})
+ if data[0].Pool != "tank" {
+ t.Errorf("matching device not annotated: Pool = %q, want tank", data[0].Pool)
+ }
+ })
+
+ t.Run("DeviceNormalisationStripsDevPrefix", func(t *testing.T) {
+ // normalizeZFSMemberKeys strips a leading "/dev/" (and other by-path
+ // prefixes) before lookup, so /dev/sda must match a bare "sda" key.
+ data := []agentshost.DiskSMART{{Device: "/dev/sda"}}
+ annotateSMARTWithZFSPools(data, map[string]string{"sda": "tank"})
+ if data[0].Pool != "tank" {
+ t.Errorf("normalised /dev/sda did not match key %q: Pool = %q, want tank", "sda", data[0].Pool)
+ }
+ })
+
+ t.Run("DeviceNormalisationIsCaseInsensitive", func(t *testing.T) {
+ // The lookup lowercases the derived device name, so an upper-case
+ // device matches a lower-case pool key. (Note: the pool map's own keys
+ // are NOT normalised, so the key itself must already be lower case.)
+ data := []agentshost.DiskSMART{{Device: "/dev/SDA"}}
+ annotateSMARTWithZFSPools(data, map[string]string{"sda": "tank"})
+ if data[0].Pool != "tank" {
+ t.Errorf("upper-case device was not lower-cased for lookup: Pool = %q, want tank", data[0].Pool)
+ }
+ })
+
+ t.Run("NonMatchingDeviceStaysEmpty", func(t *testing.T) {
+ data := []agentshost.DiskSMART{{Device: "sdb"}}
+ annotateSMARTWithZFSPools(data, map[string]string{"sda": "tank"})
+ if data[0].Pool != "" {
+ t.Errorf("non-matching device was annotated: Pool = %q, want empty", data[0].Pool)
+ }
+ })
+
+ t.Run("OnlyMatchingEntriesAreMutatedMixedSlice", func(t *testing.T) {
+ data := []agentshost.DiskSMART{
+ {Device: "sda"},
+ {Device: "sdb"},
+ {Device: "sda", Pool: "preset"},
+ }
+ annotateSMARTWithZFSPools(data, map[string]string{"sda": "tank"})
+ if data[0].Pool != "tank" {
+ t.Errorf("data[0] (sda) not annotated: Pool = %q, want tank", data[0].Pool)
+ }
+ if data[1].Pool != "" {
+ t.Errorf("data[1] (sdb) unexpectedly annotated: Pool = %q, want empty", data[1].Pool)
+ }
+ if data[2].Pool != "preset" {
+ t.Errorf("data[2] (pre-populated) clobbered: Pool = %q, want preset", data[2].Pool)
+ }
+ })
+}
diff --git a/internal/hostagent/unraid_merge_branchcov0722am_test.go b/internal/hostagent/unraid_merge_branchcov0722am_test.go
new file mode 100644
index 0000000000..39990ed33f
--- /dev/null
+++ b/internal/hostagent/unraid_merge_branchcov0722am_test.go
@@ -0,0 +1,419 @@
+package hostagent
+
+import (
+ "testing"
+
+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
+)
+
+// These tests target mergeUnraidDiskINI, mergeUnraidDisk and defaultUnraidDiskName
+// in unraid.go, which previously had 0.0% coverage. They assert the real
+// branch behaviour of each function (nil/empty inputs, whitespace-only field
+// values, base/incoming precedence, keying and ordering) without modifying any
+// source file.
+
+// branchcovStringMerge exercises the whitespace-guarded merge rule shared by
+// every TrimSpace-protected string field on UnraidDisk. Each guarded field gets
+// its own subtest that delegates here so the three arms (empty keeps base,
+// whitespace-only keeps base, populated wins and is trimmed) are all hit.
+func branchcovStringMerge(
+ t *testing.T,
+ set func(*agentshost.UnraidDisk, string),
+ get func(agentshost.UnraidDisk) string,
+) {
+ t.Helper()
+ const baseVal = "baseval"
+ newBase := func() agentshost.UnraidDisk {
+ var d agentshost.UnraidDisk
+ set(&d, baseVal)
+ return d
+ }
+ incoming := func(v string) agentshost.UnraidDisk {
+ var d agentshost.UnraidDisk
+ set(&d, v)
+ return d
+ }
+ if got := get(mergeUnraidDisk(newBase(), incoming(""))); got != baseVal {
+ t.Errorf("empty incoming keeps base: got %q, want %q", got, baseVal)
+ }
+ if got := get(mergeUnraidDisk(newBase(), incoming(" "))); got != baseVal {
+ t.Errorf("whitespace-only incoming keeps base: got %q, want %q", got, baseVal)
+ }
+ if got := get(mergeUnraidDisk(newBase(), incoming(" fresh "))); got != "fresh" {
+ t.Errorf("populated incoming wins and is trimmed: got %q, want fresh", got)
+ }
+}
+
+// branchcovInt64Merge exercises the "> 0" merge guard shared by the int64
+// numeric fields. Each guarded field gets its own subtest that delegates here.
+func branchcovInt64Merge(
+ t *testing.T,
+ set func(*agentshost.UnraidDisk, int64),
+ get func(agentshost.UnraidDisk) int64,
+) {
+ t.Helper()
+ const baseVal int64 = 100
+ newBase := func() agentshost.UnraidDisk {
+ var d agentshost.UnraidDisk
+ set(&d, baseVal)
+ return d
+ }
+ incoming := func(v int64) agentshost.UnraidDisk {
+ var d agentshost.UnraidDisk
+ set(&d, v)
+ return d
+ }
+ if got := get(mergeUnraidDisk(newBase(), incoming(0))); got != baseVal {
+ t.Errorf("zero incoming keeps base: got %d, want %d", got, baseVal)
+ }
+ if got := get(mergeUnraidDisk(newBase(), incoming(-9))); got != baseVal {
+ t.Errorf("negative incoming keeps base: got %d, want %d", got, baseVal)
+ }
+ if got := get(mergeUnraidDisk(newBase(), incoming(42))); got != 42 {
+ t.Errorf("positive incoming wins: got %d, want 42", got)
+ }
+}
+
+func TestBranchcov0722R2MergeUnraidDiskINI(t *testing.T) {
+ t.Run("NilStorageAndNilIniAllocatesEmptyStorage", func(t *testing.T) {
+ got := mergeUnraidDiskINI(nil, nil)
+ if got == nil {
+ t.Fatal("expected non-nil storage allocated for nil input")
+ }
+ if len(got.Disks) != 0 {
+ t.Fatalf("expected no disks, got %+v", got.Disks)
+ }
+ })
+
+ t.Run("NilStorageAndEmptyIniSliceAllocatesEmptyStorage", func(t *testing.T) {
+ got := mergeUnraidDiskINI(nil, []agentshost.UnraidDisk{})
+ if got == nil {
+ t.Fatal("expected non-nil storage allocated for nil input with empty slice")
+ }
+ if len(got.Disks) != 0 {
+ t.Fatalf("expected no disks, got %+v", got.Disks)
+ }
+ })
+
+ t.Run("NilStorageWithIniDisksBuildsStorageSortedBySlot", func(t *testing.T) {
+ iniDisks := []agentshost.UnraidDisk{
+ {Name: "disk3", Slot: 3},
+ {Name: "disk1", Slot: 1},
+ {Name: "disk2", Slot: 2},
+ }
+ got := mergeUnraidDiskINI(nil, iniDisks)
+ if got == nil {
+ t.Fatal("expected non-nil storage")
+ }
+ if len(got.Disks) != 3 {
+ t.Fatalf("disk count = %d, want 3: %+v", len(got.Disks), got.Disks)
+ }
+ wantSlots := []int{1, 2, 3}
+ for i, want := range wantSlots {
+ if got.Disks[i].Slot != want {
+ t.Fatalf("disks[%d].Slot = %d, want %d (sorted ascending)", i, got.Disks[i].Slot, want)
+ }
+ }
+ })
+
+ t.Run("EmptyIniReturnsSamePointerUnmutated", func(t *testing.T) {
+ original := &agentshost.UnraidStorage{
+ ArrayStarted: true,
+ ArrayState: "STARTED",
+ Disks: []agentshost.UnraidDisk{
+ {Name: "disk1", Slot: 1},
+ },
+ }
+ originalSnapshot := append([]agentshost.UnraidDisk(nil), original.Disks...)
+ got := mergeUnraidDiskINI(original, nil)
+ if got != original {
+ t.Fatalf("expected same pointer returned for empty ini, got %p want %p", got, original)
+ }
+ if !got.ArrayStarted || got.ArrayState != "STARTED" {
+ t.Fatalf("non-Disk fields not preserved: %+v", got)
+ }
+ if len(got.Disks) != len(originalSnapshot) {
+ t.Fatalf("Disks mutated on empty ini: got %+v", got.Disks)
+ }
+ })
+
+ t.Run("MatchingSlotMergesWithoutDuplicating", func(t *testing.T) {
+ storage := &agentshost.UnraidStorage{
+ Disks: []agentshost.UnraidDisk{
+ {Name: "disk1", Slot: 1, SizeBytes: 1000},
+ },
+ }
+ iniDisks := []agentshost.UnraidDisk{
+ {Slot: 1, Serial: "SER123", Status: "online"},
+ }
+ got := mergeUnraidDiskINI(storage, iniDisks)
+ if len(got.Disks) != 1 {
+ t.Fatalf("expected merged disk count 1 (no duplicate), got %d: %+v", len(got.Disks), got.Disks)
+ }
+ d := got.Disks[0]
+ if d.Name != "disk1" {
+ t.Errorf("Name = %q, want disk1 (base kept when incoming empty)", d.Name)
+ }
+ if d.SizeBytes != 1000 {
+ t.Errorf("SizeBytes = %d, want 1000 (base kept when incoming zero)", d.SizeBytes)
+ }
+ if d.Serial != "SER123" {
+ t.Errorf("Serial = %q, want SER123 (incoming wins)", d.Serial)
+ }
+ if d.Status != "online" {
+ t.Errorf("Status = %q, want online (incoming wins)", d.Status)
+ }
+ })
+
+ t.Run("NewSlotAppendsDisk", func(t *testing.T) {
+ storage := &agentshost.UnraidStorage{
+ Disks: []agentshost.UnraidDisk{
+ {Name: "disk1", Slot: 1},
+ },
+ }
+ iniDisks := []agentshost.UnraidDisk{
+ {Name: "disk2", Slot: 2, Serial: "SER2"},
+ }
+ got := mergeUnraidDiskINI(storage, iniDisks)
+ if len(got.Disks) != 2 {
+ t.Fatalf("expected 2 disks, got %d: %+v", len(got.Disks), got.Disks)
+ }
+ if got.Disks[0].Slot != 1 || got.Disks[1].Slot != 2 {
+ t.Fatalf("unexpected slot order: %+v", got.Disks)
+ }
+ if got.Disks[1].Name != "disk2" || got.Disks[1].Serial != "SER2" {
+ t.Errorf("appended disk not preserved: %+v", got.Disks[1])
+ }
+ })
+
+ t.Run("IniDiskLowerSlotSortedBeforeExisting", func(t *testing.T) {
+ storage := &agentshost.UnraidStorage{
+ Disks: []agentshost.UnraidDisk{
+ {Name: "disk5", Slot: 5},
+ },
+ }
+ iniDisks := []agentshost.UnraidDisk{
+ {Name: "parity", Slot: 0},
+ }
+ got := mergeUnraidDiskINI(storage, iniDisks)
+ if len(got.Disks) != 2 {
+ t.Fatalf("expected 2 disks, got %d", len(got.Disks))
+ }
+ if got.Disks[0].Slot != 0 || got.Disks[0].Name != "parity" {
+ t.Fatalf("incoming slot 0 not sorted first: %+v", got.Disks[0])
+ }
+ if got.Disks[1].Slot != 5 || got.Disks[1].Name != "disk5" {
+ t.Fatalf("existing slot 5 not second: %+v", got.Disks[1])
+ }
+ })
+
+ t.Run("MixOfMatchingAndNewSlotsStablySorted", func(t *testing.T) {
+ storage := &agentshost.UnraidStorage{
+ Disks: []agentshost.UnraidDisk{
+ {Name: "disk1", Slot: 1, SizeBytes: 500},
+ {Name: "disk3", Slot: 3, SizeBytes: 3000},
+ },
+ }
+ iniDisks := []agentshost.UnraidDisk{
+ {Slot: 1, Serial: "S1"},
+ {Slot: 2, Name: "disk2", Serial: "S2"},
+ }
+ got := mergeUnraidDiskINI(storage, iniDisks)
+ if len(got.Disks) != 3 {
+ t.Fatalf("expected 3 disks, got %d: %+v", len(got.Disks), got.Disks)
+ }
+ if got.Disks[0].Slot != 1 || got.Disks[0].Name != "disk1" || got.Disks[0].Serial != "S1" {
+ t.Errorf("slot 1 merge unexpected: %+v", got.Disks[0])
+ }
+ if got.Disks[0].SizeBytes != 500 {
+ t.Errorf("slot 1 base SizeBytes not kept: %d", got.Disks[0].SizeBytes)
+ }
+ if got.Disks[1].Slot != 2 || got.Disks[1].Name != "disk2" || got.Disks[1].Serial != "S2" {
+ t.Errorf("slot 2 append unexpected: %+v", got.Disks[1])
+ }
+ if got.Disks[2].Slot != 3 || got.Disks[2].SizeBytes != 3000 || got.Disks[2].Name != "disk3" {
+ t.Errorf("slot 3 untouched unexpected: %+v", got.Disks[2])
+ }
+ })
+
+ t.Run("MutatesInputStorageDisksFieldAndReturnsSamePointer", func(t *testing.T) {
+ storage := &agentshost.UnraidStorage{
+ Disks: []agentshost.UnraidDisk{
+ {Name: "disk1", Slot: 1},
+ },
+ }
+ originalLen := len(storage.Disks)
+ got := mergeUnraidDiskINI(storage, []agentshost.UnraidDisk{{Name: "disk2", Slot: 2}})
+ if got != storage {
+ t.Fatalf("expected the same pointer returned (in-place mutation), got %p want %p", got, storage)
+ }
+ if len(storage.Disks) == originalLen {
+ t.Fatalf("expected input storage.Disks to be mutated, still len %d", len(storage.Disks))
+ }
+ if len(storage.Disks) != 2 {
+ t.Fatalf("input storage.Disks len = %d, want 2: %+v", len(storage.Disks), storage.Disks)
+ }
+ })
+}
+
+func TestBranchcov0722R2MergeUnraidDisk(t *testing.T) {
+ t.Run("Name", func(t *testing.T) {
+ branchcovStringMerge(t,
+ func(d *agentshost.UnraidDisk, v string) { d.Name = v },
+ func(d agentshost.UnraidDisk) string { return d.Name })
+ })
+ t.Run("Device", func(t *testing.T) {
+ branchcovStringMerge(t,
+ func(d *agentshost.UnraidDisk, v string) { d.Device = v },
+ func(d agentshost.UnraidDisk) string { return d.Device })
+ })
+ t.Run("Role", func(t *testing.T) {
+ branchcovStringMerge(t,
+ func(d *agentshost.UnraidDisk, v string) { d.Role = v },
+ func(d agentshost.UnraidDisk) string { return d.Role })
+ })
+ t.Run("Status", func(t *testing.T) {
+ branchcovStringMerge(t,
+ func(d *agentshost.UnraidDisk, v string) { d.Status = v },
+ func(d agentshost.UnraidDisk) string { return d.Status })
+ })
+ t.Run("RawStatus", func(t *testing.T) {
+ branchcovStringMerge(t,
+ func(d *agentshost.UnraidDisk, v string) { d.RawStatus = v },
+ func(d agentshost.UnraidDisk) string { return d.RawStatus })
+ })
+ t.Run("Model", func(t *testing.T) {
+ branchcovStringMerge(t,
+ func(d *agentshost.UnraidDisk, v string) { d.Model = v },
+ func(d agentshost.UnraidDisk) string { return d.Model })
+ })
+ t.Run("Serial", func(t *testing.T) {
+ branchcovStringMerge(t,
+ func(d *agentshost.UnraidDisk, v string) { d.Serial = v },
+ func(d agentshost.UnraidDisk) string { return d.Serial })
+ })
+ t.Run("Filesystem", func(t *testing.T) {
+ branchcovStringMerge(t,
+ func(d *agentshost.UnraidDisk, v string) { d.Filesystem = v },
+ func(d agentshost.UnraidDisk) string { return d.Filesystem })
+ })
+ t.Run("Transport", func(t *testing.T) {
+ branchcovStringMerge(t,
+ func(d *agentshost.UnraidDisk, v string) { d.Transport = v },
+ func(d agentshost.UnraidDisk) string { return d.Transport })
+ })
+
+ t.Run("SizeBytes", func(t *testing.T) {
+ branchcovInt64Merge(t,
+ func(d *agentshost.UnraidDisk, v int64) { d.SizeBytes = v },
+ func(d agentshost.UnraidDisk) int64 { return d.SizeBytes })
+ })
+ t.Run("UsedBytes", func(t *testing.T) {
+ branchcovInt64Merge(t,
+ func(d *agentshost.UnraidDisk, v int64) { d.UsedBytes = v },
+ func(d agentshost.UnraidDisk) int64 { return d.UsedBytes })
+ })
+ t.Run("FreeBytes", func(t *testing.T) {
+ branchcovInt64Merge(t,
+ func(d *agentshost.UnraidDisk, v int64) { d.FreeBytes = v },
+ func(d agentshost.UnraidDisk) int64 { return d.FreeBytes })
+ })
+ t.Run("ReadCount", func(t *testing.T) {
+ branchcovInt64Merge(t,
+ func(d *agentshost.UnraidDisk, v int64) { d.ReadCount = v },
+ func(d agentshost.UnraidDisk) int64 { return d.ReadCount })
+ })
+ t.Run("WriteCount", func(t *testing.T) {
+ branchcovInt64Merge(t,
+ func(d *agentshost.UnraidDisk, v int64) { d.WriteCount = v },
+ func(d agentshost.UnraidDisk) int64 { return d.WriteCount })
+ })
+ t.Run("ErrorCount", func(t *testing.T) {
+ branchcovInt64Merge(t,
+ func(d *agentshost.UnraidDisk, v int64) { d.ErrorCount = v },
+ func(d agentshost.UnraidDisk) int64 { return d.ErrorCount })
+ })
+
+ t.Run("Temperature", func(t *testing.T) {
+ const baseVal = 100
+ newBase := func() agentshost.UnraidDisk {
+ return agentshost.UnraidDisk{Temperature: baseVal}
+ }
+ if got := mergeUnraidDisk(newBase(), agentshost.UnraidDisk{Temperature: 0}).Temperature; got != baseVal {
+ t.Errorf("zero incoming keeps base: got %d, want %d", got, baseVal)
+ }
+ if got := mergeUnraidDisk(newBase(), agentshost.UnraidDisk{Temperature: -9}).Temperature; got != baseVal {
+ t.Errorf("negative incoming keeps base: got %d, want %d", got, baseVal)
+ }
+ if got := mergeUnraidDisk(newBase(), agentshost.UnraidDisk{Temperature: 42}).Temperature; got != 42 {
+ t.Errorf("positive incoming wins: got %d, want 42", got)
+ }
+ })
+
+ // SpunDown has NO guard: it is unconditionally overwritten by incoming,
+ // even when incoming is the zero value (false). This subtest documents that
+ // real behaviour, which differs from every other field in the merge.
+ t.Run("SpunDownAlwaysOverwrites", func(t *testing.T) {
+ if got := mergeUnraidDisk(agentshost.UnraidDisk{SpunDown: true}, agentshost.UnraidDisk{SpunDown: false}).SpunDown; got {
+ t.Errorf("true base, false incoming: got %v, want false (unconditional overwrite)", got)
+ }
+ if got := mergeUnraidDisk(agentshost.UnraidDisk{SpunDown: false}, agentshost.UnraidDisk{SpunDown: true}).SpunDown; !got {
+ t.Errorf("false base, true incoming: got %v, want true", got)
+ }
+ // The zero-value incoming (false) still clobbers a populated base.
+ if got := mergeUnraidDisk(agentshost.UnraidDisk{SpunDown: true}, agentshost.UnraidDisk{}).SpunDown; got {
+ t.Errorf("true base, zero incoming: got %v, want false (zero-value clobbers base)", got)
+ }
+ })
+
+ // Slot uses a composite rule: out.Slot = incoming.Slot when
+ // incoming.Slot > 0 OR out.Slot == 0; otherwise the base slot is kept.
+ t.Run("SlotCompositeRule", func(t *testing.T) {
+ if got := mergeUnraidDisk(agentshost.UnraidDisk{Slot: 5}, agentshost.UnraidDisk{Slot: 7}).Slot; got != 7 {
+ t.Errorf("positive incoming wins: got %d, want 7", got)
+ }
+ if got := mergeUnraidDisk(agentshost.UnraidDisk{Slot: 5}, agentshost.UnraidDisk{Slot: 0}).Slot; got != 5 {
+ t.Errorf("zero incoming, non-zero base keeps base: got %d, want 5", got)
+ }
+ if got := mergeUnraidDisk(agentshost.UnraidDisk{Slot: 5}, agentshost.UnraidDisk{Slot: -1}).Slot; got != 5 {
+ t.Errorf("negative incoming, non-zero base keeps base: got %d, want 5", got)
+ }
+ if got := mergeUnraidDisk(agentshost.UnraidDisk{Slot: 0}, agentshost.UnraidDisk{Slot: 0}).Slot; got != 0 {
+ t.Errorf("zero base, zero incoming: got %d, want 0 (out.Slot==0 branch takes incoming)", got)
+ }
+ // When base slot is 0, the out.Slot==0 branch takes incoming even if it
+ // is negative.
+ if got := mergeUnraidDisk(agentshost.UnraidDisk{Slot: 0}, agentshost.UnraidDisk{Slot: -3}).Slot; got != -3 {
+ t.Errorf("zero base, negative incoming: got %d, want -3 (out.Slot==0 branch takes incoming)", got)
+ }
+ })
+}
+
+func TestBranchcov0722R2DefaultUnraidDiskName(t *testing.T) {
+ tests := []struct {
+ name string
+ role string
+ idx int
+ want string
+ }{
+ {"parity index 0 returns bare parity", "parity", 0, "parity"},
+ {"parity negative index returns bare parity", "parity", -1, "parity"},
+ {"parity positive index appends number", "parity", 1, "parity1"},
+ {"parity large index appends number", "parity", 29, "parity29"},
+ {"data index 0 formats as disk0", "data", 0, "disk0"},
+ {"data index 1 formats as disk1", "data", 1, "disk1"},
+ {"data large index formats number", "data", 1234, "disk1234"},
+ {"unknown role cache returns empty", "cache", 30, ""},
+ {"unknown role flash returns empty", "flash", 1, ""},
+ {"empty role returns empty", "", 0, ""},
+ {"uppercase PARITY is default arm (case sensitive)", "PARITY", 1, ""},
+ {"mixed-case Parity is default arm (case sensitive)", "Parity", 1, ""},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := defaultUnraidDiskName(tt.role, tt.idx); got != tt.want {
+ t.Errorf("defaultUnraidDiskName(%q, %d) = %q, want %q", tt.role, tt.idx, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/internal/updates/retryable_error_branchcov0722am_test.go b/internal/updates/retryable_error_branchcov0722am_test.go
new file mode 100644
index 0000000000..b5ab6fa468
--- /dev/null
+++ b/internal/updates/retryable_error_branchcov0722am_test.go
@@ -0,0 +1,69 @@
+package updates
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "testing"
+)
+
+type branchcov0722R2NetError struct {
+ message string
+ timeout bool
+ temporary bool
+}
+
+func (e *branchcov0722R2NetError) Error() string { return e.message }
+func (e *branchcov0722R2NetError) Timeout() bool { return e.timeout }
+func (e *branchcov0722R2NetError) Temporary() bool { return e.temporary }
+
+var _ net.Error = (*branchcov0722R2NetError)(nil)
+
+func TestBranchcov0722R2IsRetryableUpdateRequestError(t *testing.T) {
+ wrappedCanceled := fmt.Errorf("upstream cancelled: %w", context.Canceled)
+ wrappedDeadline := fmt.Errorf("upstream deadline: %w", context.DeadlineExceeded)
+ wrappedEOF := fmt.Errorf("read failed: %w", io.EOF)
+ wrappedUnexpectedEOF := fmt.Errorf("short read: %w", io.ErrUnexpectedEOF)
+ wrappedNetErr := fmt.Errorf("dial failed: %w", &branchcov0722R2NetError{message: "i/o timeout", timeout: true})
+
+ cases := []struct {
+ name string
+ err error
+ want bool
+ }{
+ {"nil error returns false", nil, false},
+ {"context canceled directly returns false", context.Canceled, false},
+ {"context deadline exceeded directly returns false", context.DeadlineExceeded, false},
+ {"context canceled wrapped one level with %w still returns false", wrappedCanceled, false},
+ {"context deadline exceeded wrapped one level with %w still returns false", wrappedDeadline, false},
+ {"net.Error implementing timeout returns true", &branchcov0722R2NetError{message: "dial tcp: i/o timeout", timeout: true, temporary: true}, true},
+ {"net.Error implementing only temporary returns true", &branchcov0722R2NetError{message: "dial tcp: temporary", timeout: false, temporary: true}, true},
+ {"net.Error wrapped one level with %w still returns true via errors.As", wrappedNetErr, true},
+ {"io.EOF directly returns true", io.EOF, true},
+ {"io.ErrUnexpectedEOF directly returns true", io.ErrUnexpectedEOF, true},
+ {"io.EOF wrapped one level with %w returns true", wrappedEOF, true},
+ {"io.ErrUnexpectedEOF wrapped one level with %w returns true", wrappedUnexpectedEOF, true},
+ {"string fragment connection reset returns true", errors.New("read tcp: connection reset by peer"), true},
+ {"string fragment connection refused returns true", errors.New("dial tcp: connection refused"), true},
+ {"string fragment connection aborted returns true", errors.New("write tcp: connection aborted"), true},
+ {"string fragment broken pipe returns true", errors.New("write tcp: broken pipe"), true},
+ {"string fragment temporary failure returns true", errors.New("temporary failure in name resolution"), true},
+ {"string fragment timeout returns true", errors.New("operation timeout reached"), true},
+ {"tls handshake message matches the earlier timeout fragment returns true", errors.New("net/http: TLS handshake timeout"), true},
+ {"string fragment http2 server sent goaway returns true", errors.New("http2: server sent GOAWAY and closed the connection"), true},
+ {"mixed case fragment lowercased before matching returns true", errors.New("CONNECTION REFUSED by host"), true},
+ {"plain unrelated error returns false", errors.New("something completely different happened"), false},
+ {"unrelated error with no matching fragment returns false", errors.New("permission denied"), false},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := isRetryableUpdateRequestError(tc.err)
+ if got != tc.want {
+ t.Fatalf("isRetryableUpdateRequestError(%v) = %v, want %v", tc.err, got, tc.want)
+ }
+ })
+ }
+}