Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Cover the alert read-model, guest identity and action-planner validators
rcourtmanbbd333631c18
diff --git a/internal/actionplanner/planner_validate_branchcov0725am_test.go b/internal/actionplanner/planner_validate_branchcov0725am_test.gonew file mode 100644index 0000000000..79aad5c33a--- /dev/null+++ b/internal/actionplanner/planner_validate_branchcov0725am_test.go@@ -0,0 +1,312 @@+package actionplanner++import (+ "encoding/json"+ "testing"++ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++// These tests drive the partially-covered arms of validateParamType,+// validateParamValue, normalizeDataSources and normalizeChanges in planner.go.+// They assert on real returned values / errors / mutated state only.++func TestBranchcov0725amValidateParamType(t *testing.T) {+ spec := func(typ string) unified.CapabilityParam {+ return unified.CapabilityParam{Name: "mode", Type: typ}+ }+ steps := []struct {+ name string+ value any+ spec unified.CapabilityParam+ wantErr bool+ wantMsg string+ }{+ // "" / "any" accept any value (including nil) and return nil.+ {"empty_type_accepts_string", "x", spec(""), false, ""},+ {"any_type_accepts_nil", nil, spec("any"), false, ""},++ // string+ {"string_accepts_string", "x", spec("string"), false, ""},+ {"string_rejects_int", 1, spec("string"), true, "parameter must be string"},+ {"string_rejects_bool", true, spec("string"), true, "parameter must be string"},++ // bool / boolean alias+ {"bool_accepts_bool", true, spec("bool"), false, ""},+ {"bool_rejects_string", "true", spec("bool"), true, "parameter must be bool"},+ {"boolean_alias_accepts_bool", false, spec("boolean"), false, ""},+ {"boolean_alias_rejects_int", 1, spec("boolean"), true, "parameter must be boolean"},++ // int / integer alias+ {"int_accepts_int", 5, spec("int"), false, ""},+ {"int_accepts_int64", int64(5), spec("int"), false, ""},+ {"int_rejects_float_fractional", 1.5, spec("int"), true, "parameter must be int"},+ {"int_rejects_string", "5", spec("int"), true, "parameter must be int"},+ {"integer_alias_accepts_int", 5, spec("integer"), false, ""},+ {"integer_alias_rejects_bool", true, spec("integer"), true, "parameter must be integer"},++ // number / float / float64 aliases+ {"number_accepts_float", 1.5, spec("number"), false, ""},+ {"number_accepts_int", 1, spec("number"), false, ""},+ {"number_rejects_string", "1.5", spec("number"), true, "parameter must be number"},+ {"float_alias_accepts_float", 1.5, spec("float"), false, ""},+ {"float64_alias_accepts_float", 1.5, spec("float64"), false, ""},+ {"float_alias_rejects_bool", true, spec("float"), true, "parameter must be float"},++ // object / map aliases+ {"object_accepts_map_string_any", map[string]any{"a": 1}, spec("object"), false, ""},+ {"object_accepts_map_int_string", map[int]string{1: "a"}, spec("object"), false, ""},+ {"object_rejects_string", "x", spec("object"), true, "parameter must be object"},+ {"map_alias_accepts_map_string_any", map[string]any{"a": 1}, spec("map"), false, ""},+ {"map_alias_rejects_slice", []int{1}, spec("map"), true, "parameter must be map"},++ // array / list aliases+ {"array_accepts_slice", []int{1}, spec("array"), false, ""},+ {"array_accepts_array", [3]int{1, 2, 3}, spec("array"), false, ""},+ {"array_rejects_map", map[string]any{"a": 1}, spec("array"), true, "parameter must be array"},+ {"list_alias_accepts_slice", []string{"a"}, spec("list"), false, ""},+ {"list_alias_rejects_string", "x", spec("list"), true, "parameter must be list"},++ // Case-insensitive + whitespace-trim normalization of the declared type+ // before the switch dispatches.+ {"uppercase_string_normalized_accepts", "x", spec(" STRING "), false, ""},+ {"mixedcase_integer_normalized_accepts", 1, spec("Integer"), false, ""},++ // Unknown type -> default arm.+ {"unknown_type_rejected", "x", spec("banana"), true, "capability declares unsupported parameter type banana"},+ {"unknown_type_uppercase_lowercased_in_message", "x", spec(" BANANA "), true, "capability declares unsupported parameter type banana"},+ }+ for _, step := range steps {+ t.Run(step.name, func(t *testing.T) {+ err := validateParamType(step.value, step.spec)+ if step.wantErr {+ if err == nil {+ t.Fatalf("validateParamType(%T, %q) = nil, want error", step.value, step.spec.Type)+ }+ ve, ok := AsValidationError(err)+ if !ok {+ t.Fatalf("validateParamType(%T, %q) error = %v, want *ValidationError", step.value, step.spec.Type, err)+ }+ if ve.Field != "params.mode" {+ t.Fatalf("Field = %q, want params.mode", ve.Field)+ }+ if step.wantMsg != "" && ve.Message != step.wantMsg {+ t.Fatalf("Message = %q, want %q", ve.Message, step.wantMsg)+ }+ } else if err != nil {+ t.Fatalf("validateParamType(%T, %q) = %v, want nil", step.value, step.spec.Type, err)+ }+ })+ }+}++func TestBranchcov0725amValidateParamValue(t *testing.T) {+ steps := []struct {+ name string+ value any+ spec unified.CapabilityParam+ wantErr bool+ wantMsg string+ }{+ // validateParamType error propagates unchanged.+ {"type_error_propagated", 1, unified.CapabilityParam{Name: "mode", Type: "string"}, true, "parameter must be string"},++ // Enum arm: match via trimmed string.+ {"enum_string_match", "red", unified.CapabilityParam{Name: "color", Type: "string", Enum: []string{"red", "green"}}, false, ""},+ // Enum: candidate is whitespace-padded; match after TrimSpace.+ {"enum_matches_via_trimmed_candidate", "red", unified.CapabilityParam{Name: "color", Type: "any", Enum: []string{" red "}}, false, ""},+ // Enum: match via json.Number enumString().+ {"enum_json_number_match", json.Number("42"), unified.CapabilityParam{Name: "n", Type: "any", Enum: []string{"42"}}, false, ""},+ // Enum: match via fmt.Sprint default path (int value).+ {"enum_int_match", 42, unified.CapabilityParam{Name: "n", Type: "any", Enum: []string{"42"}}, false, ""},+ // Enum: no candidate matches.+ {"enum_no_match", "purple", unified.CapabilityParam{Name: "color", Type: "string", Enum: []string{"red", "green"}}, true, "parameter value is outside the allowed enum"},++ // Pattern arm.+ {"pattern_match", "abc", unified.CapabilityParam{Name: "slug", Type: "string", Pattern: "^[a-z]+$"}, false, ""},+ {"pattern_no_match", "ABC", unified.CapabilityParam{Name: "slug", Type: "string", Pattern: "^[a-z]+$"}, true, "parameter value does not match the required pattern"},+ // Pattern with a non-string value (type "any" passes type check first).+ {"pattern_requires_string_value", 42, unified.CapabilityParam{Name: "slug", Type: "any", Pattern: "^[0-9]+$"}, true, "pattern validation requires a string value"},+ // Pattern that fails to compile.+ {"pattern_invalid_regex", "abc", unified.CapabilityParam{Name: "slug", Type: "any", Pattern: "["}, true, "capability declares an invalid pattern"},++ // No enum, no pattern, type ok -> final nil return.+ {"plain_type_ok_no_enum_no_pattern", "hello", unified.CapabilityParam{Name: "greeting", Type: "string"}, false, ""},+ }+ for _, step := range steps {+ t.Run(step.name, func(t *testing.T) {+ err := validateParamValue(step.value, step.spec)+ if step.wantErr {+ if err == nil {+ t.Fatalf("validateParamValue(%T, %+v) = nil, want error", step.value, step.spec)+ }+ ve, ok := AsValidationError(err)+ if !ok {+ t.Fatalf("validateParamValue(%T, %+v) error = %v, want *ValidationError", step.value, step.spec, err)+ }+ if step.wantMsg != "" && ve.Message != step.wantMsg {+ t.Fatalf("Message = %q, want %q", ve.Message, step.wantMsg)+ }+ } else if err != nil {+ t.Fatalf("validateParamValue(%T, %+v) = %v, want nil", step.value, step.spec, err)+ }+ })+ }+}++func TestBranchcov0725amNormalizeDataSources(t *testing.T) {+ assertDataSources := func(t *testing.T, got, want []unified.DataSource) {+ t.Helper()+ if got == nil {+ t.Fatalf("normalizeDataSources returned nil, want non-nil slice")+ }+ if len(got) != len(want) {+ t.Fatalf("len = %d, want %d (got=%#v)", len(got), len(want), got)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("idx %d = %q, want %q (got=%#v)", i, got[i], want[i], got)+ }+ }+ }++ t.Run("nil_returns_nonnil_empty", func(t *testing.T) {+ got := normalizeDataSources(nil)+ assertDataSources(t, got, []unified.DataSource{})+ })++ t.Run("all_blank_and_whitespace_only_returns_nonnil_empty", func(t *testing.T) {+ got := normalizeDataSources([]unified.DataSource{"", " ", "\t"})+ assertDataSources(t, got, []unified.DataSource{})+ })++ t.Run("blank_entries_dropped_keeping_valid", func(t *testing.T) {+ got := normalizeDataSources([]unified.DataSource{"", " ", "\t", "proxmox"})+ assertDataSources(t, got, []unified.DataSource{"proxmox"})+ })++ t.Run("duplicates_after_case_and_trim_normalization_deduped_and_sorted", func(t *testing.T) {+ got := normalizeDataSources([]unified.DataSource{"Proxmox", "proxmox", " PROXMOX ", "docker"})+ assertDataSources(t, got, []unified.DataSource{"docker", "proxmox"})+ })++ t.Run("trim_and_lowercase_then_sorted", func(t *testing.T) {+ got := normalizeDataSources([]unified.DataSource{" Kubernetes ", "Docker", " proxmox"})+ assertDataSources(t, got, []unified.DataSource{"docker", "kubernetes", "proxmox"})+ })++ t.Run("already_sorted_unchanged", func(t *testing.T) {+ got := normalizeDataSources([]unified.DataSource{"agent", "docker"})+ assertDataSources(t, got, []unified.DataSource{"agent", "docker"})+ })+}++func TestBranchcov0725amNormalizeChanges(t *testing.T) {+ assertNormalized := func(t *testing.T, got []normalizedChange, want []normalizedChange) {+ t.Helper()+ if got == nil {+ t.Fatalf("normalizeChanges returned nil, want non-nil slice")+ }+ if len(got) != len(want) {+ t.Fatalf("len = %d, want %d (got=%#v)", len(got), len(want), got)+ }+ for i := range want {+ if got[i].ID != want[i].ID ||+ got[i].ResourceID != want[i].ResourceID ||+ got[i].Kind != want[i].Kind ||+ got[i].From != want[i].From ||+ got[i].To != want[i].To ||+ got[i].SourceType != want[i].SourceType ||+ got[i].SourceAdapter != want[i].SourceAdapter ||+ got[i].Confidence != want[i].Confidence {+ t.Fatalf("idx %d scalar fields = %+v, want %+v", i, got[i], want[i])+ }+ if len(got[i].RelatedResources) != len(want[i].RelatedResources) {+ t.Fatalf("idx %d RelatedResources len = %d, want %d", i, len(got[i].RelatedResources), len(want[i].RelatedResources))+ }+ for j := range want[i].RelatedResources {+ if got[i].RelatedResources[j] != want[i].RelatedResources[j] {+ t.Fatalf("idx %d RelatedResources[%d] = %q, want %q", i, j, got[i].RelatedResources[j], want[i].RelatedResources[j])+ }+ }+ }+ }++ t.Run("nil_returns_nonnil_empty", func(t *testing.T) {+ got := normalizeChanges(nil)+ assertNormalized(t, got, []normalizedChange{})+ })++ t.Run("single_change_trims_and_canonicalizes_fields", func(t *testing.T) {+ change := unified.ResourceChange{+ ID: " c1 ",+ ResourceID: " vm:1 ",+ Kind: unified.ChangeStateTransition,+ From: " running ",+ To: " stopped ",+ SourceType: unified.SourcePlatformEvent,+ SourceAdapter: unified.AdapterProxmox,+ Confidence: unified.ConfidenceHigh,+ RelatedResources: []string{" vm:3 ", "vm:1", "vm:1"},+ }+ got := normalizeChanges([]unified.ResourceChange{change})+ want := []normalizedChange{{+ ID: "c1",+ ResourceID: "vm:1",+ Kind: unified.ChangeStateTransition,+ From: "running",+ To: "stopped",+ SourceType: unified.SourcePlatformEvent,+ SourceAdapter: unified.AdapterProxmox,+ Confidence: unified.ConfidenceHigh,+ RelatedResources: []string{"vm:1", "vm:3"},+ }}+ assertNormalized(t, got, want)+ })++ t.Run("sorted_by_resource_id", func(t *testing.T) {+ changes := []unified.ResourceChange{+ {ID: "a", ResourceID: "vm:9", Kind: unified.ChangeActivity},+ {ID: "a", ResourceID: "vm:1", Kind: unified.ChangeActivity},+ }+ got := normalizeChanges(changes)+ if got[0].ResourceID != "vm:1" || got[1].ResourceID != "vm:9" {+ t.Fatalf("order = [%s, %s], want vm:1 then vm:9", got[0].ResourceID, got[1].ResourceID)+ }+ })++ t.Run("same_resource_id_sorted_by_change_id", func(t *testing.T) {+ changes := []unified.ResourceChange{+ {ID: "c9", ResourceID: "vm:1", Kind: unified.ChangeActivity},+ {ID: "c1", ResourceID: "vm:1", Kind: unified.ChangeActivity},+ }+ got := normalizeChanges(changes)+ if got[0].ID != "c1" || got[1].ID != "c9" {+ t.Fatalf("order = [%s, %s], want c1 then c9", got[0].ID, got[1].ID)+ }+ })++ t.Run("same_resource_and_change_id_sorted_by_kind", func(t *testing.T) {+ changes := []unified.ResourceChange{+ {ID: "c1", ResourceID: "vm:1", Kind: unified.ChangeRestart},+ {ID: "c1", ResourceID: "vm:1", Kind: unified.ChangeActivity},+ }+ got := normalizeChanges(changes)+ if got[0].Kind != unified.ChangeActivity || got[1].Kind != unified.ChangeRestart {+ t.Fatalf("order = [%s, %s], want activity then restart", got[0].Kind, got[1].Kind)+ }+ })++ t.Run("blank_related_resources_dropped", func(t *testing.T) {+ change := unified.ResourceChange{+ ID: "c1",+ ResourceID: "vm:1",+ Kind: unified.ChangeActivity,+ RelatedResources: []string{"", " ", "vm:2"},+ }+ got := normalizeChanges([]unified.ResourceChange{change})+ if len(got[0].RelatedResources) != 1 || got[0].RelatedResources[0] != "vm:2" {+ t.Fatalf("RelatedResources = %#v, want [vm:2]", got[0].RelatedResources)+ }+ })+}diff --git a/internal/alerts/guest_identity_branchcov0725am_test.go b/internal/alerts/guest_identity_branchcov0725am_test.gonew file mode 100644index 0000000000..cb5ffebc6c--- /dev/null+++ b/internal/alerts/guest_identity_branchcov0725am_test.go@@ -0,0 +1,622 @@+package alerts++import (+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++// TestBranchcov0725amSnapshotAlertStillTriggered raises statement coverage of+// snapshotAlertStillTriggered (backup_snapshot.go:61, baseline 15.4%). The+// existing suite reaches snapshot evaluation only through the live+// CheckSnapshotsForInstance path, so snapshotAlertStillTriggered itself is+// almost entirely uncovered: only the trailing `return false` is hit. These+// cases independently drive every arm with assertions that distinguish them:+// - the nil-alert guard and the disabled-cfg guard (both -> false)+// - each of the four threshold "still triggered" arms in isolation:+// critical-days, warning-days, critical-size, warning-size (each -> true)+// - the `>=` boundary at exactly the threshold value (-> true) for both age+// and size, plus the just-below value (-> false) to pin the comparison+// - missing metadata (age/size default to 0 -> false)+// - no thresholds configured at all (-> false)+//+// Each case is constructed so exactly one arm is the deciding one (e.g. to+// isolate the size arms the age is held below every age threshold).+func TestBranchcov0725amSnapshotAlertStillTriggered(t *testing.T) {+ cases := []struct {+ name string+ alert *Alert+ cfg SnapshotAlertConfig+ want bool+ }{+ {+ // Nil-alert guard: returns false regardless of cfg.+ name: "nil_alert_returns_false",+ alert: nil,+ cfg: SnapshotAlertConfig{Enabled: true, WarningDays: 3, CriticalDays: 5},+ want: false,+ },+ {+ // Disabled-cfg guard: returns false even with triggering metadata.+ name: "disabled_cfg_returns_false",+ alert: &Alert{Metadata: map[string]interface{}{"snapshotAgeDays": 99.0}},+ cfg: SnapshotAlertConfig{Enabled: false, WarningDays: 3, CriticalDays: 5},+ want: false,+ },+ {+ // Critical-age arm: age 10 >= CriticalDays 5 (and > WarningDays 3).+ name: "critical_age_triggers",+ alert: &Alert{Metadata: map[string]interface{}{+ "snapshotAgeDays": 10.0,+ "snapshotSizeGiB": 0.0,+ }},+ cfg: SnapshotAlertConfig{Enabled: true, WarningDays: 3, CriticalDays: 5},+ want: true,+ },+ {+ // Warning-age arm: age 4 below CriticalDays 5 but >= WarningDays 3.+ name: "warning_age_triggers_below_critical",+ alert: &Alert{Metadata: map[string]interface{}{+ "snapshotAgeDays": 4.0,+ }},+ cfg: SnapshotAlertConfig{Enabled: true, WarningDays: 3, CriticalDays: 5},+ want: true,+ },+ {+ // Critical-size arm (age held low so it cannot fire):+ // size 10 >= CriticalSizeGiB 5.+ name: "critical_size_triggers",+ alert: &Alert{Metadata: map[string]interface{}{+ "snapshotAgeDays": 1.0,+ "snapshotSizeGiB": 10.0,+ }},+ cfg: SnapshotAlertConfig{+ Enabled: true,+ WarningSizeGiB: 3,+ CriticalSizeGiB: 5,+ },+ want: true,+ },+ {+ // Warning-size arm (age held low): size 4 below CriticalSizeGiB 5+ // but >= WarningSizeGiB 3.+ name: "warning_size_triggers_below_critical",+ alert: &Alert{Metadata: map[string]interface{}{+ "snapshotAgeDays": 1.0,+ "snapshotSizeGiB": 4.0,+ }},+ cfg: SnapshotAlertConfig{+ Enabled: true,+ WarningSizeGiB: 3,+ CriticalSizeGiB: 5,+ },+ want: true,+ },+ {+ // Age boundary: age exactly == CriticalDays -> `>=` is true.+ name: "age_at_exact_critical_boundary_triggers",+ alert: &Alert{Metadata: map[string]interface{}{+ "snapshotAgeDays": 5.0,+ }},+ cfg: SnapshotAlertConfig{Enabled: true, CriticalDays: 5, WarningDays: 3},+ want: true,+ },+ {+ // Size boundary: size exactly == WarningSizeGiB -> `>=` is true.+ name: "size_at_exact_warning_boundary_triggers",+ alert: &Alert{Metadata: map[string]interface{}{+ "snapshotAgeDays": 1.0,+ "snapshotSizeGiB": 3.0,+ }},+ cfg: SnapshotAlertConfig{+ Enabled: true,+ WarningSizeGiB: 3,+ CriticalSizeGiB: 5,+ },+ want: true,+ },+ {+ // Just-below boundary: age 2 < WarningDays 3 -> false.+ name: "age_below_warning_returns_false",+ alert: &Alert{Metadata: map[string]interface{}{+ "snapshotAgeDays": 2.0,+ }},+ cfg: SnapshotAlertConfig{Enabled: true, WarningDays: 3, CriticalDays: 5},+ want: false,+ },+ {+ // Missing metadata: age/size default to 0 -> false.+ name: "missing_metadata_returns_false",+ alert: &Alert{Metadata: map[string]interface{}{"snapshotName": "daily"}},+ cfg: SnapshotAlertConfig{Enabled: true, WarningDays: 3, CriticalDays: 5, WarningSizeGiB: 3, CriticalSizeGiB: 5},+ want: false,+ },+ {+ // No thresholds configured at all -> never triggers.+ name: "no_thresholds_returns_false",+ alert: &Alert{Metadata: map[string]interface{}{+ "snapshotAgeDays": 99.0,+ "snapshotSizeGiB": 99.0,+ }},+ cfg: SnapshotAlertConfig{Enabled: true},+ want: false,+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ if got := snapshotAlertStillTriggered(tc.alert, tc.cfg); got != tc.want {+ t.Fatalf("snapshotAlertStillTriggered want %v, got %v", tc.want, got)+ }+ })+ }+}++// TestBranchcov0725amParseStableGuestOverrideKey raises statement coverage of+// parseStableGuestOverrideKey (guest_override_identity.go:64, baseline 30.0%).+// The existing suite only reaches it indirectly via lookupGuestOverride for the+// happy path. These cases drive every deciding arm and assert the parsed+// identity (instance/node/vmid) so each producing arm is pinned:+// - empty key, wrong part-count (2 and 4), and parts[0] != "guest" (the+// canonical-key shape "inst:node:vmid") -> {}, false+// - parts[0] == "guest" but vmid non-numeric, zero, or negative -> false+// - instance fails isCanonicalGuestKeyPart (empty, or contains "/") -> false+// - happy path: "guest:inst:100" -> {inst, inst, 100}, true (node is mirrored+// from instance), including leading/trailing whitespace trimming+func TestBranchcov0725amParseStableGuestOverrideKey(t *testing.T) {+ cases := []struct {+ name string+ key string+ wantIdent guestOverrideIdentity+ wantOk bool+ }{+ {+ // Empty key -> after TrimSpace still "" -> Split -> [""] len 1 -> false.+ name: "empty_key_false",+ key: "",+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // Wrong part count: 2 parts -> false.+ name: "two_parts_false",+ key: "guest:100",+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // Wrong part count: 4 parts -> false.+ name: "four_parts_false",+ key: "guest:inst:100:extra",+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // parts[0] != "guest" (canonical-key shape) -> false. This is the+ // distinct arm from a valid canonical key, which parseCanonicalGuestKey+ // accepts but this function must reject.+ name: "non_guest_prefix_false",+ key: "pve1:node1:100",+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // parts[0] == "guest" but vmid non-numeric -> false.+ name: "non_numeric_vmid_false",+ key: "guest:inst:abc",+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // vmid == 0 -> `vmid <= 0` guard -> false.+ name: "zero_vmid_false",+ key: "guest:inst:0",+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // vmid negative -> `vmid <= 0` guard -> false.+ name: "negative_vmid_false",+ key: "guest:inst:-5",+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // instance empty -> isCanonicalGuestKeyPart("") false -> false.+ name: "empty_instance_false",+ key: "guest::100",+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // instance contains "/" -> isCanonicalGuestKeyPart false -> false.+ name: "instance_with_slash_false",+ key: "guest:inst/sub:100",+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // Happy path: node is mirrored from instance.+ name: "valid_key_mirrors_node",+ key: "guest:pve1:100",+ wantIdent: guestOverrideIdentity{instance: "pve1", node: "pve1", vmid: 100},+ wantOk: true,+ },+ {+ // Leading/trailing whitespace is trimmed on the whole key and on+ // the instance segment before validation.+ name: "valid_key_with_whitespace_trimmed",+ key: " guest: pve1 :200 ",+ wantIdent: guestOverrideIdentity{instance: "pve1", node: "pve1", vmid: 200},+ wantOk: true,+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ gotIdent, gotOk := parseStableGuestOverrideKey(tc.key)+ if gotOk != tc.wantOk {+ t.Fatalf("parseStableGuestOverrideKey(%q) ok = %v, want %v", tc.key, gotOk, tc.wantOk)+ }+ if gotIdent != tc.wantIdent {+ t.Fatalf("parseStableGuestOverrideKey(%q) = %+v, want %+v", tc.key, gotIdent, tc.wantIdent)+ }+ })+ }+}++// TestBranchcov0725amExtractGuestSnapshot raises statement coverage of+// extractGuestSnapshot (guest_snapshot.go:245, baseline 35.7%). The existing+// suite covers only the default (unknown-type) arm. These cases drive every+// other type-switch arm and each pointer-nil guard, asserting on the real+// returned snapshot (Kind, VMID, Name) so the producing arm is unambiguous:+// - models.VM and *models.VM (non-nil) -> guestKindVM with propagated fields+// - *models.VM nil -> empty canonical snapshot, false+// - models.Container and *models.Container (non-nil) -> guestKindContainer+// - *models.Container nil -> empty canonical snapshot, false+// - guestSnapshot value and *guestSnapshot (non-nil) -> normalized passthrough+// - *guestSnapshot nil -> empty canonical snapshot, false+//+// The already-covered default arm (struct{} -> false) is intentionally not+// duplicated here.+func TestBranchcov0725amExtractGuestSnapshot(t *testing.T) {+ cases := []struct {+ name string+ guest any+ wantOk bool+ wantKind guestKind+ wantVMID int+ wantName string+ // wantNilCollections asserts the false-returning arms yield the+ // canonical empty snapshot (non-nil Disks/Tags slices).+ wantNilCollections bool+ }{+ {+ // models.VM value arm -> VM kind, fields propagated.+ name: "vm_value",+ guest: models.VM{Instance: "pve1", Node: "n1", VMID: 100, Name: "vm100"},+ wantOk: true,+ wantKind: guestKindVM,+ wantVMID: 100,+ wantName: "vm100",+ },+ {+ // *models.VM non-nil arm -> VM kind, fields propagated.+ name: "vm_ptr_nonnil",+ guest: &models.VM{Instance: "pve1", Node: "n1", VMID: 101, Name: "vm101"},+ wantOk: true,+ wantKind: guestKindVM,+ wantVMID: 101,+ wantName: "vm101",+ },+ {+ // *models.VM nil arm -> false, canonical empty snapshot.+ name: "vm_ptr_nil",+ guest: (*models.VM)(nil),+ wantOk: false,+ wantKind: guestKindUnknown,+ wantNilCollections: true,+ },+ {+ // models.Container value arm -> Container kind, fields propagated.+ name: "container_value",+ guest: models.Container{Instance: "pve2", Node: "n2", VMID: 200, Name: "ct200"},+ wantOk: true,+ wantKind: guestKindContainer,+ wantVMID: 200,+ wantName: "ct200",+ },+ {+ // *models.Container non-nil arm -> Container kind.+ name: "container_ptr_nonnil",+ guest: &models.Container{Instance: "pve2", Node: "n2", VMID: 201, Name: "ct201"},+ wantOk: true,+ wantKind: guestKindContainer,+ wantVMID: 201,+ wantName: "ct201",+ },+ {+ // *models.Container nil arm -> false, canonical empty snapshot.+ name: "container_ptr_nil",+ guest: (*models.Container)(nil),+ wantOk: false,+ wantKind: guestKindUnknown,+ wantNilCollections: true,+ },+ {+ // guestSnapshot value arm -> passthrough (and normalized).+ name: "guest_snapshot_value",+ guest: guestSnapshot{Kind: guestKindVM, VMID: 300, Name: "gs300", Disks: nil, Tags: nil},+ wantOk: true,+ wantKind: guestKindVM,+ wantVMID: 300,+ wantName: "gs300",+ },+ {+ // *guestSnapshot non-nil arm -> passthrough (and normalized).+ name: "guest_snapshot_ptr_nonnil",+ guest: &guestSnapshot{Kind: guestKindContainer, VMID: 301, Name: "gs301"},+ wantOk: true,+ wantKind: guestKindContainer,+ wantVMID: 301,+ wantName: "gs301",+ },+ {+ // *guestSnapshot nil arm -> false, canonical empty snapshot.+ name: "guest_snapshot_ptr_nil",+ guest: (*guestSnapshot)(nil),+ wantOk: false,+ wantKind: guestKindUnknown,+ wantNilCollections: true,+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ got, ok := extractGuestSnapshot(tc.guest)+ if ok != tc.wantOk {+ t.Fatalf("extractGuestSnapshot(%T) ok = %v, want %v", tc.guest, ok, tc.wantOk)+ }+ if got.Kind != tc.wantKind {+ t.Fatalf("extractGuestSnapshot(%T) Kind = %v, want %v", tc.guest, got.Kind, tc.wantKind)+ }+ if tc.wantOk {+ if got.VMID != tc.wantVMID {+ t.Fatalf("extractGuestSnapshot(%T) VMID = %d, want %d", tc.guest, got.VMID, tc.wantVMID)+ }+ if got.Name != tc.wantName {+ t.Fatalf("extractGuestSnapshot(%T) Name = %q, want %q", tc.guest, got.Name, tc.wantName)+ }+ }+ if tc.wantNilCollections {+ // The canonical empty snapshot must have non-nil empty slices.+ if got.Disks == nil || got.Tags == nil {+ t.Fatalf("extractGuestSnapshot(%T) expected normalized empty collections, got Disks=%v Tags=%v", tc.guest, got.Disks, got.Tags)+ }+ if len(got.Disks) != 0 || len(got.Tags) != 0 {+ t.Fatalf("extractGuestSnapshot(%T) expected empty collections, got Disks=%v Tags=%v", tc.guest, got.Disks, got.Tags)+ }+ }+ })+ }+}++// TestBranchcov0725amGuestOverrideIdentityFromGuestOrID raises statement+// coverage of guestOverrideIdentityFromGuestOrID (guest_override_identity.go:87,+// baseline 50.0%). These cases drive every type-switch arm, each pointer-nil+// guard, and both halves of the default fallback (canonical-key parse success+// vs. stable-key parse). Each case asserts the concrete returned identity so+// the producing arm is pinned:+// - models.VM / *models.VM (non-nil) / models.Container / *models.Container+// (non-nil) -> guestOverrideIdentityFromParts with the model's fields+// - *models.VM nil and *models.Container nil -> {}, false+// - a VM with no instance/node -> fromParts returns false (drives the+// fromParts failure path reached only through the VM arm)+// - default + canonical key "inst:node:vmid" (parts[0] != "guest") -> parsed+// - default + stable key "guest:inst:vmid" (canonical parse rejects "guest"+// prefix, stable parse succeeds) -> parsed with node mirrored from instance+// - default + unparseable id -> both parses fail -> false+func TestBranchcov0725amGuestOverrideIdentityFromGuestOrID(t *testing.T) {+ cases := []struct {+ name string+ guest any+ guestID string+ wantIdent guestOverrideIdentity+ wantOk bool+ }{+ {+ // models.VM value arm.+ name: "vm_value",+ guest: models.VM{Instance: "pve1", Node: "node1", VMID: 100},+ wantIdent: guestOverrideIdentity{instance: "pve1", node: "node1", vmid: 100},+ wantOk: true,+ },+ {+ // *models.VM non-nil arm.+ name: "vm_ptr_nonnil",+ guest: &models.VM{Instance: "pve1", Node: "node1", VMID: 101},+ wantIdent: guestOverrideIdentity{instance: "pve1", node: "node1", vmid: 101},+ wantOk: true,+ },+ {+ // *models.VM nil arm.+ name: "vm_ptr_nil",+ guest: (*models.VM)(nil),+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // models.VM with no instance/node -> fromParts returns false+ // (instance/node empty). Drives the fromParts failure path.+ name: "vm_missing_instance_node_false",+ guest: models.VM{VMID: 102},+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // models.Container value arm.+ name: "container_value",+ guest: models.Container{Instance: "pve2", Node: "node2", VMID: 200},+ wantIdent: guestOverrideIdentity{instance: "pve2", node: "node2", vmid: 200},+ wantOk: true,+ },+ {+ // *models.Container non-nil arm.+ name: "container_ptr_nonnil",+ guest: &models.Container{Instance: "pve2", Node: "node2", VMID: 201},+ wantIdent: guestOverrideIdentity{instance: "pve2", node: "node2", vmid: 201},+ wantOk: true,+ },+ {+ // *models.Container nil arm.+ name: "container_ptr_nil",+ guest: (*models.Container)(nil),+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ {+ // default arm: canonical key parses (parts[0] != "guest").+ name: "default_canonical_key",+ guest: nil,+ guestID: "pve3:node3:300",+ wantIdent: guestOverrideIdentity{instance: "pve3", node: "node3", vmid: 300},+ wantOk: true,+ },+ {+ // default arm: canonical parse rejects "guest:" prefix, stable+ // parse succeeds; node is mirrored from instance.+ name: "default_stable_key",+ guest: nil,+ guestID: "guest:pve4:400",+ wantIdent: guestOverrideIdentity{instance: "pve4", node: "pve4", vmid: 400},+ wantOk: true,+ },+ {+ // default arm: both parses fail (single-segment, non-numeric) ->+ // false.+ name: "default_unparseable_false",+ guest: nil,+ guestID: "garbage",+ wantIdent: guestOverrideIdentity{},+ wantOk: false,+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ gotIdent, gotOk := guestOverrideIdentityFromGuestOrID(tc.guest, tc.guestID)+ if gotOk != tc.wantOk {+ t.Fatalf("guestOverrideIdentityFromGuestOrID ok = %v, want %v", gotOk, tc.wantOk)+ }+ if gotIdent != tc.wantIdent {+ t.Fatalf("guestOverrideIdentityFromGuestOrID = %+v, want %+v", gotIdent, tc.wantIdent)+ }+ })+ }+}++// TestBranchcov0725amHasActiveAlertTrackingKeyNoLock raises statement coverage+// of (*Manager).hasActiveAlertTrackingKeyNoLock (canonical_identity.go:413,+// baseline 40.0%). The existing suite only reaches the direct-map-key lookup+// arm. These cases drive every arm with assertions that distinguish them:+// - empty trackingKey -> false (guard)+// - trackingKey is a direct map key -> true (direct-lookup arm)+// - trackingKey is NOT a direct key but equals an alert's canonical tracking+// key -> true (the iteration/scan arm), using an alert stored under a+// legacy id whose derived canonical state differs from its storage key+// - trackingKey absent everywhere -> false (final return)+// - a nil-valued map entry is skipped without panic and without a false+// positive (the nil-continue arm), proven by querying a key that is only+// "reachable" through the nil entry+//+// A minimal Manager literal is used because the method reads m.activeAlerts+// only; no goroutines or persistence are required.+func TestBranchcov0725amHasActiveAlertTrackingKeyNoLock(t *testing.T) {+ // Build alerts that exercise both the direct-key and the canonical-scan+ // arms. The "legacy" alert is stored under its legacy ID but carries a+ // CanonicalState that canonicalTrackingKeyForAlert will derive.+ legacyAlert := &Alert{+ ID: "backup-age-legacy-1",+ Type: "backup-age",+ ResourceID: "res-1",+ CanonicalSpecID: "res-1-backup-age",+ CanonicalState: "res-1::res-1-backup-age",+ }+ legacyCanonicalKey := canonicalTrackingKeyForAlert(legacyAlert)+ if legacyCanonicalKey == "" || legacyCanonicalKey == legacyAlert.ID {+ t.Fatalf("test setup: legacy alert must have a canonical key distinct from its storage id; got %q", legacyCanonicalKey)+ }++ // directKey alert is stored under a plain key with no canonical identity,+ // so only the direct-lookup arm can find it.+ directKey := "plain-direct-key"+ directAlert := &Alert{ID: directKey, Type: "cpu"}++ m := &Manager{+ activeAlerts: map[string]*Alert{+ legacyAlert.ID: legacyAlert, // stored under legacy id, NOT under legacyCanonicalKey+ directKey: directAlert,+ "nil-slot": nil, // nil-valued entry to drive the continue arm+ },+ }++ cases := []struct {+ name string+ trackingKey string+ want bool+ }{+ {+ // Guard arm: empty key -> false.+ name: "empty_key_false",+ trackingKey: "",+ want: false,+ },+ {+ // Direct-lookup arm: key present in the map -> true.+ name: "direct_key_true",+ trackingKey: directKey,+ want: true,+ },+ {+ // Scan arm: key NOT a direct map key but equals an alert's derived+ // canonical tracking key -> true.+ name: "canonical_scan_true",+ trackingKey: legacyCanonicalKey,+ want: true,+ },+ {+ // Final return: key absent everywhere -> false.+ name: "missing_key_false",+ trackingKey: "does-not-exist",+ want: false,+ },+ {+ // Nil-continue arm: the only map entry is a nil-valued slot, so the+ // scan must skip it and return false without panicking. Using a+ // dedicated manager keeps this case isolated from the others.+ name: "nil_entry_skipped_false",+ trackingKey: "anything",+ want: false,+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ mgr := m+ if tc.name == "nil_entry_skipped_false" {+ mgr = &Manager{activeAlerts: map[string]*Alert{"only-nil": nil}}+ if tc.trackingKey == "only-nil" {+ t.Fatal("test setup: tracking key must not be a direct map key for this case")+ }+ }+ if got := mgr.hasActiveAlertTrackingKeyNoLock(tc.trackingKey); got != tc.want {+ t.Fatalf("hasActiveAlertTrackingKeyNoLock(%q) = %v, want %v", tc.trackingKey, got, tc.want)+ }+ })+ }+}diff --git a/internal/alerts/read_model_branchcov0725am_test.go b/internal/alerts/read_model_branchcov0725am_test.gonew file mode 100644index 0000000000..c2d2d080b9--- /dev/null+++ b/internal/alerts/read_model_branchcov0725am_test.go@@ -0,0 +1,364 @@+package alerts++import (+ "encoding/json"+ "testing"+)++// TestBranchcov0725amMetadataBoolValue raises statement coverage of+// metadataBoolValue (read_model.go:196). The existing suite only reaches it+// indirectly through the live sort path, leaving most type-switch arms+// unmeasured (~25%). These cases drive, in order:+// - nil metadata map (short-circuit return false)+// - populated map but missing key (return false)+// - present key whose value is nil interface (falls through, return false)+// - bool true / bool false+// - every accepted truthy string token ("1","true","yes","on"), case- and+// whitespace-insensitive, plus non-truthy strings that must fall through+// - every signed/unsigned int type: nonzero -> true, zero -> false+// - float32/float64 nonzero -> true, zero -> false+// - json.Number that parses to a nonzero/zero int+// - json.Number that fails to parse (falls through, return false)+// - an unsupported type ([]string) -> default return false+//+// Each case carries a distinct key/value so the assertion pins exactly which+// arm produced the result.+func TestBranchcov0725amMetadataBoolValue(t *testing.T) {+ cases := []struct {+ name string+ metadata map[string]interface{}+ key string+ want bool+ }{+ {"nil_metadata_returns_false", nil, "protectionReduced", false},+ {"missing_key_returns_false", map[string]interface{}{"other": true}, "protectionReduced", false},+ {"nil_value_returns_false", map[string]interface{}{"k": nil}, "k", false},+ {"bool_true", map[string]interface{}{"k": true}, "k", true},+ {"bool_false", map[string]interface{}{"k": false}, "k", false},++ {"string_one_is_true", map[string]interface{}{"k": "1"}, "k", true},+ {"string_true_is_true", map[string]interface{}{"k": "true"}, "k", true},+ {"string_yes_is_true", map[string]interface{}{"k": "yes"}, "k", true},+ {"string_on_is_true", map[string]interface{}{"k": "on"}, "k", true},+ {"string_TRUE_uppercase_is_true", map[string]interface{}{"k": "TRUE"}, "k", true},+ {"string_YES_mixedcase_is_true", map[string]interface{}{"k": "YeS"}, "k", true},+ {"string_padded_true_is_true", map[string]interface{}{"k": " true "}, "k", true},+ {"string_zero_is_false", map[string]interface{}{"k": "0"}, "k", false},+ {"string_false_is_false", map[string]interface{}{"k": "false"}, "k", false},+ {"string_no_is_false", map[string]interface{}{"k": "no"}, "k", false},+ {"string_off_is_false", map[string]interface{}{"k": "off"}, "k", false},+ {"string_unknown_is_false", map[string]interface{}{"k": "maybe"}, "k", false},+ {"string_empty_is_false", map[string]interface{}{"k": ""}, "k", false},++ {"int_zero_is_false", map[string]interface{}{"k": 0}, "k", false},+ {"int_nonzero_is_true", map[string]interface{}{"k": 5}, "k", true},+ {"int_negative_is_true", map[string]interface{}{"k": -3}, "k", true},+ {"int8_nonzero_is_true", map[string]interface{}{"k": int8(2)}, "k", true},+ {"int8_zero_is_false", map[string]interface{}{"k": int8(0)}, "k", false},+ {"int16_nonzero_is_true", map[string]interface{}{"k": int16(7)}, "k", true},+ {"int32_nonzero_is_true", map[string]interface{}{"k": int32(7)}, "k", true},+ {"int64_nonzero_is_true", map[string]interface{}{"k": int64(9)}, "k", true},+ {"uint_nonzero_is_true", map[string]interface{}{"k": uint(4)}, "k", true},+ {"uint8_nonzero_is_true", map[string]interface{}{"k": uint8(4)}, "k", true},+ {"uint16_nonzero_is_true", map[string]interface{}{"k": uint16(4)}, "k", true},+ {"uint32_nonzero_is_true", map[string]interface{}{"k": uint32(4)}, "k", true},+ {"uint64_nonzero_is_true", map[string]interface{}{"k": uint64(4)}, "k", true},+ {"uint_zero_is_false", map[string]interface{}{"k": uint(0)}, "k", false},++ {"float32_nonzero_is_true", map[string]interface{}{"k": float32(1.5)}, "k", true},+ {"float32_zero_is_false", map[string]interface{}{"k": float32(0)}, "k", false},+ {"float64_nonzero_is_true", map[string]interface{}{"k": float64(2.5)}, "k", true},+ {"float64_zero_is_false", map[string]interface{}{"k": float64(0)}, "k", false},++ {"json_number_one_is_true", map[string]interface{}{"k": json.Number("1")}, "k", true},+ {"json_number_zero_is_false", map[string]interface{}{"k": json.Number("0")}, "k", false},+ {"json_number_unparseable_is_false", map[string]interface{}{"k": json.Number("not-a-number")}, "k", false},++ {"unsupported_type_is_false", map[string]interface{}{"k": []string{"true"}}, "k", false},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ if got := metadataBoolValue(tc.metadata, tc.key); got != tc.want {+ t.Fatalf("metadataBoolValue(%v, %q) = %v, want %v", tc.metadata, tc.key, got, tc.want)+ }+ })+ }+}++// TestBranchcov0725amMetadataIntValue raises statement coverage of+// metadataIntValue (read_model.go:127). The existing suite only exercises the+// int and the nil/miss paths indirectly (~27.8%). These cases drive every+// accepted underlying type (all signed/unsigned int widths, float32/float64,+// json.Number, string), the truncation behaviour of floats, the+// trim-then-Atoi behaviour of strings, the json.Number Int64() success and+// failure paths (including an overflow), and the wrong-type/nil fall-through+// to 0. Each numeric value is distinct so the assertion pins exactly which+// arm produced it.+func TestBranchcov0725amMetadataIntValue(t *testing.T) {+ cases := []struct {+ name string+ value interface{}+ want int+ }{+ {"nil_returns_zero", nil, 0},+ {"int", 42, 42},+ {"int_negative", -17, -17},+ {"int8", int8(8), 8},+ {"int16", int16(1600), 1600},+ {"int32", int32(320000), 320000},+ {"int64", int64(6400000), 6400000},+ {"uint", uint(13), 13},+ {"uint8", uint8(200), 200},+ {"uint16", uint16(40000), 40000},+ {"uint32", uint32(500000), 500000},+ {"uint64", uint64(9000000), 9000000},+ {"float32_truncates", float32(3.9), 3},+ {"float32_negative_truncates", float32(-2.7), -2},+ {"float64_truncates", float64(99.999), 99},+ {"float64_negative_truncates", float64(-1.1), -1},+ {"json_number_int", json.Number("42"), 42},+ {"json_number_negative_int", json.Number("-5"), -5},+ // json.Number holding a float is NOT a valid int64 -> Int64() errors -> 0.+ {"json_number_float_is_zero", json.Number("3.9"), 0},+ // json.Number overflowing int64 -> Int64() errors -> 0.+ {"json_number_overflow_is_zero", json.Number("99999999999999999999"), 0},+ {"json_number_unparseable_is_zero", json.Number("abc"), 0},+ {"string_int", "42", 42},+ {"string_negative_int", "-9", -9},+ {"string_padded_int_trimmed", " 77 ", 77},+ // A string holding a float is rejected by Atoi -> 0.+ {"string_float_is_zero", "3.9", 0},+ {"string_non_numeric_is_zero", "abc", 0},+ {"string_empty_is_zero", "", 0},+ {"unsupported_type_is_zero", []int{1, 2}, 0},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ if got := metadataIntValue(tc.value); got != tc.want {+ t.Fatalf("metadataIntValue(%T(%v)) = %d, want %d", tc.value, tc.value, got, tc.want)+ }+ })+ }+}++// TestBranchcov0725amAlertTypeSortRank raises statement coverage of+// alertTypeSortRank (read_model.go:108). The existing suite hits a subset of+// types through live evaluation (~37.5%). These cases drive every named+// switch arm (including each member of the multi-value case clauses) and the+// default/fallback arm, pinning the exact rank for every input class. Because+// the sort comparator orders by descending rank, the exact rank fully+// determines ordering.+func TestBranchcov0725amAlertTypeSortRank(t *testing.T) {+ cases := []struct {+ name string+ alertTpe string+ want int+ }{+ {"backup_posture_incident_is_6", "backup-posture-incident", 6},+ {"backup_storage_incident_is_5", "backup-storage-incident", 5},+ {"storage_incident_is_4", "storage-incident", 4},+ {"zfs_pool_state_is_4", "zfs-pool-state", 4},+ {"zfs_pool_errors_is_4", "zfs-pool-errors", 4},+ {"resource_incident_is_4", "resource-incident", 4},+ {"disk_health_is_3", "disk-health", 3},+ {"disk_wearout_is_3", "disk-wearout", 3},+ {"zfs_device_is_3", "zfs-device", 3},+ {"offline_is_2", "offline", 2},+ {"connectivity_is_2", "connectivity", 2},+ {"powered_off_is_2", "powered-off", 2},+ {"docker_host_offline_is_2", "docker-host-offline", 2},+ {"unknown_type_default_is_1", "some-other-type", 1},+ {"empty_type_default_is_1", "", 1},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ got := alertTypeSortRank(Alert{Type: tc.alertTpe})+ if got != tc.want {+ t.Fatalf("alertTypeSortRank(Type=%q) = %d, want %d", tc.alertTpe, got, tc.want)+ }+ })+ }+}++// TestBranchcov0725amAlertProtectionSortRank raises statement coverage of+// alertProtectionSortRank (read_model.go:62). The existing suite reaches ~50%.+// These cases drive all three switch arms: protectionReduced -> 2,+// rebuildInProgress -> 1, and the default -> 0, plus the nil-metadata and+// missing-key fall-throughs. Crucially, when protectionReduced is true the+// function must return 2 even if rebuildInProgress is also set (first-match+// precedence), which the precedence case pins.+func TestBranchcov0725amAlertProtectionSortRank(t *testing.T) {+ cases := []struct {+ name string+ meta map[string]interface{}+ want int+ }{+ {"nil_metadata_is_0", nil, 0},+ {"empty_metadata_is_0", map[string]interface{}{}, 0},+ {"protection_reduced_is_2", map[string]interface{}{"protectionReduced": true}, 2},+ {"rebuild_in_progress_is_1", map[string]interface{}{"rebuildInProgress": true}, 1},+ {"neither_flag_is_0", map[string]interface{}{"unrelated": true}, 0},+ {"protection_reduced_beats_rebuild", map[string]interface{}{"protectionReduced": true, "rebuildInProgress": true}, 2},+ // Falsy values must not trigger the flag arms.+ {"protection_reduced_false_is_0", map[string]interface{}{"protectionReduced": false}, 0},+ {"rebuild_in_progress_false_is_0", map[string]interface{}{"rebuildInProgress": false}, 0},+ {"protection_reduced_string_truthy_is_2", map[string]interface{}{"protectionReduced": "yes"}, 2},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ got := alertProtectionSortRank(Alert{Metadata: tc.meta})+ if got != tc.want {+ t.Fatalf("alertProtectionSortRank(%v) = %d, want %d", tc.meta, got, tc.want)+ }+ })+ }+}++// TestBranchcov0725amAlertRecoverabilitySortRank raises statement coverage of+// alertRecoverabilitySortRank (read_model.go:91). The existing suite reaches+// ~57.1%. The function is a top-down switch over conjuncts of metadataBoolValue+// and metadataIntValue, so each arm requires a precise combination of flags to+// defeat the earlier cases. These cases drive all six arms:+// 1. backupTarget && protectedWorkloadCount>0 -> 2+// 2. backupServer && protectedWorkloadCount>0 -> 2+// 3. backupTarget (protectedWorkloadCount<=0) -> 1+// 4. backupServer && affectedDatastoreCount>0 -> 1+// 5. backupServer (neither count>0) -> 1+// 6. default (no backup role) -> 0+//+// plus the nil-metadata and boundary (count == 0) cases that prove the+// `> 0` thresholds are exclusive at zero.+func TestBranchcov0725amAlertRecoverabilitySortRank(t *testing.T) {+ cases := []struct {+ name string+ meta map[string]interface{}+ want int+ }{+ {"nil_metadata_is_0", nil, 0},+ {"empty_metadata_is_0", map[string]interface{}{}, 0},+ {+ "arm1_backup_target_with_protected_workloads_is_2",+ map[string]interface{}{"backupTarget": true, "protectedWorkloadCount": 3},+ 2,+ },+ {+ "arm2_backup_server_with_protected_workloads_is_2",+ map[string]interface{}{"backupServer": true, "protectedWorkloadCount": 2},+ 2,+ },+ {+ "arm3_backup_target_no_protected_workloads_is_1",+ map[string]interface{}{"backupTarget": true, "protectedWorkloadCount": 0},+ 1,+ },+ {+ "arm3_backup_target_missing_count_is_1",+ map[string]interface{}{"backupTarget": true},+ 1,+ },+ {+ "arm4_backup_server_with_affected_datastores_is_1",+ map[string]interface{}{"backupServer": true, "affectedDatastoreCount": 4},+ 1,+ },+ {+ "arm5_backup_server_no_counts_is_1",+ map[string]interface{}{"backupServer": true},+ 1,+ },+ {+ "default_no_backup_role_is_0",+ map[string]interface{}{"unrelated": true},+ 0,+ },+ {+ // backupTarget must defeat backupServer precedence: when both are+ // set with protected workloads, arm 1 (rank 2) wins over arm 2.+ "backup_target_beats_backup_server_when_both_set",+ map[string]interface{}{"backupTarget": true, "backupServer": true, "protectedWorkloadCount": 5},+ 2,+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ got := alertRecoverabilitySortRank(Alert{Metadata: tc.meta})+ if got != tc.want {+ t.Fatalf("alertRecoverabilitySortRank(%v) = %d, want %d", tc.meta, got, tc.want)+ }+ })+ }+}++// TestBranchcov0725amNumericConditionValue raises statement coverage of+// numericConditionValue (filter_evaluation.go:135). The existing suite only+// reaches it indirectly through evaluateVMCondition, exercising float64, int,+// and the string (default) path (~22.2%). These cases drive every accepted+// numeric type arm, the json.Number Float64() success and failure paths+// (including an overflow that errors), and the default/failure arms (nil and+// an unsupported type). Because the function returns (float64, bool), each+// case asserts BOTH the converted value and the ok flag, using distinct+// magnitudes so the assertion pins the producing arm.+func TestBranchcov0725amNumericConditionValue(t *testing.T) {+ cases := []struct {+ name string+ raw any+ wantVal float64+ wantOk bool+ }{+ {"float64", 12.5, 12.5, true},+ {"float64_negative", -3.25, -3.25, true},+ {"float64_zero", 0.0, 0.0, true},+ {"float32", float32(7.5), 7.5, true},+ {"int", 42, 42, true},+ {"int_negative", -9, -9, true},+ {"int8", int8(8), 8, true},+ {"int16", int16(1600), 1600, true},+ {"int32", int32(320000), 320000, true},+ {"int64", int64(6400000), 6400000, true},+ {"uint", uint(13), 13, true},+ {"uint8", uint8(200), 200, true},+ {"uint16", uint16(40000), 40000, true},+ {"uint32", uint32(500000), 500000, true},+ {"uint64", uint64(9000000), 9000000, true},+ {"json_number_int", json.Number("42"), 42, true},+ {"json_number_float", json.Number("3.5"), 3.5, true},+ {"json_number_negative", json.Number("-2.25"), -2.25, true},+ // Overflow: 1e400 is not representable as float64 -> ParseFloat errors -> ok false.+ {"json_number_overflow_is_false", json.Number("1e400"), 0, false},+ // Non-numeric text -> ParseFloat errors -> ok false.+ {"json_number_unparseable_is_false", json.Number("not-a-number"), 0, false},+ // nil hits the default arm -> ok false.+ {"nil_is_false", nil, 0, false},+ // string is NOT accepted (unlike metadataIntValue) -> default arm -> ok false.+ {"string_is_false", "42", 0, false},+ // Unsupported type -> default arm -> ok false.+ {"slice_is_false", []int{1}, 0, false},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ gotVal, gotOk := numericConditionValue(tc.raw)+ if gotOk != tc.wantOk {+ t.Fatalf("numericConditionValue(%T(%v)) ok = %v, want %v", tc.raw, tc.raw, gotOk, tc.wantOk)+ }+ if gotOk && gotVal != tc.wantVal {+ t.Fatalf("numericConditionValue(%T(%v)) = %v, want %v", tc.raw, tc.raw, gotVal, tc.wantVal)+ }+ // When ok is false the implementation returns 0; pin that too.+ if !tc.wantOk && gotVal != 0 {+ t.Fatalf("numericConditionValue(%T(%v)) val = %v on failure, want 0", tc.raw, tc.raw, gotVal)+ }+ })+ }+}diff --git a/internal/alerts/specs/specs_validate_branchcov0725am_test.go b/internal/alerts/specs/specs_validate_branchcov0725am_test.gonew file mode 100644index 0000000000..d908b507cf--- /dev/null+++ b/internal/alerts/specs/specs_validate_branchcov0725am_test.go@@ -0,0 +1,362 @@+package specs++import (+ "math"+ "strings"+ "testing"+ "time"+)++// This file is a purpose-built branch-coverage test set (selectable via+// `-run "^TestBranchcov0725am"`) for four partially-covered functions whose+// uncovered arms the existing suite does not reach:+//+// - ChangeThresholdSpec.Validate (types.go:402) baseline 57.1%+// - BaselineAnomalySpec.Validate (types.go:447) baseline 58.8%+// - metricTriggered (evaluator.go:701) baseline 50.0%+// - metricStillLatched (evaluator.go:715) baseline 50.0%+//+// Conventions mirror the sibling in-package branch-coverage file+// evaluator_branchcov0724pm_test.go and types_test.go: stdlib `testing` only,+// table-driven subtests, t.Parallel(), t.Fatalf assertions on the concrete+// returned error / bool. No testify.+//+// The two Validate methods are reached by the existing suite only through the+// "happy path" accept case (ResourceAlertSpec.Validate -> payload.Validate) and,+// for ChangeThreshold, the warning-percent-without-delta arm; for+// BaselineAnomaly, the inverted quiet-delta arm. metricTriggered and+// metricStillLatched are never called by name in any test and are only reached+// indirectly through Evaluate, which always supplies a non-nil, validated spec —+// so their nil-spec and unknown-direction arms are entirely uncovered. These+// tests call all four functions directly to drive every remaining arm.+//+// Purity: every target is a pure function over its struct arguments; no network,+// daemon, database, or filesystem is touched.++// assertBranchcov0725amError centralises the "specific rejection reason"+// assertion used by both Validate tables: when wantErr is true the returned+// error must be non-nil and contain wantSubstr (asserting the specific error+// path); when wantErr is false the error must be nil (the accepting case).+func assertBranchcov0725amError(t *testing.T, err error, wantErr bool, wantSubstr string) {+ t.Helper()+ if wantErr {+ if err == nil {+ t.Fatalf("expected error containing %q, got nil", wantSubstr)+ }+ if !strings.Contains(err.Error(), wantSubstr) {+ t.Fatalf("expected error containing %q, got %q", wantSubstr, err.Error())+ }+ return+ }+ if err != nil {+ t.Fatalf("expected no error, got %v", err)+ }+}++// TestBranchcov0725amChangeThresholdSpecValidate drives every distinct+// rejection reason in ChangeThresholdSpec.Validate (types.go:402) as its own+// case asserting the specific error, plus the accepting case. The existing+// suite already covers only the warning-percent-without-delta arm and the+// accept path; this adds the empty-metric, negative-window, non-finite,+// negative-percent, critical-percent-without-delta, inverted-percent,+// no-threshold, inverted-current and inverted-delta arms.+func TestBranchcov0725amChangeThresholdSpecValidate(t *testing.T) {+ t.Parallel()++ // A fully-valid change threshold used as the base for rejection cases; each+ // case below overrides only the field(s) relevant to the arm under test so+ // that every earlier guard passes and the targeted return is reached.+ positivePercentDelta := ChangeThresholdSpec{+ Metric: "quarantine-spam",+ ReferenceWindow: 2 * time.Hour,+ WarningCurrent: 2000,+ CriticalCurrent: 5000,+ WarningDelta: 250,+ CriticalDelta: 500,+ WarningPercent: 25,+ CriticalPercent: 50,+ }++ cases := []struct {+ name string+ spec ChangeThresholdSpec+ wantErr bool+ wantSubstr string+ }{+ // ---- accepting case (arm: return nil) ----+ {"accepts fully populated spec", positivePercentDelta, false, ""},++ // ---- empty metric (arm: "metric is required") ----+ {"empty metric rejected", ChangeThresholdSpec{Metric: " ", WarningCurrent: 1}, true, "metric is required"},++ // ---- negative reference window (arm: "reference window must be zero or positive") ----+ {"negative reference window rejected", ChangeThresholdSpec{+ Metric: "quarantine-spam", ReferenceWindow: -1 * time.Second, WarningCurrent: 1,+ }, true, "reference window must be zero or positive"},++ // ---- non-finite threshold (arm: "thresholds must be finite") ----+ // Exactly one field is non-finite so the big || fires deterministically.+ {"non-finite warning current rejected", ChangeThresholdSpec{+ Metric: "quarantine-spam", WarningCurrent: math.NaN(), CriticalCurrent: 1,+ }, true, "thresholds must be finite"},+ {"infinite critical delta rejected", ChangeThresholdSpec{+ Metric: "quarantine-spam", CriticalCurrent: 1, CriticalDelta: math.Inf(1),+ }, true, "thresholds must be finite"},++ // ---- negative percent (arm: "percent thresholds must not be negative") ----+ {"negative warning percent rejected", ChangeThresholdSpec{+ Metric: "quarantine-spam", WarningCurrent: 1, WarningPercent: -5,+ }, true, "percent thresholds must not be negative"},+ {"negative critical percent rejected", ChangeThresholdSpec{+ Metric: "quarantine-spam", CriticalCurrent: 1, CriticalPercent: -1,+ }, true, "percent thresholds must not be negative"},++ // ---- critical percent without critical delta (arm: "critical delta is required when critical percent is set") ----+ // WarningPercent is left at 0 so the warning guard does not fire first.+ {"critical percent without critical delta rejected", ChangeThresholdSpec{+ Metric: "quarantine-spam", CriticalCurrent: 1, CriticalPercent: 50,+ }, true, "critical delta is required when critical percent is set"},++ // ---- inverted percent (arm: "critical percent must be greater than or equal to warning percent") ----+ // Both percents > 0 with matching deltas so the percent/delta guards pass.+ {"critical percent below warning percent rejected", ChangeThresholdSpec{+ Metric: "quarantine-spam", CriticalCurrent: 1,+ WarningDelta: 250, CriticalDelta: 500, WarningPercent: 50, CriticalPercent: 25,+ }, true, "critical percent must be greater than or equal to warning percent"},++ // ---- no current or delta threshold (arm: "at least one current or delta threshold is required") ----+ // All currents/deltas zero and percents zero so every earlier guard passes.+ {"no current or delta threshold rejected", ChangeThresholdSpec{+ Metric: "quarantine-spam",+ }, true, "at least one current or delta threshold is required"},++ // ---- inverted current (arm: "critical current must be greater than or equal to warning current") ----+ {"critical current below warning current rejected", ChangeThresholdSpec{+ Metric: "quarantine-spam", WarningCurrent: 5000, CriticalCurrent: 2000,+ }, true, "critical current must be greater than or equal to warning current"},++ // ---- inverted delta (arm: "critical delta must be greater than or equal to warning delta") ----+ // Currents left at zero so the inverted-current guard is skipped.+ {"critical delta below warning delta rejected", ChangeThresholdSpec{+ Metric: "quarantine-spam", WarningDelta: 500, CriticalDelta: 250,+ }, true, "critical delta must be greater than or equal to warning delta"},++ // ---- boundary: equal current/delta pairs are accepted (not strictly inverted) ----+ {"equal warning and critical current accepted", ChangeThresholdSpec{+ Metric: "quarantine-spam", WarningCurrent: 2000, CriticalCurrent: 2000,+ }, false, ""},+ {"equal warning and critical delta accepted", ChangeThresholdSpec{+ Metric: "quarantine-spam", WarningDelta: 250, CriticalDelta: 250,+ }, false, ""},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ err := tc.spec.Validate()+ assertBranchcov0725amError(t, err, tc.wantErr, tc.wantSubstr)+ })+ }+}++// TestBranchcov0725amBaselineAnomalySpecValidate drives every distinct+// rejection reason in BaselineAnomalySpec.Validate (types.go:447) as its own+// case asserting the specific error, plus the accepting case. The existing+// suite already covers only the inverted-quiet-delta arm and the accept path;+// this adds the empty-metric, non-finite, negative-quiet-baseline,+// negative-ratio, non-positive-delta, inverted-ratio and inverted-delta arms.+func TestBranchcov0725amBaselineAnomalySpecValidate(t *testing.T) {+ t.Parallel()++ // A fully-valid baseline anomaly used as the base for rejection cases.+ valid := BaselineAnomalySpec{+ Metric: "spamIn",+ QuietBaseline: 40,+ WarningRatio: 1.8,+ CriticalRatio: 2.5,+ WarningDelta: 150,+ CriticalDelta: 300,+ QuietWarningDelta: 60,+ QuietCriticalDelta: 120,+ }++ cases := []struct {+ name string+ spec BaselineAnomalySpec+ wantErr bool+ wantSubstr string+ }{+ // ---- accepting case (arm: return nil) ----+ {"accepts fully populated spec", valid, false, ""},++ // ---- empty metric (arm: "metric is required") ----+ {"empty metric rejected", BaselineAnomalySpec{Metric: "\t", QuietBaseline: 1, WarningDelta: 1, CriticalDelta: 1, QuietWarningDelta: 1, QuietCriticalDelta: 1}, true, "metric is required"},++ // ---- non-finite threshold (arm: "thresholds must be finite") ----+ {"non-finite quiet baseline rejected", BaselineAnomalySpec{+ Metric: "spamIn", QuietBaseline: math.NaN(),+ WarningDelta: 1, CriticalDelta: 1, QuietWarningDelta: 1, QuietCriticalDelta: 1,+ }, true, "thresholds must be finite"},+ {"negative-infinite critical ratio rejected", BaselineAnomalySpec{+ Metric: "spamIn", QuietBaseline: 1, CriticalRatio: math.Inf(-1),+ WarningDelta: 1, CriticalDelta: 1, QuietWarningDelta: 1, QuietCriticalDelta: 1,+ }, true, "thresholds must be finite"},++ // ---- negative quiet baseline (arm: "quiet baseline must not be negative") ----+ {"negative quiet baseline rejected", BaselineAnomalySpec{+ Metric: "spamIn", QuietBaseline: -5,+ WarningDelta: 1, CriticalDelta: 1, QuietWarningDelta: 1, QuietCriticalDelta: 1,+ }, true, "quiet baseline must not be negative"},++ // ---- negative ratio (arm: "ratios must not be negative") ----+ {"negative warning ratio rejected", BaselineAnomalySpec{+ Metric: "spamIn", QuietBaseline: 40, WarningRatio: -1.8,+ WarningDelta: 1, CriticalDelta: 1, QuietWarningDelta: 1, QuietCriticalDelta: 1,+ }, true, "ratios must not be negative"},+ {"negative critical ratio rejected", BaselineAnomalySpec{+ Metric: "spamIn", QuietBaseline: 40, WarningRatio: 1.8, CriticalRatio: -2.5,+ WarningDelta: 1, CriticalDelta: 1, QuietWarningDelta: 1, QuietCriticalDelta: 1,+ }, true, "ratios must not be negative"},++ // ---- non-positive delta (arm: "delta thresholds must be positive") ----+ // Exactly one delta is zero (the rest positive) so the <= 0 guard fires.+ {"zero warning delta rejected", BaselineAnomalySpec{+ Metric: "spamIn", QuietBaseline: 40, WarningRatio: 1.8, CriticalRatio: 2.5,+ WarningDelta: 0, CriticalDelta: 300, QuietWarningDelta: 60, QuietCriticalDelta: 120,+ }, true, "delta thresholds must be positive"},++ // ---- inverted ratio (arm: "critical ratio must be greater than or equal to warning ratio") ----+ {"critical ratio below warning ratio rejected", BaselineAnomalySpec{+ Metric: "spamIn", QuietBaseline: 40, WarningRatio: 2.5, CriticalRatio: 1.8,+ WarningDelta: 150, CriticalDelta: 300, QuietWarningDelta: 60, QuietCriticalDelta: 120,+ }, true, "critical ratio must be greater than or equal to warning ratio"},++ // ---- inverted delta (arm: "critical delta must be greater than or equal to warning delta") ----+ {"critical delta below warning delta rejected", BaselineAnomalySpec{+ Metric: "spamIn", QuietBaseline: 40, WarningRatio: 1.8, CriticalRatio: 2.5,+ WarningDelta: 300, CriticalDelta: 150, QuietWarningDelta: 60, QuietCriticalDelta: 120,+ }, true, "critical delta must be greater than or equal to warning delta"},++ // ---- boundary: zero ratios are accepted (the ratio checks are skipped when ratios are 0) ----+ {"zero ratios with positive deltas accepted", BaselineAnomalySpec{+ Metric: "spamIn", QuietBaseline: 40, WarningRatio: 0, CriticalRatio: 0,+ WarningDelta: 150, CriticalDelta: 300, QuietWarningDelta: 60, QuietCriticalDelta: 120,+ }, false, ""},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ err := tc.spec.Validate()+ assertBranchcov0725amError(t, err, tc.wantErr, tc.wantSubstr)+ })+ }+}++// TestBranchcov0725amMetricTriggered drives every arm of metricTriggered+// (evaluator.go:701): the nil-spec early return, both valid directions with the+// metric value pinned at / just below / just above the trigger, and the+// unknown-direction default. Evaluate always feeds a non-nil validated spec, so+// only the direction arms (and only some of their outcomes) are covered today.+// The "latched" context is represented by repeating the at/just-above/just-below+// pinning with a spec that carries a Recovery pointer, proving metricTriggered+// is independent of latch state (it consults only Trigger/Direction).+func TestBranchcov0725amMetricTriggered(t *testing.T) {+ t.Parallel()++ above := func(recovery *float64) *MetricThresholdSpec {+ return &MetricThresholdSpec{Metric: "cpu", Direction: ThresholdDirectionAbove, Trigger: 90, Recovery: recovery}+ }+ below := func(recovery *float64) *MetricThresholdSpec {+ return &MetricThresholdSpec{Metric: "latency", Direction: ThresholdDirectionBelow, Trigger: 10, Recovery: recovery}+ }+ noRecovery := func() *float64 { return nil }++ cases := []struct {+ name string+ spec *MetricThresholdSpec+ observed float64+ want bool+ }{+ // nil spec short-circuits to false regardless of the observed value.+ {"nil spec returns false", nil, 9999, false},++ // direction above: triggered is observed >= Trigger (boundary-inclusive).+ {"above at trigger returns true", above(noRecovery()), 90, true},+ {"above just above trigger returns true", above(noRecovery()), 90.5, true},+ {"above just below trigger returns false", above(noRecovery()), 89.999, false},++ // direction below: triggered is observed <= Trigger (boundary-inclusive).+ {"below at trigger returns true", below(noRecovery()), 10, true},+ {"below just below trigger returns true", below(noRecovery()), 9.5, true},+ {"below just above trigger returns false", below(noRecovery()), 10.001, false},++ // unknown direction falls through to the default false arm.+ {"unknown direction returns false", &MetricThresholdSpec{Metric: "cpu", Direction: "sideways", Trigger: 90}, 9999, false},+ {"empty direction returns false", &MetricThresholdSpec{Metric: "cpu", Direction: "", Trigger: 90}, 9999, false},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ got := metricTriggered(tc.spec, tc.observed)+ if got != tc.want {+ t.Fatalf("metricTriggered(observed=%v) = %v, want %v", tc.observed, got, tc.want)+ }+ })+ }+}++// TestBranchcov0725amMetricStillLatched drives every arm of metricStillLatched+// (evaluator.go:715): the nil-spec early return, the nil-Recovery early return,+// both valid directions with the metric pinned at / just below / just above the+// recovery threshold (note the comparison is strict, so observed == recovery is+// "recovered" = false), and the unknown-direction default. The "still latched"+// true outcome and the "recovered / unlatched" false outcome are both driven for+// each direction.+func TestBranchcov0725amMetricStillLatched(t *testing.T) {+ t.Parallel()++ aboveRecovery := func() *float64 { v := 85.0; return &v }+ belowRecovery := func() *float64 { v := 15.0; return &v }++ cases := []struct {+ name string+ spec *MetricThresholdSpec+ observed float64+ want bool+ }{+ // nil spec short-circuits to false.+ {"nil spec returns false", nil, 9999, false},++ // nil Recovery short-circuits to false (no latch point defined).+ {"nil recovery returns false", &MetricThresholdSpec{Metric: "cpu", Direction: ThresholdDirectionAbove, Trigger: 90}, 9999, false},++ // direction above: still latched is observed > *Recovery (strict).+ {"above just above recovery returns true (latched)", &MetricThresholdSpec{Metric: "cpu", Direction: ThresholdDirectionAbove, Trigger: 90, Recovery: aboveRecovery()}, 86, true},+ {"above at recovery returns false (recovered)", &MetricThresholdSpec{Metric: "cpu", Direction: ThresholdDirectionAbove, Trigger: 90, Recovery: aboveRecovery()}, 85, false},+ {"above just below recovery returns false", &MetricThresholdSpec{Metric: "cpu", Direction: ThresholdDirectionAbove, Trigger: 90, Recovery: aboveRecovery()}, 84.999, false},++ // direction below: still latched is observed < *Recovery (strict).+ {"below just below recovery returns true (latched)", &MetricThresholdSpec{Metric: "cpu", Direction: ThresholdDirectionBelow, Trigger: 10, Recovery: belowRecovery()}, 14, true},+ {"below at recovery returns false (recovered)", &MetricThresholdSpec{Metric: "cpu", Direction: ThresholdDirectionBelow, Trigger: 10, Recovery: belowRecovery()}, 15, false},+ {"below just above recovery returns false", &MetricThresholdSpec{Metric: "cpu", Direction: ThresholdDirectionBelow, Trigger: 10, Recovery: belowRecovery()}, 15.001, false},++ // unknown direction with a Recovery set still falls through to false.+ {"unknown direction returns false", &MetricThresholdSpec{Metric: "cpu", Direction: "sideways", Trigger: 90, Recovery: aboveRecovery()}, 9999, false},+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ got := metricStillLatched(tc.spec, tc.observed)+ if got != tc.want {+ t.Fatalf("metricStillLatched(observed=%v) = %v, want %v", tc.observed, got, tc.want)+ }+ })+ }+}