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.

15.5 KB
Raw Blame
package storagehealth

import (
	"testing"

	"github.com/rcourtman/pulse-go-rewrite/internal/models"
	"github.com/rcourtman/pulse-go-rewrite/pkg/diskinventory"
)

// --- AssessSample: comprehensive branch coverage ---

func TestAssessSample_HealthyDisk(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:  "PASSED",
		Wearout: 80,
	})
	if assessment.Level != RiskHealthy {
		t.Errorf("expected healthy, got %s", assessment.Level)
	}
	if len(assessment.Reasons) != 0 {
		t.Errorf("expected 0 reasons, got %d", len(assessment.Reasons))
	}
}

func TestAssessSampleWithThresholdsTunesAndDisablesSMARTRules(t *testing.T) {
	thresholds := DefaultSMARTThresholds()
	thresholds.HealthFailure = false
	thresholds.PendingSectors = 3
	thresholds.MediaErrors = 0
	thresholds.LifeWarning = 20
	thresholds.LifeCritical = 10

	assessment := AssessSampleWithThresholds(Sample{
		Health:         "FAILED",
		PendingSectors: 2,
		MediaErrors:    50,
		Wearout:        15,
		WearoutKnown:   true,
	}, thresholds)

	if assessment.Level != RiskWarning {
		t.Fatalf("Level = %q, want warning from configured life threshold", assessment.Level)
	}
	if len(assessment.Reasons) != 1 || assessment.Reasons[0].Code != "wearout_low" {
		t.Fatalf("Reasons = %+v, want only wearout_low", assessment.Reasons)
	}

	assessment = AssessSampleWithThresholds(Sample{PendingSectors: 3}, thresholds)
	if assessment.Level != RiskCritical || len(assessment.Reasons) != 1 || assessment.Reasons[0].Code != "pending_sectors" {
		t.Fatalf("threshold boundary did not trigger: %+v", assessment)
	}
}

func TestAssessSample_FailedHealthStatus(t *testing.T) {
	assessment := AssessSample(Sample{
		Health: "FAILED",
	})
	if assessment.Level != RiskCritical {
		t.Errorf("expected critical for FAILED health, got %s", assessment.Level)
	}
	found := false
	for _, r := range assessment.Reasons {
		if r.Code == "health_status" {
			found = true
			break
		}
	}
	if !found {
		t.Error("expected health_status reason")
	}
}

func TestAssessSample_PassedHealthDoesNotTrigger(t *testing.T) {
	for _, health := range []string{"PASSED", "OK", "UNKNOWN", ""} {
		assessment := AssessSample(Sample{Health: health})
		for _, r := range assessment.Reasons {
			if r.Code == "health_status" {
				t.Errorf("health %q should not trigger health_status reason", health)
			}
		}
	}
}

func TestAssessSample_FailedHealthWithFirmwareBug(t *testing.T) {
	assessment := AssessSample(Sample{
		Model:  "Samsung SSD 980 Pro",
		Health: "FAILED",
	})
	// Known firmware bug should suppress the FAILED health escalation.
	for _, r := range assessment.Reasons {
		if r.Code == "health_status" {
			t.Error("Samsung 980 FAILED should be suppressed by firmware bug detection")
		}
	}
}

func TestAssessSample_PendingSectors(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:         "PASSED",
		PendingSectors: 5,
	})
	if assessment.Level != RiskCritical {
		t.Errorf("expected critical for pending sectors, got %s", assessment.Level)
	}
	found := false
	for _, r := range assessment.Reasons {
		if r.Code == "pending_sectors" && r.Severity == RiskCritical {
			found = true
		}
	}
	if !found {
		t.Error("expected pending_sectors reason at critical severity")
	}
}

func TestAssessSample_OfflineUncorrectable(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:               "PASSED",
		OfflineUncorrectable: 2,
	})
	if assessment.Level != RiskCritical {
		t.Errorf("expected critical for offline uncorrectable, got %s", assessment.Level)
	}
}

func TestAssessSample_MediaErrors(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:      "PASSED",
		MediaErrors: 1,
	})
	if assessment.Level != RiskCritical {
		t.Errorf("expected critical for media errors, got %s", assessment.Level)
	}
}

func TestAssessSample_WearoutCritical(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:  "PASSED",
		Wearout: 3, // <=5 should be critical
	})
	if assessment.Level != RiskCritical {
		t.Errorf("expected critical for wearout=3, got %s", assessment.Level)
	}
	found := false
	for _, r := range assessment.Reasons {
		if r.Code == "wearout_low" && r.Severity == RiskCritical {
			found = true
		}
	}
	if !found {
		t.Error("expected wearout_low reason at critical severity")
	}
}

func TestAssessSample_ReportedZeroWearoutIsCritical(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:       "PASSED",
		Wearout:      0,
		WearoutKnown: true,
	})
	if assessment.Level != RiskCritical {
		t.Fatalf("expected reported wearout=0 to be critical, got %s", assessment.Level)
	}
}

func TestAssessSample_UnreportedZeroWearoutIsNeutral(t *testing.T) {
	assessment := AssessSample(Sample{Health: "PASSED"})
	if assessment.Level != RiskHealthy {
		t.Fatalf("expected zero-value unreported wearout to remain neutral, got %s", assessment.Level)
	}
}

func TestAssessPhysicalDisk_PercentageUsedProvesZeroLifeOnSATASSD(t *testing.T) {
	percentageUsed := 100
	assessment := AssessPhysicalDisk(models.PhysicalDisk{
		Type:    "sata",
		Health:  "PASSED",
		Wearout: 0,
		SmartAttributes: &models.SMARTAttributes{
			PercentageUsed: &percentageUsed,
		},
	})
	if assessment.Level != RiskCritical {
		t.Fatalf("reported percentage-used=100 should prove zero remaining life, got %s", assessment.Level)
	}
}

func TestAssessPhysicalDisk_ReportedZeroWearoutUsesMediaType(t *testing.T) {
	if assessment := AssessPhysicalDisk(models.PhysicalDisk{
		Type:    "nvme",
		Health:  "PASSED",
		Wearout: 0,
	}); assessment.Level != RiskCritical {
		t.Fatalf("reported NVMe wearout=0 should be critical, got %+v", assessment)
	}
	if assessment := AssessPhysicalDisk(models.PhysicalDisk{
		Type:    "sata",
		Health:  "PASSED",
		Wearout: 0,
	}); assessment.Level != RiskHealthy {
		t.Fatalf("SATA transport without endurance evidence should remain neutral, got %+v", assessment)
	}
}

func TestRemainingLifeFromPercentageUsedClampsControllerValues(t *testing.T) {
	for _, test := range []struct {
		used int
		want int
	}{
		{used: -4, want: -1},
		{used: 0, want: 100},
		{used: 95, want: 5},
		{used: 100, want: 0},
		{used: 143, want: 0},
	} {
		if got := RemainingLifeFromPercentageUsed(test.used); got != test.want {
			t.Fatalf("RemainingLifeFromPercentageUsed(%d) = %d, want %d", test.used, got, test.want)
		}
	}
}

func TestAssessPhysicalDisk_InvalidPercentageUsedRemainsUnknown(t *testing.T) {
	percentageUsed := -4
	assessment := AssessPhysicalDisk(models.PhysicalDisk{
		Type: "nvme",
		SmartAttributes: &models.SMARTAttributes{
			PercentageUsed: &percentageUsed,
		},
	})

	if assessment.Level != RiskHealthy || len(assessment.Reasons) != 0 {
		t.Fatalf("invalid percentage used should remain neutral, got %+v", assessment)
	}
}

func TestAssessSample_WearoutWarning(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:  "PASSED",
		Wearout: 8, // >5, <10 should be warning
	})
	if assessment.Level != RiskWarning {
		t.Errorf("expected warning for wearout=8, got %s", assessment.Level)
	}
}

func TestAssessSample_WearoutHealthy(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:  "PASSED",
		Wearout: 50,
	})
	for _, r := range assessment.Reasons {
		if r.Code == "wearout_low" {
			t.Error("wearout=50 should not trigger wearout_low")
		}
	}
}

func TestAssessSample_NVMeAvailableSpareCritical(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:         "PASSED",
		AvailableSpare: 8, // <=10 critical
	})
	if assessment.Level != RiskCritical {
		t.Errorf("expected critical for available spare=8, got %s", assessment.Level)
	}
}

func TestAssessSample_NVMeAvailableSpareWarning(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:         "PASSED",
		AvailableSpare: 15, // >10, <20 warning
	})
	if assessment.Level != RiskWarning {
		t.Errorf("expected warning for available spare=15, got %s", assessment.Level)
	}
}

func TestAssessSample_NVMeAvailableSpareHealthy(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:         "PASSED",
		AvailableSpare: 50,
	})
	for _, r := range assessment.Reasons {
		if r.Code == "nvme_available_spare_low" {
			t.Error("available spare=50 should not trigger reason")
		}
	}
}

func TestAssessSample_NVMePercentageUsedCritical(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:         "PASSED",
		PercentageUsed: 97, // >=95 critical
	})
	if assessment.Level != RiskCritical {
		t.Errorf("expected critical for percentage used=97, got %s", assessment.Level)
	}
}

func TestAssessSample_NVMePercentageUsedWarning(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:         "PASSED",
		PercentageUsed: 92, // >=90, <95 warning
	})
	if assessment.Level != RiskWarning {
		t.Errorf("expected warning for percentage used=92, got %s", assessment.Level)
	}
}

func TestAssessSample_ReallocatedSectors(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:             "PASSED",
		ReallocatedSectors: 4,
	})
	if assessment.Level != RiskWarning {
		t.Errorf("expected warning for reallocated sectors, got %s", assessment.Level)
	}
	found := false
	for _, r := range assessment.Reasons {
		if r.Code == "reallocated_sectors" && r.Severity == RiskWarning {
			found = true
		}
	}
	if !found {
		t.Error("expected reallocated_sectors at warning severity")
	}
}

func TestAssessSample_CRCErrors(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:        "PASSED",
		UDMACRCErrors: 10,
	})
	if assessment.Level != RiskMonitor {
		t.Errorf("expected monitor for CRC errors, got %s", assessment.Level)
	}
}

func TestAssessSample_MultipleIssuesTakesHighest(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:             "PASSED",
		ReallocatedSectors: 1,  // warning
		PendingSectors:     1,  // critical
		UDMACRCErrors:      10, // monitor
	})
	if assessment.Level != RiskCritical {
		t.Errorf("expected critical (highest), got %s", assessment.Level)
	}
	if len(assessment.Reasons) != 3 {
		t.Errorf("expected 3 reasons, got %d", len(assessment.Reasons))
	}
}

func TestAssessSample_ReasonsSortedBySeverityDescending(t *testing.T) {
	assessment := AssessSample(Sample{
		Health:             "PASSED",
		PendingSectors:     1,  // critical
		UDMACRCErrors:      10, // monitor
		ReallocatedSectors: 1,  // warning
		WearoutKnown:       true,
		Wearout:            8, // warning
	})
	for i := 1; i < len(assessment.Reasons); i++ {
		prevRank := severityRank(assessment.Reasons[i-1].Severity)
		currRank := severityRank(assessment.Reasons[i].Severity)
		if prevRank < currRank {
			t.Errorf("reasons should be sorted by severity descending at position %d: %s (%d) < %s (%d)",
				i, assessment.Reasons[i-1].Severity, prevRank, assessment.Reasons[i].Severity, currRank)
		}
	}
}

// --- HasKnownFirmwareBug ---

func TestHasKnownFirmwareBug(t *testing.T) {
	tests := []struct {
		model    string
		expected bool
	}{
		{"Samsung SSD 980 Pro 1TB", true},
		{"SAMSUNG SSD 980 PRO", true},
		{"samsung ssd 990 evo", true},
		{"Samsung 980 500G", true},
		{"Samsung 990 Pro 2TB", true},
		{"Crucial MX500", false},
		{"WD Blue SN570", false},
		{"", false},
		{"Samsung SSD 870 EVO", false},
	}
	for _, tt := range tests {
		got := HasKnownFirmwareBug(tt.model)
		if got != tt.expected {
			t.Errorf("HasKnownFirmwareBug(%q) = %v, want %v", tt.model, got, tt.expected)
		}
	}
}

// --- severityRank ---

func TestSeverityRank_Ordering(t *testing.T) {
	if severityRank(RiskHealthy) >= severityRank(RiskMonitor) {
		t.Error("healthy should rank lower than monitor")
	}
	if severityRank(RiskMonitor) >= severityRank(RiskWarning) {
		t.Error("monitor should rank lower than warning")
	}
	if severityRank(RiskWarning) >= severityRank(RiskCritical) {
		t.Error("warning should rank lower than critical")
	}
}

func TestSeverityRank_UnknownIsZero(t *testing.T) {
	if severityRank("bogus") != 0 {
		t.Error("unknown level should rank 0")
	}
}

// --- normalizeHealth ---

func TestNormalizeHealth(t *testing.T) {
	tests := []struct {
		input    string
		expected string
	}{
		{"passed", "PASSED"},
		{" OK ", "OK"},
		{"FAILED", "FAILED"},
		{"", ""},
	}
	for _, tt := range tests {
		got := normalizeHealth(tt.input)
		if got != tt.expected {
			t.Errorf("normalizeHealth(%q) = %q, want %q", tt.input, got, tt.expected)
		}
	}
}

// --- WearoutReported ---

// Wearout has two distinct absent states and one real zero. -1 is the
// canonical unreported sentinel, and 0 is genuine evidence only from a device
// that reports endurance at all. Rotational disks never do, so a 0 from one is
// absence rather than a spent disk. Every consumer gates on this single
// predicate so the UI and the alert path cannot disagree about the same disk.
func TestWearoutReported(t *testing.T) {
	tests := []struct {
		name     string
		wearout  int
		diskType string
		expected bool
	}{
		{"unreported sentinel on an ssd", -1, "ssd", false},
		{"unreported sentinel on an nvme", -1, "nvme", false},
		{"unreported sentinel with no type", -1, "", false},
		{"spent ssd reports zero", 0, "ssd", true},
		{"spent nvme reports zero", 0, "nvme", true},
		{"spent nvme reports zero regardless of case", 0, "NVMe", true},
		{"rotational zero is absence, not a spent disk", 0, "hdd", false},
		{"untyped zero is absence, not a spent disk", 0, "", false},
		{"positive reading is evidence whatever the type", 5, "hdd", true},
		{"full life is evidence", 100, "ssd", true},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := WearoutReported(tt.wearout, tt.diskType); got != tt.expected {
				t.Errorf("WearoutReported(%d, %q) = %v, want %v", tt.wearout, tt.diskType, got, tt.expected)
			}
		})
	}
}

// A spent SSD must reach the critical arm. Before the sentinel was unified,
// WearoutKnown was computed inline and a 0 reading fell through as if the disk
// had said nothing.
func TestAssessPhysicalDisk_SpentSSDIsCritical(t *testing.T) {
	assessment := AssessPhysicalDisk(models.PhysicalDisk{
		Health:  "PASSED",
		Type:    "ssd",
		Wearout: 0,
	})
	if assessment.Level != RiskCritical {
		t.Fatalf("spent SSD should assess critical, got %q", assessment.Level)
	}
}

func TestAssessPhysicalDisk_UnreportedWearoutIsNotRisk(t *testing.T) {
	for _, diskType := range []string{"ssd", "hdd", ""} {
		assessment := AssessPhysicalDisk(models.PhysicalDisk{
			Health:  "PASSED",
			Type:    diskType,
			Wearout: -1,
		})
		if assessment.Level == RiskCritical {
			t.Errorf("unreported wearout on %q must not assess critical", diskType)
		}
	}
}

func TestAssessPhysicalDisk_RotationalZeroIsNotRisk(t *testing.T) {
	assessment := AssessPhysicalDisk(models.PhysicalDisk{
		Health:  "PASSED",
		Type:    "hdd",
		Wearout: 0,
	})
	if assessment.Level == RiskCritical {
		t.Error("a rotational disk reporting 0 wearout reports no endurance at all and must not assess critical")
	}
}

// Heat belongs to the alert disk temperature policy, which users tune per disk
// type and per host. Disk risk cannot see that configuration, so it must not
// judge temperature at all, however hot and however current the reading.
func TestDiskAssessmentsNeverJudgeTemperature(t *testing.T) {
	collected := &diskinventory.CollectionStatus{Temperature: diskinventory.Available("host_agent")}
	for _, temperature := range []int{56, 63, 72, 95} {
		disk := models.PhysicalDisk{Model: "WDC WD80EFAX", Type: "sata", Health: "PASSED", Wearout: -1, Temperature: temperature, Collection: collected}
		if got := AssessPhysicalDisk(disk); got.Level != RiskHealthy || len(got.Reasons) != 0 {
			t.Errorf("%dC physical disk = %+v, want healthy with no reasons", temperature, got)
		}

		smart := models.HostDiskSMART{Device: "/dev/nvme0n1", Model: "Samsung 990 PRO", Type: "nvme", Health: "PASSED", Temperature: temperature, Collection: collected}
		if got := AssessHostSMARTDisk(smart); got.Level != RiskHealthy || len(got.Reasons) != 0 {
			t.Errorf("%dC host SMART disk = %+v, want healthy with no reasons", temperature, got)
		}
	}
}