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 eval CLI parsers, cloud audit predicates and vmware fixture fetching

rcourtman6e9fb0188791
diff --git a/cmd/eval/main_parsers_branchcov0723am_test.go b/cmd/eval/main_parsers_branchcov0723am_test.go
new file mode 100644
index 0000000000..2806083aa5
--- /dev/null
+++ b/cmd/eval/main_parsers_branchcov0723am_test.go
@@ -0,0 +1,709 @@
+package main
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/eval"
+)
+
+// These tests target the pure parser/helper functions in main.go (the
+// auto-selection and CLI machinery). They were chosen because they have no
+// network or model dependency, so every branch can be driven deterministically.
+//
+// fetchAutoModels is intentionally NOT covered here: it issues a live HTTP
+// request and the package has no mock server. listScenarios is also skipped:
+// it only prints to stdout and this package has no pre-existing convention for
+// capturing os.Stdout.
+
+// TestBranchcov0723AmEnvBool pins every arm of envBool. The source uses
+// os.LookupEnv and lowercases+trims the value before a switch, so an unset
+// key and an empty-string value both fall through to the default arm and
+// return (false, false) — i.e. unset and empty are NOT distinguished.
+func TestBranchcov0723AmEnvBool(t *testing.T) {
+ const key = "EVAL_TEST_BRANCHCOV_BOOL"
+
+ t.Run("unset returns false false", func(t *testing.T) {
+ // Use a key that was never set. t.Setenv cannot express "unset", so
+ // we rely on a uniquely-named key the environment does not carry.
+ got, ok := envBool("EVAL_TEST_BRANCHCOV_BOOL_DEFINITELY_UNSET")
+ if ok {
+ t.Fatalf("unset key ok=true, want false")
+ }
+ if got {
+ t.Fatalf("unset key got=true, want false")
+ }
+ })
+
+ truthy := []string{"1", "true", "TRUE", "True", "yes", "YES", "y", "Y", "on", "ON", " true ", "\ton\n"}
+ for _, v := range truthy {
+ v := v
+ t.Run("truthy spelling "+v, func(t *testing.T) {
+ t.Setenv(key, v)
+ got, ok := envBool(key)
+ if !ok {
+ t.Fatalf("envBool(%q) ok=false, want true", v)
+ }
+ if !got {
+ t.Fatalf("envBool(%q) got=false, want true", v)
+ }
+ })
+ }
+
+ falsy := []string{"0", "false", "FALSE", "False", "no", "NO", "n", "N", "off", "OFF", " off "}
+ for _, v := range falsy {
+ v := v
+ t.Run("falsy spelling "+v, func(t *testing.T) {
+ t.Setenv(key, v)
+ got, ok := envBool(key)
+ if !ok {
+ t.Fatalf("envBool(%q) ok=false, want true", v)
+ }
+ if got {
+ t.Fatalf("envBool(%q) got=true, want false", v)
+ }
+ })
+ }
+
+ t.Run("garbage returns false false", func(t *testing.T) {
+ t.Setenv(key, "maybe")
+ got, ok := envBool(key)
+ if ok {
+ t.Fatalf("garbage ok=true, want false")
+ }
+ if got {
+ t.Fatalf("garbage got=true, want false")
+ }
+ })
+
+ t.Run("empty string set is not distinguished from unset", func(t *testing.T) {
+ t.Setenv(key, "")
+ got, ok := envBool(key)
+ // Source: LookupEnv returns ("", true), then TrimSpace("")=="" which
+ // hits the default arm of the switch -> (false, false). Identical to
+ // the unset path.
+ if ok {
+ t.Fatalf("empty-string value ok=true, want false (should collapse to unset)")
+ }
+ if got {
+ t.Fatalf("empty-string value got=true, want false")
+ }
+ })
+}
+
+// TestBranchcov0723AmEnvInt pins envInt, which uses fmt.Sscanf "%d". The
+// "%d" verb is lenient: it parses a leading integer out of "12abc" (-> 12),
+// accepts "+7" and "-5", but errors (and yields ok=false) on pure garbage,
+// empty, and overflow.
+func TestBranchcov0723AmEnvInt(t *testing.T) {
+ const key = "EVAL_TEST_BRANCHCOV_INT"
+
+ t.Run("unset returns 0 false", func(t *testing.T) {
+ got, ok := envInt("EVAL_TEST_BRANCHCOV_INT_DEFINITELY_UNSET")
+ if ok {
+ t.Fatalf("unset ok=true, want false")
+ }
+ if got != 0 {
+ t.Fatalf("unset got=%d, want 0", got)
+ }
+ })
+
+ cases := []struct {
+ name string
+ value string
+ want int
+ wantOK bool
+ }{
+ {"plain positive", "42", 42, true},
+ {"negative", "-5", -5, true},
+ {"plus sign", "+7", 7, true},
+ {"surrounding whitespace trimmed by source", " 42 ", 42, true},
+ {"leading integer parsed out of trailing garbage", "12abc", 12, true},
+ {"hex prefix parses leading zero then stops", "0x10", 0, true},
+ {"pure garbage fails", "abc", 0, false},
+ {"empty string set fails like unset", "", 0, false},
+ {"overflow fails", "99999999999999999999999", 0, false},
+ }
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ t.Setenv(key, tc.value)
+ got, ok := envInt(key)
+ if ok != tc.wantOK {
+ t.Fatalf("envInt(%q) ok=%v, want %v", tc.value, ok, tc.wantOK)
+ }
+ if got != tc.want {
+ t.Fatalf("envInt(%q) got=%d, want %d", tc.value, got, tc.want)
+ }
+ })
+ }
+}
+
+// TestBranchcov0723AmParseModelList pins parseModelList: trims, splits on
+// comma, drops empty fields, and does NOT dedup.
+func TestBranchcov0723AmParseModelList(t *testing.T) {
+ cases := []struct {
+ name string
+ raw string
+ want []string
+ }{
+ {"empty is nil", "", nil},
+ {"whitespace only is nil", " \t\n ", nil},
+ {"single", "openai:gpt-4", []string{"openai:gpt-4"}},
+ {"several", "openai:gpt-4, anthropic:claude ,gemini:pro", []string{"openai:gpt-4", "anthropic:claude", "gemini:pro"}},
+ {"duplicates kept (no dedup)", "openai:a,openai:a,openai:b", []string{"openai:a", "openai:a", "openai:b"}},
+ {"leading separator drops empty first field", ",openai:a,openai:b", []string{"openai:a", "openai:b"}},
+ {"trailing separator drops empty last field", "openai:a,openai:b,", []string{"openai:a", "openai:b"}},
+ {"interior empty fields dropped", "openai:a,,openai:b", []string{"openai:a", "openai:b"}},
+ // All-comma input is NOT nil: after trimming the raw string is still
+ // ",,," (non-empty), so the source reaches `make` and returns a
+ // non-nil empty slice. Only truly empty/whitespace input returns nil.
+ {"all-empty fields yields non-nil empty slice", ",,,", []string{}},
+ }
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ got := parseModelList(tc.raw)
+ if len(got) != len(tc.want) {
+ t.Fatalf("parseModelList(%q)=%v, want %v", tc.raw, got, tc.want)
+ }
+ for i := range tc.want {
+ if got[i] != tc.want[i] {
+ t.Fatalf("parseModelList(%q)[%d]=%q, want %q (full: %v)", tc.raw, i, got[i], tc.want[i], got)
+ }
+ }
+ if tc.want == nil && got != nil {
+ t.Fatalf("parseModelList(%q)=%v, want nil", tc.raw, got)
+ }
+ })
+ }
+}
+
+// TestBranchcov0723AmParseProviderFilter pins parseProviderFilter: it does
+// NOT lowercase, so mixed-case entries become distinct keys. Returns nil for
+// empty input.
+func TestBranchcov0723AmParseProviderFilter(t *testing.T) {
+ t.Run("empty is nil", func(t *testing.T) {
+ if got := parseProviderFilter(""); got != nil {
+ t.Fatalf("parseProviderFilter(\"\")=%v, want nil", got)
+ }
+ })
+ t.Run("whitespace only is nil", func(t *testing.T) {
+ if got := parseProviderFilter(" "); got != nil {
+ t.Fatalf("parseProviderFilter(\" \")=%v, want nil", got)
+ }
+ })
+ t.Run("single provider", func(t *testing.T) {
+ got := parseProviderFilter("openai")
+ if len(got) != 1 || !got["openai"] {
+ t.Fatalf("parseProviderFilter(\"openai\")=%v, want {openai:true}", got)
+ }
+ })
+ t.Run("several providers trimmed", func(t *testing.T) {
+ got := parseProviderFilter("openai, anthropic , gemini")
+ want := map[string]bool{"openai": true, "anthropic": true, "gemini": true}
+ if len(got) != 3 || !got["openai"] || !got["anthropic"] || !got["gemini"] {
+ t.Fatalf("parseProviderFilter got=%v, want %v", got, want)
+ }
+ })
+ t.Run("duplicates collapse into one key", func(t *testing.T) {
+ got := parseProviderFilter("openai,openai,openai")
+ if len(got) != 1 || !got["openai"] {
+ t.Fatalf("duplicates got=%v, want single {openai:true}", got)
+ }
+ })
+ t.Run("NOT lowercased: case variants are distinct keys", func(t *testing.T) {
+ // The whole point of pinning this: parseProviderFilter preserves case,
+ // unlike parseExcludeKeywords which lowercases.
+ got := parseProviderFilter("OpenAI,openai,OPENAI")
+ if len(got) != 3 {
+ t.Fatalf("case variants got=%v, want 3 distinct keys", got)
+ }
+ if !got["OpenAI"] || !got["openai"] || !got["OPENAI"] {
+ t.Fatalf("case variants got=%v, want OpenAI/openai/OPENAI all true", got)
+ }
+ })
+ t.Run("empty fields dropped", func(t *testing.T) {
+ got := parseProviderFilter(",openai,,")
+ if len(got) != 1 || !got["openai"] {
+ t.Fatalf("got=%v, want {openai:true}", got)
+ }
+ })
+}
+
+// TestBranchcov0723AmParseProviderFilterWithDefault pins the ONLY behaviour
+// that distinguishes this function from parseProviderFilter: empty/whitespace
+// input returns the fixed six-provider default map; any other input
+// delegates to parseProviderFilter unchanged.
+func TestBranchcov0723AmParseProviderFilterWithDefault(t *testing.T) {
+ expectedDefault := map[string]bool{
+ "openai": true,
+ "openrouter": true,
+ "anthropic": true,
+ "deepseek": true,
+ "gemini": true,
+ "ollama": true,
+ }
+ t.Run("empty input yields the six-provider default", func(t *testing.T) {
+ got := parseProviderFilterWithDefault("")
+ if len(got) != len(expectedDefault) {
+ t.Fatalf("default len=%d, want %d (%v)", len(got), len(expectedDefault), got)
+ }
+ for k := range expectedDefault {
+ if !got[k] {
+ t.Fatalf("default map missing %q, got=%v", k, got)
+ }
+ }
+ })
+ t.Run("whitespace input also yields the default", func(t *testing.T) {
+ got := parseProviderFilterWithDefault(" \t ")
+ for k := range expectedDefault {
+ if !got[k] {
+ t.Fatalf("whitespace default missing %q, got=%v", k, got)
+ }
+ }
+ })
+ t.Run("non-empty delegates to parseProviderFilter (not the default)", func(t *testing.T) {
+ // A single custom provider must NOT be merged with the defaults.
+ got := parseProviderFilterWithDefault("acme")
+ if len(got) != 1 || !got["acme"] {
+ t.Fatalf("non-empty got=%v, want {acme:true} only (no defaults)", got)
+ }
+ if got["openai"] {
+ t.Fatalf("non-empty input leaked default openai into result: %v", got)
+ }
+ })
+ t.Run("non-empty lowercases-not, matching parseProviderFilter", func(t *testing.T) {
+ got := parseProviderFilterWithDefault("OpenAI")
+ if len(got) != 1 || !got["OpenAI"] || got["openai"] {
+ t.Fatalf("case preserved? got=%v", got)
+ }
+ })
+}
+
+// TestBranchcov0723AmParseExcludeKeywords pins parseExcludeKeywords, whose
+// normalisation differs from parseProviderFilter: it LOWERCASES each entry,
+// and it has a default keyword list plus a "disable" sentinel.
+func TestBranchcov0723AmParseExcludeKeywords(t *testing.T) {
+ t.Run("empty yields the default keyword list", func(t *testing.T) {
+ got := parseExcludeKeywords("")
+ // Pin a representative subset of the well-known defaults plus the
+ // exact length so additions are noticed.
+ wantCount := 14
+ if len(got) != wantCount {
+ t.Fatalf("default exclude list len=%d, want %d (%v)", len(got), wantCount, got)
+ }
+ mustContain := []string{"codex", "image", "vision", "video", "audio", "speech", "embed", "embedding", "moderation", "rerank", "tts", "realtime", "transcribe", "openai:gpt-5.2-pro"}
+ gotSet := make(map[string]bool, len(got))
+ for _, k := range got {
+ gotSet[k] = true
+ }
+ for _, w := range mustContain {
+ if !gotSet[w] {
+ t.Fatalf("default list missing %q, got=%v", w, got)
+ }
+ }
+ })
+ t.Run("whitespace yields the default keyword list", func(t *testing.T) {
+ got := parseExcludeKeywords(" \t ")
+ if len(got) == 0 {
+ t.Fatalf("whitespace should yield default list, got empty")
+ }
+ })
+
+ disableSentinels := []string{"0", "false", "off", "none", "FALSE", "Off", "NONE"}
+ for _, s := range disableSentinels {
+ s := s
+ t.Run("disable sentinel "+s+" returns nil", func(t *testing.T) {
+ got := parseExcludeKeywords(s)
+ if got != nil {
+ t.Fatalf("parseExcludeKeywords(%q)=%v, want nil", s, got)
+ }
+ })
+ }
+
+ t.Run("single keyword lowercased", func(t *testing.T) {
+ got := parseExcludeKeywords("Image")
+ if len(got) != 1 || got[0] != "image" {
+ t.Fatalf("got=%v, want [image]", got)
+ }
+ })
+ t.Run("several keywords trimmed and lowercased", func(t *testing.T) {
+ got := parseExcludeKeywords("Image, VISION ,Audio")
+ want := []string{"image", "vision", "audio"}
+ if len(got) != len(want) {
+ t.Fatalf("got=%v, want %v", got, want)
+ }
+ for i, w := range want {
+ if got[i] != w {
+ t.Fatalf("got[%d]=%q, want %q (full: %v)", i, got[i], w, got)
+ }
+ }
+ })
+ t.Run("empty fields dropped", func(t *testing.T) {
+ got := parseExcludeKeywords(",image,,")
+ if len(got) != 1 || got[0] != "image" {
+ t.Fatalf("got=%v, want [image]", got)
+ }
+ })
+ t.Run("custom keyword with colon preserved after lowercasing", func(t *testing.T) {
+ // A custom exclusion like a model id should survive intact (lowercased).
+ got := parseExcludeKeywords("OpenAI:GPT-4-Vision")
+ if len(got) != 1 || got[0] != "openai:gpt-4-vision" {
+ t.Fatalf("got=%v, want [openai:gpt-4-vision]", got)
+ }
+ })
+}
+
+// TestBranchcov0723AmHasAnyKeyword pins hasAnyKeyword. The source builds
+// target = lowercased(ID + " " + Name + " " + Description) and applies
+// case-sensitive strings.Contains against each (un-lowercased) keyword, so a
+// mixed-case keyword will NOT match even when its lowercase would.
+func TestBranchcov0723AmHasAnyKeyword(t *testing.T) {
+ model := apiModelInfo{
+ ID: "openai:probe-id-123",
+ Name: "SpecialNameToken",
+ Description: "UniqueDescToken here",
+ }
+
+ t.Run("nil keywords false", func(t *testing.T) {
+ if hasAnyKeyword(model, nil) {
+ t.Fatalf("nil keywords -> true, want false")
+ }
+ })
+ t.Run("empty keywords slice false", func(t *testing.T) {
+ if hasAnyKeyword(model, []string{}) {
+ t.Fatalf("empty slice -> true, want false")
+ }
+ })
+ t.Run("only empty-string keywords skipped -> false", func(t *testing.T) {
+ if hasAnyKeyword(model, []string{"", "", ""}) {
+ t.Fatalf("only-empty keywords -> true, want false")
+ }
+ })
+ t.Run("keyword matching ID field", func(t *testing.T) {
+ if !hasAnyKeyword(model, []string{"probe-id-123"}) {
+ t.Fatalf("keyword in ID should match")
+ }
+ })
+ t.Run("keyword matching Name field", func(t *testing.T) {
+ if !hasAnyKeyword(model, []string{"specialnametoken"}) {
+ t.Fatalf("lowercased keyword in Name should match")
+ }
+ })
+ t.Run("keyword matching Description field", func(t *testing.T) {
+ if !hasAnyKeyword(model, []string{"uniquedesctoken"}) {
+ t.Fatalf("lowercased keyword in Description should match")
+ }
+ })
+ t.Run("mixed-case keyword does NOT match (target is lowercased, keyword is not)", func(t *testing.T) {
+ // "SpecialNameToken" lowercased becomes "specialnametoken" in target;
+ // Contains is case-sensitive, so the uppercase keyword fails.
+ if hasAnyKeyword(model, []string{"SpecialNameToken"}) {
+ t.Fatalf("mixed-case keyword should not match lowercased target")
+ }
+ })
+ t.Run("near-miss non-existent keyword false", func(t *testing.T) {
+ if hasAnyKeyword(model, []string{"zzz-not-present-anywhere"}) {
+ t.Fatalf("non-existent keyword should not match")
+ }
+ })
+ t.Run("empty keyword alongside a real match still matches", func(t *testing.T) {
+ if !hasAnyKeyword(model, []string{"", "probe-id-123"}) {
+ t.Fatalf("empty+real keyword should match on the real one")
+ }
+ })
+}
+
+// TestBranchcov0723AmCountProvider pins countProvider: matching is a strict
+// prefix test on "<provider>:", so a provider name appearing anywhere other
+// than the prefix is NOT counted.
+func TestBranchcov0723AmCountProvider(t *testing.T) {
+ t.Run("empty provider returns 0", func(t *testing.T) {
+ if got := countProvider([]string{"openai:a", "openai:b"}, ""); got != 0 {
+ t.Fatalf("empty provider -> %d, want 0", got)
+ }
+ })
+ t.Run("empty models returns 0", func(t *testing.T) {
+ if got := countProvider(nil, "openai"); got != 0 {
+ t.Fatalf("nil models -> %d, want 0", got)
+ }
+ })
+ t.Run("no match returns 0", func(t *testing.T) {
+ got := countProvider([]string{"anthropic:claude", "gemini:pro"}, "openai")
+ if got != 0 {
+ t.Fatalf("no match -> %d, want 0", got)
+ }
+ })
+ t.Run("several matches counted", func(t *testing.T) {
+ got := countProvider([]string{"openai:gpt-4", "openai:gpt-3.5", "anthropic:claude", "openai:o1"}, "openai")
+ if got != 3 {
+ t.Fatalf("got %d, want 3", got)
+ }
+ })
+ t.Run("provider substring in non-prefix position not counted", func(t *testing.T) {
+ // HasPrefix("foo-openai-bar", "openai:") is false.
+ got := countProvider([]string{"foo-openai-bar", "prefix:openai:thing"}, "openai")
+ if got != 0 {
+ t.Fatalf("non-prefix occurrence -> %d, want 0", got)
+ }
+ })
+ t.Run("bare provider name without colon not counted", func(t *testing.T) {
+ // "openai" does not start with "openai:".
+ got := countProvider([]string{"openai", "openaiproxy:x"}, "openai")
+ if got != 0 {
+ t.Fatalf("bare provider name -> %d, want 0", got)
+ }
+ })
+}
+
+// TestBranchcov0723AmSelectionReason covers all six reachable reason strings
+// of selectionReason by driving (model.Notable, model.CreatedAt, stat.Notable)
+// through every combination.
+func TestBranchcov0723AmSelectionReason(t *testing.T) {
+ // 1704067200 = 2024-01-01 00:00:00 UTC -> "2024-01-02"? Verify:
+ // time.Unix(1704067200,0).UTC() = 2024-01-01 00:00:00 -> Format "2006-01-02" = "2024-01-01".
+ const ts2024 = 1704067200
+ cases := []struct {
+ name string
+ model apiModelInfo
+ stat providerStats
+ want string
+ }{
+ {
+ name: "notable stat zero and model notable",
+ model: apiModelInfo{Notable: true, CreatedAt: ts2024},
+ stat: providerStats{Total: 1, Notable: 0},
+ want: "no notable models; notable",
+ },
+ {
+ name: "notable stat zero and model not notable with created_at",
+ model: apiModelInfo{Notable: false, CreatedAt: ts2024},
+ stat: providerStats{Total: 1, Notable: 0},
+ want: "no notable models; created_at=2024-01-01",
+ },
+ {
+ name: "notable stat zero and model not notable without created_at (fallback)",
+ model: apiModelInfo{Notable: false, CreatedAt: 0},
+ stat: providerStats{Total: 1, Notable: 0},
+ want: "no notable models; fallback",
+ },
+ {
+ name: "stat has notable and model notable",
+ model: apiModelInfo{Notable: true, CreatedAt: ts2024},
+ stat: providerStats{Total: 2, Notable: 1},
+ want: "notable",
+ },
+ {
+ name: "stat has notable and model not notable with created_at",
+ model: apiModelInfo{Notable: false, CreatedAt: ts2024},
+ stat: providerStats{Total: 2, Notable: 1},
+ want: "created_at=2024-01-01",
+ },
+ {
+ name: "stat has notable and model not notable without created_at (fallback)",
+ model: apiModelInfo{Notable: false, CreatedAt: 0},
+ stat: providerStats{Total: 2, Notable: 1},
+ want: "fallback",
+ },
+ }
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ got := selectionReason(tc.model, tc.stat)
+ if got != tc.want {
+ t.Fatalf("selectionReason(...) = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+// TestBranchcov0723AmSortedProviders pins the exact sort (ascending string
+// order over the map keys) plus determinism across randomised map iteration.
+func TestBranchcov0723AmSortedProviders(t *testing.T) {
+ t.Run("nil map returns empty slice", func(t *testing.T) {
+ got := sortedProviders(nil)
+ if len(got) != 0 {
+ t.Fatalf("nil map -> %v, want empty", got)
+ }
+ })
+ t.Run("empty map returns empty slice", func(t *testing.T) {
+ got := sortedProviders(map[string]providerStats{})
+ if len(got) != 0 {
+ t.Fatalf("empty map -> %v, want empty", got)
+ }
+ })
+ t.Run("exact ascending order regardless of insertion", func(t *testing.T) {
+ stats := map[string]providerStats{
+ "openrouter": {Total: 2},
+ "openai": {Total: 5},
+ "anthropic": {Total: 1},
+ "deepseek": {Total: 3},
+ "ollama": {Total: 1},
+ "gemini": {Total: 1},
+ }
+ got := sortedProviders(stats)
+ want := []string{"anthropic", "deepseek", "gemini", "ollama", "openai", "openrouter"}
+ if len(got) != len(want) {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("index %d got %q, want ordering %v (full got=%v)", i, got[i], want, got)
+ }
+ }
+ })
+ t.Run("deterministic across many calls over random map iteration", func(t *testing.T) {
+ stats := map[string]providerStats{
+ "openrouter": {},
+ "openai": {},
+ "anthropic": {},
+ "deepseek": {},
+ "ollama": {},
+ "gemini": {},
+ "mistral": {},
+ "cohere": {},
+ "meta": {},
+ "ai21": {},
+ }
+ first := sortedProviders(stats)
+ firstKey := strings.Join(first, ",")
+ for i := 0; i < 200; i++ {
+ got := sortedProviders(stats)
+ if k := strings.Join(got, ","); k != firstKey {
+ t.Fatalf("iteration %d produced %v, want deterministic %v", i, got, first)
+ }
+ }
+ })
+}
+
+// TestBranchcov0723AmGetPatrolScenarios asserts the exact scenario NAMES for
+// each switch arm, including the patrol-quality alias and the empty/unknown
+// fallback to nil.
+func TestBranchcov0723AmGetPatrolScenarios(t *testing.T) {
+ names := func(scenarios []eval.PatrolScenario) []string {
+ out := make([]string, len(scenarios))
+ for i, s := range scenarios {
+ out[i] = s.Name
+ }
+ return out
+ }
+ t.Run("patrol returns all four in declared order", func(t *testing.T) {
+ got := names(getPatrolScenarios("patrol"))
+ want := []string{"Patrol Basic Run", "Patrol Investigation Quality", "Patrol Finding Quality", "Patrol Signal Coverage"}
+ if len(got) != len(want) {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("index %d got %q, want %q (full: %v)", i, got[i], want[i], got)
+ }
+ }
+ })
+ t.Run("patrol-basic", func(t *testing.T) {
+ got := names(getPatrolScenarios("patrol-basic"))
+ want := []string{"Patrol Basic Run"}
+ if len(got) != 1 || got[0] != want[0] {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ })
+ t.Run("patrol-investigation", func(t *testing.T) {
+ got := names(getPatrolScenarios("patrol-investigation"))
+ want := []string{"Patrol Investigation Quality"}
+ if len(got) != 1 || got[0] != want[0] {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ })
+ t.Run("patrol-finding-quality", func(t *testing.T) {
+ got := names(getPatrolScenarios("patrol-finding-quality"))
+ want := []string{"Patrol Finding Quality"}
+ if len(got) != 1 || got[0] != want[0] {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ })
+ t.Run("patrol-signal-coverage", func(t *testing.T) {
+ got := names(getPatrolScenarios("patrol-signal-coverage"))
+ want := []string{"Patrol Signal Coverage"}
+ if len(got) != 1 || got[0] != want[0] {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ })
+ t.Run("patrol-quality alias maps to signal coverage", func(t *testing.T) {
+ got := names(getPatrolScenarios("patrol-quality"))
+ want := []string{"Patrol Signal Coverage"}
+ if len(got) != 1 || got[0] != want[0] {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ })
+ t.Run("unknown name returns nil", func(t *testing.T) {
+ if got := getPatrolScenarios("does-not-exist"); got != nil {
+ t.Fatalf("unknown -> %v, want nil", got)
+ }
+ })
+ t.Run("empty name returns nil", func(t *testing.T) {
+ if got := getPatrolScenarios(""); got != nil {
+ t.Fatalf("empty -> %v, want nil", got)
+ }
+ })
+}
+
+// TestBranchcov0723AmGetScenarios asserts the scenario NAMES for a single
+// scenario arm, two collection arms (all and matrix), and the empty/unknown
+// fallback to nil.
+func TestBranchcov0723AmGetScenarios(t *testing.T) {
+ names := func(scenarios []eval.Scenario) []string {
+ out := make([]string, len(scenarios))
+ for i, s := range scenarios {
+ out[i] = s.Name
+ }
+ return out
+ }
+ t.Run("smoke returns single Quick Smoke Test", func(t *testing.T) {
+ got := names(getScenarios("smoke"))
+ want := []string{"Quick Smoke Test"}
+ if len(got) != 1 || got[0] != want[0] {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ })
+ t.Run("all returns the 11 basic scenarios in declared order", func(t *testing.T) {
+ got := names(getScenarios("all"))
+ want := []string{
+ "Quick Smoke Test",
+ "Read-Only Infrastructure",
+ "Routing Validation",
+ "Routing Mismatch Recovery",
+ "Log Tailing (Bounded)",
+ "Read-Only Violation Recovery",
+ "Search Then Get By ID",
+ "Ambiguous Resource Disambiguation",
+ "Context Target Carryover",
+ "Resource Context Handoff",
+ "Infrastructure Discovery",
+ }
+ if len(got) != len(want) {
+ t.Fatalf("all -> %d scenarios %v, want %d (%v)", len(got), got, len(want), want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("all[%d] = %q, want %q (full: %v)", i, got[i], want[i], got)
+ }
+ }
+ })
+ t.Run("matrix returns smoke + readonly only", func(t *testing.T) {
+ got := names(getScenarios("matrix"))
+ want := []string{"Quick Smoke Test", "Read-Only Infrastructure"}
+ if len(got) != 2 || got[0] != want[0] || got[1] != want[1] {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+ })
+ t.Run("unknown name returns nil", func(t *testing.T) {
+ if got := getScenarios("totally-unknown-scenario"); got != nil {
+ t.Fatalf("unknown -> %v, want nil", got)
+ }
+ })
+ t.Run("empty name returns nil", func(t *testing.T) {
+ if got := getScenarios(""); got != nil {
+ t.Fatalf("empty -> %v, want nil", got)
+ }
+ })
+}
diff --git a/internal/actionlifecycle/service_errors_branchcov0723am_test.go b/internal/actionlifecycle/service_errors_branchcov0723am_test.go
new file mode 100644
index 0000000000..e7fed65524
--- /dev/null
+++ b/internal/actionlifecycle/service_errors_branchcov0723am_test.go
@@ -0,0 +1,386 @@
+package actionlifecycle
+
+import (
+ "errors"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// TestBranchcov0723Am_AvailabilityCheckError covers both the Error() format
+// and the Unwrap() cause-reachability for AvailabilityCheckError, including
+// the populated-cause, nil-cause (zero-value), and errors.Is/errors.As paths.
+// The other typed errors in service.go are already exercised by
+// TestTypedError_Error_FormatsFields / TestTypedError_Unwrap in
+// dispatch_context_branchcov0718_test.go; AvailabilityCheckError is the one
+// gap those tests leave.
+func TestBranchcov0723Am_AvailabilityCheckError(t *testing.T) {
+ cause := errors.New("registry probe timed out")
+
+ t.Run("populated_cause_formats_message_and_unwraps", func(t *testing.T) {
+ err := &AvailabilityCheckError{Err: cause}
+ want := "action execution availability check: registry probe timed out"
+ if got := err.Error(); got != want {
+ t.Fatalf("Error()=%q; want %q", got, want)
+ }
+ if unwrapped := err.Unwrap(); unwrapped != cause {
+ t.Fatalf("Unwrap()=%v; want %v", unwrapped, cause)
+ }
+ if !errors.Is(err, cause) {
+ t.Fatalf("errors.Is(err, cause)=false; want true")
+ }
+ var target *AvailabilityCheckError
+ if !errors.As(err, &target) || target.Err != cause {
+ t.Fatalf("errors.As target=%#v; want wrapped cause", target)
+ }
+ })
+
+ t.Run("zero_value_renders_nil_cause_and_unwraps_to_nil", func(t *testing.T) {
+ err := &AvailabilityCheckError{}
+ // %v on a nil interface renders as "<nil>".
+ want := "action execution availability check: <nil>"
+ if got := err.Error(); got != want {
+ t.Fatalf("Error()=%q; want %q", got, want)
+ }
+ if unwrapped := err.Unwrap(); unwrapped != nil {
+ t.Fatalf("Unwrap()=%v; want nil", unwrapped)
+ }
+ // errors.Is against a non-nil sentinel must be false when the chain
+ // has no matching target.
+ if errors.Is(err, cause) {
+ t.Fatalf("errors.Is(zero-value err, cause)=true; want false")
+ }
+ })
+}
+
+// failingCreateStore embeds a real ResourceStore and forces CreateActionAudit
+// to return the configured error, mirroring the barrierDecisionStore /
+// delayedCreateStore wrapper pattern used elsewhere in this package.
+type failingCreateStore struct {
+ unified.ResourceStore
+ createErr error
+}
+
+func (s *failingCreateStore) CreateActionAudit(record unified.ActionAuditRecord, events []unified.ActionLifecycleEvent) (unified.ActionAuditRecord, bool, error) {
+ return unified.ActionAuditRecord{}, false, s.createErr
+}
+
+// TestBranchcov0723Am_PersistPlanAudit drives PersistPlanAudit through every
+// branch of persistPlanAudit: the store-error path, the success path for both
+// PlannedActionState arms (single planned event vs. appended pending event),
+// idempotent replan (created=false, no error), a zero-value request, and a
+// minimal plan with no blast-radius/preflight payload. Audit fields are read
+// back through the same store rather than asserted from the return value
+// alone.
+func TestBranchcov0723Am_PersistPlanAudit(t *testing.T) {
+ plannedAt := time.Date(2026, 7, 23, 9, 30, 0, 0, time.UTC)
+
+ t.Run("store_error_is_propagated_unchanged", func(t *testing.T) {
+ storeErr := errors.New("disk write failed")
+ store := &failingCreateStore{ResourceStore: unified.NewMemoryStore(), createErr: storeErr}
+ req := unified.ActionRequest{RequestID: "req-1", ResourceID: "vm:42", CapabilityName: "restart", RequestedBy: "agent:test"}
+ plan := unified.ActionPlan{ActionID: "act-1", RequestID: "req-1", PlannedAt: plannedAt}
+ err := PersistPlanAudit(store, req, plan)
+ if !errors.Is(err, storeErr) {
+ t.Fatalf("PersistPlanAudit err=%v; want %v", err, storeErr)
+ }
+ if got := err.Error(); got != storeErr.Error() {
+ t.Fatalf("error message=%q; want %q (must not be swallowed)", got, storeErr.Error())
+ }
+ // No audit may have been persisted when the create failed.
+ if _, found, qerr := store.GetActionAudit("act-1"); qerr != nil || found {
+ t.Fatalf("audit persisted despite error: found=%v err=%v", found, qerr)
+ }
+ })
+
+ t.Run("success_planned_state_records_single_event", func(t *testing.T) {
+ store := unified.NewMemoryStore()
+ req := unified.ActionRequest{
+ RequestID: "req-1",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ Params: map[string]any{"mode": "graceful"},
+ Reason: "Recover after confirmed outage",
+ RequestedBy: "agent:test",
+ }
+ plan := unified.ActionPlan{
+ ActionID: "act-planned",
+ RequestID: "req-1",
+ Allowed: true,
+ RequiresApproval: false,
+ PlannedAt: plannedAt,
+ PlanHash: "sha256:abc",
+ }
+ if err := PersistPlanAudit(store, req, plan); err != nil {
+ t.Fatalf("PersistPlanAudit: %v", err)
+ }
+ record, found, err := store.GetActionAudit("act-planned")
+ if err != nil || !found {
+ t.Fatalf("GetActionAudit found=%v err=%v", found, err)
+ }
+ // Verify the audit fields PersistPlanAudit derives from req+plan.
+ if record.ID != "act-planned" {
+ t.Fatalf("record.ID=%q; want act-planned", record.ID)
+ }
+ if record.State != unified.ActionStatePlanned {
+ t.Fatalf("record.State=%q; want %q", record.State, unified.ActionStatePlanned)
+ }
+ if record.CreatedAt != plannedAt || record.UpdatedAt != plannedAt {
+ t.Fatalf("timestamps created=%v updated=%v; want %v", record.CreatedAt, record.UpdatedAt, plannedAt)
+ }
+ if !reflect.DeepEqual(record.Request, req) {
+ t.Fatalf("record.Request=%#v; want %#v", record.Request, req)
+ }
+ // PersistPlanAudit copies the plan verbatim into the record; the store
+ // then enriches default policy/TTL/preflight fields around it. Assert
+ // only the identity-bearing fields PersistPlanAudit is responsible for
+ // so the test stays scoped to this function's behaviour.
+ if record.Plan.ActionID != plan.ActionID || record.Plan.PlannedAt != plan.PlannedAt ||
+ record.Plan.PlanHash != plan.PlanHash || record.Plan.RequiresApproval != plan.RequiresApproval ||
+ record.Plan.RequestID != plan.RequestID {
+ t.Fatalf("record.Plan identity fields mismatch:\n got =%#v\n want=%#v", record.Plan, plan)
+ }
+ if record.Origin != nil {
+ t.Fatalf("record.Origin=%#v; want nil (no origin supplied)", record.Origin)
+ }
+ events, err := store.GetActionLifecycleEvents("act-planned", time.Time{}, 100)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ if len(events) != 1 {
+ t.Fatalf("len(events)=%d; want 1 (no second event for planned state)", len(events))
+ }
+ ev := events[0]
+ wantEv := unified.ActionLifecycleEvent{
+ ActionID: "act-planned", Timestamp: plannedAt,
+ State: unified.ActionStatePlanned, Actor: "agent:test",
+ Message: "Action plan created.",
+ }
+ if ev.ActionID != wantEv.ActionID || ev.Timestamp != wantEv.Timestamp ||
+ ev.State != wantEv.State || ev.Actor != wantEv.Actor || ev.Message != wantEv.Message {
+ t.Fatalf("event=%#v; want %#v", ev, wantEv)
+ }
+ })
+
+ t.Run("success_pending_state_appends_waiting_for_approval_event", func(t *testing.T) {
+ store := unified.NewMemoryStore()
+ req := unified.ActionRequest{RequestID: "req-2", ResourceID: "vm:42", CapabilityName: "restart", RequestedBy: "operator:1"}
+ // RequiresApproval=true forces PlannedActionState to ActionStatePending,
+ // exercising the "state != Planned" branch that appends the second event.
+ plan := unified.ActionPlan{ActionID: "act-pending", RequestID: "req-2", RequiresApproval: true, PlannedAt: plannedAt}
+ if err := PersistPlanAudit(store, req, plan); err != nil {
+ t.Fatalf("PersistPlanAudit: %v", err)
+ }
+ record, found, err := store.GetActionAudit("act-pending")
+ if err != nil || !found {
+ t.Fatalf("GetActionAudit found=%v err=%v", found, err)
+ }
+ if record.State != unified.ActionStatePending {
+ t.Fatalf("record.State=%q; want %q", record.State, unified.ActionStatePending)
+ }
+ events, err := store.GetActionLifecycleEvents("act-pending", time.Time{}, 100)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ // GetActionLifecycleEvents returns events newest-first, so the
+ // waiting-for-approval event precedes the planned transition.
+ if len(events) != 2 {
+ t.Fatalf("len(events)=%d; want 2 (planned + waiting-for-approval)", len(events))
+ }
+ pending := events[0]
+ if pending.State != unified.ActionStatePending ||
+ pending.Message != "Action is waiting for approval before execution." ||
+ pending.Actor != "operator:1" || pending.Timestamp != plannedAt || pending.ActionID != "act-pending" {
+ t.Fatalf("waiting-for-approval event=%#v", pending)
+ }
+ planned := events[1]
+ if planned.State != unified.ActionStatePlanned || planned.Message != "Action plan created." {
+ t.Fatalf("planned transition event=%#v; want planned transition", planned)
+ }
+ })
+
+ t.Run("idempotent_replan_returns_nil_without_new_events", func(t *testing.T) {
+ store := unified.NewMemoryStore()
+ req := unified.ActionRequest{RequestID: "req-3", ResourceID: "vm:42", CapabilityName: "restart", RequestedBy: "agent:test"}
+ plan := unified.ActionPlan{ActionID: "act-replan", RequestID: "req-3", PlannedAt: plannedAt}
+ if err := PersistPlanAudit(store, req, plan); err != nil {
+ t.Fatalf("first PersistPlanAudit: %v", err)
+ }
+ // Replaying the identical plan must not error (created=false is silent).
+ if err := PersistPlanAudit(store, req, plan); err != nil {
+ t.Fatalf("second PersistPlanAudit: %v", err)
+ }
+ events, err := store.GetActionLifecycleEvents("act-replan", time.Time{}, 100)
+ if err != nil {
+ t.Fatalf("GetActionLifecycleEvents: %v", err)
+ }
+ if len(events) != 1 {
+ t.Fatalf("len(events)=%d after replan; want 1 (idempotent)", len(events))
+ }
+ })
+
+ t.Run("zero_value_request_propagates_store_validation_error", func(t *testing.T) {
+ // PersistPlanAudit performs no request validation of its own; it
+ // delegates to the store. A fully zero-value request is rejected by
+ // the store's NormalizeActionAuditRecord, and that error must flow
+ // back to the caller unchanged (not swallowed, not transformed).
+ store := unified.NewMemoryStore()
+ plan := unified.ActionPlan{ActionID: "act-emptyreq", RequestID: "req-4", PlannedAt: plannedAt}
+ err := PersistPlanAudit(store, unified.ActionRequest{}, plan)
+ if err == nil {
+ t.Fatalf("PersistPlanAudit(zero-value req)=nil; want store validation error")
+ }
+ if !strings.Contains(err.Error(), "action request resource id required") {
+ t.Fatalf("err=%q; want substring %q (store validation propagated verbatim)", err.Error(), "action request resource id required")
+ }
+ // Nothing was persisted.
+ if _, found, qerr := store.GetActionAudit("act-emptyreq"); qerr != nil || found {
+ t.Fatalf("audit persisted despite validation error: found=%v err=%v", found, qerr)
+ }
+ })
+
+ t.Run("request_with_only_required_fields_is_persisted_faithfully", func(t *testing.T) {
+ // A request carrying just the store-required fields (ResourceID,
+ // CapabilityName, RequestedBy) but leaving Reason/Params empty must
+ // round-trip those empty fields verbatim — proving PersistPlanAudit
+ // does not synthesize or alter request content.
+ store := unified.NewMemoryStore()
+ req := unified.ActionRequest{
+ RequestID: "req-4b",
+ ResourceID: "vm:42",
+ CapabilityName: "restart",
+ RequestedBy: "agent:test",
+ }
+ plan := unified.ActionPlan{ActionID: "act-thinreq", RequestID: "req-4b", PlannedAt: plannedAt}
+ if err := PersistPlanAudit(store, req, plan); err != nil {
+ t.Fatalf("PersistPlanAudit: %v", err)
+ }
+ record, found, err := store.GetActionAudit("act-thinreq")
+ if err != nil || !found {
+ t.Fatalf("GetActionAudit found=%v err=%v", found, err)
+ }
+ if record.Request.Reason != "" {
+ t.Fatalf("record.Request.Reason=%q; want empty (faithful pass-through)", record.Request.Reason)
+ }
+ if record.Request.RequestedBy != "agent:test" || record.Request.ResourceID != "vm:42" ||
+ record.Request.CapabilityName != "restart" {
+ t.Fatalf("record.Request=%#v; want %#v", record.Request, req)
+ }
+ })
+
+ t.Run("minimal_plan_with_no_blast_radius_or_preflight", func(t *testing.T) {
+ store := unified.NewMemoryStore()
+ // "No steps": a bare plan carrying only the durable identity and
+ // timestamp, with no PlanHash, PredictedBlastRadius, Preflight, or
+ // PolicyDecision payload (Allowed is even false). PersistPlanAudit
+ // must still persist a valid planned audit and preserve the identity
+ // fields it copies from the input. (The store enriches default
+ // policy/TTL/preflight around the plan; that is the store's job, not
+ // PersistPlanAudit's, so only identity fields are asserted here.)
+ plan := unified.ActionPlan{ActionID: "act-bare", RequestID: "req-5", PlannedAt: plannedAt}
+ req := unified.ActionRequest{RequestID: "req-5", ResourceID: "vm:42", CapabilityName: "restart", RequestedBy: "agent:test"}
+ if err := PersistPlanAudit(store, req, plan); err != nil {
+ t.Fatalf("PersistPlanAudit: %v", err)
+ }
+ record, found, err := store.GetActionAudit("act-bare")
+ if err != nil || !found {
+ t.Fatalf("GetActionAudit found=%v err=%v", found, err)
+ }
+ if record.Plan.ActionID != "act-bare" || record.Plan.PlannedAt != plannedAt ||
+ record.Plan.RequestID != "req-5" || record.Plan.PlanHash != "" {
+ t.Fatalf("record.Plan identity fields mismatch:\n got =%#v\n want ActionID/PlannedAt/RequestID preserved, empty PlanHash", record.Plan)
+ }
+ if record.State != unified.ActionStatePlanned {
+ t.Fatalf("record.State=%q; want %q (no approval required)", record.State, unified.ActionStatePlanned)
+ }
+ events, _ := store.GetActionLifecycleEvents("act-bare", time.Time{}, 100)
+ if len(events) != 1 {
+ t.Fatalf("len(events)=%d; want 1 (single planned event)", len(events))
+ }
+ })
+}
+
+// TestBranchcov0723Am_WithPolicyMutation covers both arms of the nil-guard,
+// the lock-held invocation of the write callback, and the faithful return of
+// the callback's result.
+func TestBranchcov0723Am_WithPolicyMutation(t *testing.T) {
+ t.Run("nil_callback_returns_unavailable_error", func(t *testing.T) {
+ s := &Service{}
+ err := s.WithPolicyMutation(nil)
+ if err == nil {
+ t.Fatalf("WithPolicyMutation(nil)=nil; want error")
+ }
+ if got := err.Error(); !strings.Contains(got, "policy mutation unavailable") {
+ t.Fatalf("err=%q; want substring %q", got, "policy mutation unavailable")
+ }
+ })
+
+ t.Run("nil_service_returns_unavailable_error_without_panicking", func(t *testing.T) {
+ var s *Service // typed nil receiver; the s==nil guard must short-circuit.
+ err := s.WithPolicyMutation(func() error { return nil })
+ if err == nil || !strings.Contains(err.Error(), "policy mutation unavailable") {
+ t.Fatalf("nil-service err=%v; want policy mutation unavailable", err)
+ }
+ })
+
+ t.Run("callback_returning_nil_is_invoked_exactly_once", func(t *testing.T) {
+ s := &Service{}
+ calls := 0
+ err := s.WithPolicyMutation(func() error {
+ calls++
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("WithPolicyMutation err=%v; want nil", err)
+ }
+ if calls != 1 {
+ t.Fatalf("callback invoked %d times; want exactly 1", calls)
+ }
+ })
+
+ t.Run("callback_returning_error_is_propagated_unchanged", func(t *testing.T) {
+ s := &Service{}
+ writeErr := errors.New("write rejected by policy store")
+ err := s.WithPolicyMutation(func() error {
+ return writeErr
+ })
+ if !errors.Is(err, writeErr) {
+ t.Fatalf("WithPolicyMutation err=%v; want %v (unchanged)", err, writeErr)
+ }
+ })
+
+ t.Run("concurrent_mutation_is_serialized_by_admission_lock", func(t *testing.T) {
+ // A shared Service must serialize two WithPolicyMutation calls:
+ // while one holds the admission write lock, the other blocks. We
+ // prove serialization by detecting overlap via a non-atomic counter
+ // guarded only by the lock: if both callbacks ever ran at once the
+ // in-flight count would briefly reach 2.
+ s := &Service{}
+ inFlight := 0
+ maxInFlight := 0
+ done := make(chan struct{})
+ writer := func() {
+ defer func() { done <- struct{}{} }()
+ _ = s.WithPolicyMutation(func() error {
+ inFlight++
+ if inFlight > maxInFlight {
+ maxInFlight = inFlight
+ }
+ // Yield to invite a race; the lock must prevent one.
+ time.Sleep(10 * time.Millisecond)
+ inFlight--
+ return nil
+ })
+ }
+ go writer()
+ go writer()
+ <-done
+ <-done
+ if maxInFlight != 1 {
+ t.Fatalf("maxInFlight=%d; want 1 (mutations must be serialized)", maxInFlight)
+ }
+ })
+}
diff --git a/internal/cloudcp/cloud_audit_branchcov0723am_test.go b/internal/cloudcp/cloud_audit_branchcov0723am_test.go
new file mode 100644
index 0000000000..954b5b4852
--- /dev/null
+++ b/internal/cloudcp/cloud_audit_branchcov0723am_test.go
@@ -0,0 +1,435 @@
+package cloudcp
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+
+ cpDocker "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/docker"
+ "github.com/rcourtman/pulse-go-rewrite/internal/cloudcp/registry"
+)
+
+// TestBranchcov0723AmAddFailure exercises every assertable branch of
+// (*CloudAuditReport).addFailure. The nil-receiver arm is intentionally not
+// covered: it is only reachable through a typed nil pointer and its sole
+// observable effect is "did not panic", which this suite forbids as a
+// tautology. Every other branch — empty/whitespace rejection, OK side-effect,
+// trimming, order preservation, and the absence of deduplication — is driven
+// with concrete inputs and asserted against the source's actual semantics.
+func TestBranchcov0723AmAddFailure(t *testing.T) {
+ t.Parallel()
+
+ t.Run("empty failure string is rejected and leaves OK untouched", func(t *testing.T) {
+ t.Parallel()
+ r := &CloudAuditReport{OK: true}
+ r.addFailure("")
+ if r.OK != true {
+ t.Fatalf("OK = %v, want true (empty failure must not flip OK)", r.OK)
+ }
+ if len(r.Failures) != 0 {
+ t.Fatalf("Failures = %v, want empty (empty failure must be rejected)", r.Failures)
+ }
+ })
+
+ t.Run("whitespace-only failure string is rejected after trim", func(t *testing.T) {
+ t.Parallel()
+ r := &CloudAuditReport{OK: true}
+ r.addFailure(" \t\n ")
+ if r.OK != true {
+ t.Fatalf("OK = %v, want true (whitespace-only failure must not flip OK)", r.OK)
+ }
+ if len(r.Failures) != 0 {
+ t.Fatalf("Failures = %v, want empty (whitespace-only failure must be rejected)", r.Failures)
+ }
+ })
+
+ t.Run("real failure on zero-value report creates slice and flips OK", func(t *testing.T) {
+ t.Parallel()
+ // Start from a literal zero-value report (Failures nil, OK false) to
+ // prove addFailure both allocates the slice and unconditionally sets
+ // OK=false for an accepted failure.
+ var r CloudAuditReport
+ r.addFailure("docker manager unavailable: boom")
+ if r.OK != false {
+ t.Fatalf("OK = %v, want false after a real failure", r.OK)
+ }
+ want := []string{"docker manager unavailable: boom"}
+ if len(r.Failures) != 1 || r.Failures[0] != want[0] {
+ t.Fatalf("Failures = %v, want %v", r.Failures, want)
+ }
+ })
+
+ t.Run("surrounding whitespace is trimmed before appending", func(t *testing.T) {
+ t.Parallel()
+ r := &CloudAuditReport{OK: true}
+ r.addFailure(" storage guardrails failed: low disk ")
+ if r.OK != false {
+ t.Fatalf("OK = %v, want false", r.OK)
+ }
+ if len(r.Failures) != 1 || r.Failures[0] != "storage guardrails failed: low disk" {
+ t.Fatalf("Failures = %v, want single trimmed entry", r.Failures)
+ }
+ })
+
+ t.Run("multiple failures preserve insertion order", func(t *testing.T) {
+ t.Parallel()
+ r := &CloudAuditReport{OK: true}
+ r.addFailure("first failure")
+ r.addFailure("second failure")
+ r.addFailure("third failure")
+ want := []string{"first failure", "second failure", "third failure"}
+ if len(r.Failures) != len(want) {
+ t.Fatalf("Failures = %v, want %v", r.Failures, want)
+ }
+ for i := range want {
+ if r.Failures[i] != want[i] {
+ t.Fatalf("Failures[%d] = %q, want %q (order not preserved)", i, r.Failures[i], want[i])
+ }
+ }
+ if r.OK != false {
+ t.Fatalf("OK = %v, want false after failures", r.OK)
+ }
+ })
+
+ t.Run("duplicate failure is NOT deduplicated", func(t *testing.T) {
+ t.Parallel()
+ // The source performs no deduplication; assert that exact semantics so
+ // a future change to dedupe is caught as a behaviour change.
+ r := &CloudAuditReport{OK: true}
+ r.addFailure("same failure")
+ r.addFailure("same failure")
+ if len(r.Failures) != 2 {
+ t.Fatalf("Failures = %v (len=%d), want len=2 (source does not dedupe)",
+ r.Failures, len(r.Failures))
+ }
+ if r.Failures[0] != "same failure" || r.Failures[1] != "same failure" {
+ t.Fatalf("Failures = %v, want both entries equal to %q", r.Failures, "same failure")
+ }
+ })
+
+ t.Run("OK stays false after a real failure even if a later failure is empty", func(t *testing.T) {
+ t.Parallel()
+ // Asserts the OK side-effect is monotonic: once flipped false it is not
+ // restored, and a subsequent rejected (empty) failure does not append.
+ r := &CloudAuditReport{OK: true}
+ r.addFailure("real failure")
+ r.addFailure("")
+ if r.OK != false {
+ t.Fatalf("OK = %v, want false (must remain false after first real failure)", r.OK)
+ }
+ if len(r.Failures) != 1 || r.Failures[0] != "real failure" {
+ t.Fatalf("Failures = %v, want exactly [\"real failure\"]", r.Failures)
+ }
+ })
+}
+
+// TestBranchcov0723AmRuntimeContainerUnhealthy covers both arms of every
+// conditional in runtimeContainerUnhealthy: the State=="running" guard (which
+// is case-SENSITIVE on State per the source), and the lowercased/trimmed
+// HealthStatus switch covering the healthy cases ("", "none", "healthy"), the
+// default/unhealthy arm, case-insensitivity, and whitespace handling.
+func TestBranchcov0723AmRuntimeContainerUnhealthy(t *testing.T) {
+ t.Parallel()
+ cases := []struct {
+ name string
+ state string
+ health string
+ wantUnwell bool
+ }{
+ // --- State arm (case-sensitive): anything not exactly "running" is unhealthy ---
+ {name: "zero value state and health", state: "", health: "", wantUnwell: true},
+ {name: "paused state", state: "paused", health: "", wantUnwell: true},
+ {name: "exited state", state: "exited", health: "", wantUnwell: true},
+ {name: "created state", state: "created", health: "", wantUnwell: true},
+ {name: "restarting state", state: "restarting", health: "", wantUnwell: true},
+ {name: "state is case sensitive uppercase RUNNING", state: "RUNNING", health: "", wantUnwell: true},
+ {name: "state is case mixed Running", state: "Running", health: "", wantUnwell: true},
+
+ // --- Healthy arm: running + (empty|none|healthy), after lowercasing & trimming ---
+ {name: "running with empty health", state: "running", health: "", wantUnwell: false},
+ {name: "running with none", state: "running", health: "none", wantUnwell: false},
+ {name: "running with healthy", state: "running", health: "healthy", wantUnwell: false},
+ {name: "running with NONE uppercase", state: "running", health: "NONE", wantUnwell: false},
+ {name: "running with HEALTHY uppercase", state: "running", health: "HEALTHY", wantUnwell: false},
+ {name: "running with Mixed Case Healthy", state: "running", health: "HeAlThY", wantUnwell: false},
+ {name: "running with health surrounded by whitespace", state: "running", health: " healthy ", wantUnwell: false},
+
+ // --- Default/unhealthy arm: running + any other health status ---
+ {name: "running with unhealthy", state: "running", health: "unhealthy", wantUnwell: true},
+ {name: "running with starting", state: "running", health: "starting", wantUnwell: true},
+ {name: "running with unknown health no-health-status", state: "running", health: "no-such-state", wantUnwell: true},
+ {name: "running with UNHEALTHY uppercase", state: "running", health: "UNHEALTHY", wantUnwell: true},
+ }
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ c := cpDocker.RuntimeContainerSummary{
+ ID: "c-id",
+ Name: "c-name",
+ State: tc.state,
+ HealthStatus: tc.health,
+ }
+ got := runtimeContainerUnhealthy(c)
+ if got != tc.wantUnwell {
+ t.Fatalf("runtimeContainerUnhealthy(state=%q, health=%q) = %v, want %v",
+ tc.state, tc.health, got, tc.wantUnwell)
+ }
+ })
+ }
+}
+
+// TestBranchcov0723AmTenantDisplayNameResolver covers both branches of the
+// closure returned by tenantDisplayNameResolver: the lookup-failure arm
+// (unknown tenant id -> "") and the success arm (existing tenant -> trimmed
+// display name), plus the whitespace-name edge case. It reuses the existing
+// newEmptyRegistryForTest helper from cloudcp_pure_branchcov0718_test.go,
+// which builds a real SQLite-backed registry rooted at a per-test tempdir.
+func TestBranchcov0723AmTenantDisplayNameResolver(t *testing.T) {
+ t.Parallel()
+
+ t.Run("unknown tenant id resolves to empty string", func(t *testing.T) {
+ t.Parallel()
+ reg := newEmptyRegistryForTest(t)
+ defer reg.Close()
+ resolver := tenantDisplayNameResolver(reg)
+ if got := resolver("does-not-exist"); got != "" {
+ t.Fatalf("resolver(unknown) = %q, want empty string", got)
+ }
+ })
+
+ t.Run("existing tenant display name is returned trimmed", func(t *testing.T) {
+ t.Parallel()
+ reg := newEmptyRegistryForTest(t)
+ defer reg.Close()
+ tenant := &registry.Tenant{
+ ID: "t-display",
+ AccountID: "acc-1",
+ Email: "[email protected]",
+ DisplayName: " Acme Workspace ",
+ }
+ if err := reg.Create(tenant); err != nil {
+ t.Fatalf("Create tenant: %v", err)
+ }
+ resolver := tenantDisplayNameResolver(reg)
+ if got := resolver("t-display"); got != "Acme Workspace" {
+ t.Fatalf("resolver(existing) = %q, want %q", got, "Acme Workspace")
+ }
+ })
+
+ t.Run("whitespace-only display name resolves to empty string", func(t *testing.T) {
+ t.Parallel()
+ reg := newEmptyRegistryForTest(t)
+ defer reg.Close()
+ tenant := &registry.Tenant{
+ ID: "t-blank",
+ AccountID: "acc-2",
+ Email: "[email protected]",
+ DisplayName: " ",
+ }
+ if err := reg.Create(tenant); err != nil {
+ t.Fatalf("Create tenant: %v", err)
+ }
+ resolver := tenantDisplayNameResolver(reg)
+ if got := resolver("t-blank"); got != "" {
+ t.Fatalf("resolver(whitespace-name) = %q, want empty string after TrimSpace", got)
+ }
+ })
+}
+
+// TestBranchcov0723AmEnforceStorageAdmission covers the two pure early-return
+// branches of EnforceStorageAdmission: cfg=nil propagates the underlying
+// CheckStorageGuardrails error, and a cfg with guardrails disabled returns nil
+// without ever touching the Docker usage provider or the filesystem.
+func TestBranchcov0723AmEnforceStorageAdmission(t *testing.T) {
+ t.Parallel()
+
+ t.Run("nil cfg returns control plane config required error", func(t *testing.T) {
+ t.Parallel()
+ err := EnforceStorageAdmission(context.Background(), nil, nil)
+ if err == nil {
+ t.Fatal("expected error for nil cfg, got nil")
+ }
+ if !strings.Contains(err.Error(), "control plane config is required") {
+ t.Fatalf("err = %q, want substring 'control plane config is required'", err.Error())
+ }
+ })
+
+ t.Run("guardrails disabled returns nil without invoking docker usage provider", func(t *testing.T) {
+ t.Parallel()
+ // Provider that fails the test if invoked, proving the disabled
+ // guardrail path short-circuits before any Docker call.
+ var providerInvoked bool
+ provider := failIfInvokedUsageProvider{t: t, invoked: &providerInvoked}
+ cfg := &CPConfig{StorageGuardrailsEnabled: false}
+ if err := EnforceStorageAdmission(context.Background(), cfg, provider); err != nil {
+ t.Fatalf("EnforceStorageAdmission(disabled) = %v, want nil", err)
+ }
+ if providerInvoked {
+ t.Fatal("docker usage provider was invoked; disabled guardrail path should short-circuit")
+ }
+ })
+}
+
+// failIfInvokedUsageProvider is a StorageDockerUsageProvider that fails the
+// associated test if DiskUsage is called. It exists to prove that the
+// guardrails-disabled path in EnforceStorageAdmission never reaches the
+// Docker usage provider.
+type failIfInvokedUsageProvider struct {
+ t *testing.T
+ invoked *bool
+}
+
+func (f failIfInvokedUsageProvider) DiskUsage(context.Context) (*cpDocker.DiskUsageSnapshot, error) {
+ *f.invoked = true
+ f.t.Fatal("DiskUsage must not be called on the disabled-guardrail path")
+ return nil, nil
+}
+
+// TestBranchcov0723AmRecoverProviderMSPWorkspaces covers the pure
+// early-return branches of RecoverProviderMSPWorkspaces that are reachable
+// before any Docker daemon, live registry, or running server is required:
+// already-cancelled context, nil cfg, and both options-validation error
+// arms. The deeper execution branches (which need a Docker manager and a
+// provider-MSP-configured control plane) are intentionally out of scope.
+func TestBranchcov0723AmRecoverProviderMSPWorkspaces(t *testing.T) {
+ t.Parallel()
+
+ t.Run("cancelled context returns ctx error", func(t *testing.T) {
+ t.Parallel()
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ _, err := RecoverProviderMSPWorkspaces(ctx, &CPConfig{},
+ ProviderMSPRecoveryOptions{AllDegraded: true})
+ if err == nil {
+ t.Fatal("expected error for cancelled context, got nil")
+ }
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("err = %v, want errors.Is(err, context.Canceled)", err)
+ }
+ })
+
+ t.Run("nil cfg returns control plane config required", func(t *testing.T) {
+ t.Parallel()
+ _, err := RecoverProviderMSPWorkspaces(context.Background(), nil,
+ ProviderMSPRecoveryOptions{AllDegraded: true})
+ if err == nil {
+ t.Fatal("expected error for nil cfg, got nil")
+ }
+ if !strings.Contains(err.Error(), "control plane config is required") {
+ t.Fatalf("err = %q, want substring 'control plane config is required'", err.Error())
+ }
+ })
+
+ t.Run("opts with both AllDegraded and TenantIDs is rejected", func(t *testing.T) {
+ t.Parallel()
+ _, err := RecoverProviderMSPWorkspaces(context.Background(), &CPConfig{},
+ ProviderMSPRecoveryOptions{AllDegraded: true, TenantIDs: []string{"t-1"}})
+ if err == nil {
+ t.Fatal("expected error for mutually exclusive options, got nil")
+ }
+ if !strings.Contains(err.Error(), "choose either --all-degraded or one or more --tenant-id values") {
+ t.Fatalf("err = %q, want substring 'choose either --all-degraded or one or more --tenant-id values'", err.Error())
+ }
+ })
+
+ t.Run("opts with neither AllDegraded nor TenantIDs is rejected", func(t *testing.T) {
+ t.Parallel()
+ _, err := RecoverProviderMSPWorkspaces(context.Background(), &CPConfig{},
+ ProviderMSPRecoveryOptions{})
+ if err == nil {
+ t.Fatal("expected error for empty options, got nil")
+ }
+ if !strings.Contains(err.Error(), "choose --all-degraded or at least one --tenant-id") {
+ t.Fatalf("err = %q, want substring 'choose --all-degraded or at least one --tenant-id'", err.Error())
+ }
+ })
+}
+
+// TestBranchcov0723AmAuditCloudNilCfg covers the single pure branch of
+// AuditCloud reachable without a Docker daemon or live registry: the nil-cfg
+// guard that returns an error before any I/O is attempted. The remaining
+// branches require a control-plane directory, a Docker manager, and storage
+// guardrail checks, and are therefore out of scope per the purity gate.
+func TestBranchcov0723AmAuditCloudNilCfg(t *testing.T) {
+ t.Parallel()
+ report, err := AuditCloud(context.Background(), nil)
+ if err == nil {
+ t.Fatal("expected error for nil cfg, got nil")
+ }
+ if !strings.Contains(err.Error(), "control plane config is required") {
+ t.Fatalf("err = %q, want substring 'control plane config is required'", err.Error())
+ }
+ if report != nil {
+ t.Fatalf("report = %v, want nil on cfg error", report)
+ }
+}
+
+// TestBranchcov0723AmRolloutTenantRuntimePureBranches covers the two pure
+// early-return branches of RolloutTenantRuntime: nil cfg and missing image
+// (both opts.Image and cfg.PulseImage empty). The remaining branches construct
+// a Docker manager and registry and call into service.Rollout, which requires
+// a Docker daemon and is therefore out of scope.
+func TestBranchcov0723AmRolloutTenantRuntimePureBranches(t *testing.T) {
+ t.Parallel()
+
+ t.Run("nil cfg returns control plane config required", func(t *testing.T) {
+ t.Parallel()
+ _, err := RolloutTenantRuntime(context.Background(), nil,
+ TenantRuntimeRolloutOptions{TenantID: "t-1", Image: "pulse-runtime:latest"})
+ if err == nil {
+ t.Fatal("expected error for nil cfg, got nil")
+ }
+ if !strings.Contains(err.Error(), "control plane config is required") {
+ t.Fatalf("err = %q, want substring 'control plane config is required'", err.Error())
+ }
+ })
+
+ t.Run("missing image falls back to cfg then errors", func(t *testing.T) {
+ t.Parallel()
+ // opts.Image empty AND cfg.PulseImage empty -> the function must
+ // reject before attempting any Docker/registry construction.
+ cfg := &CPConfig{}
+ _, err := RolloutTenantRuntime(context.Background(), cfg,
+ TenantRuntimeRolloutOptions{TenantID: "t-1"})
+ if err == nil {
+ t.Fatal("expected error for missing image, got nil")
+ }
+ if !strings.Contains(err.Error(), "missing tenant runtime image") {
+ t.Fatalf("err = %q, want substring 'missing tenant runtime image'", err.Error())
+ }
+ })
+}
+
+// TestBranchcov0723AmPlanTenantRuntimeImageRolloutPureBranches covers the two
+// pure early-return branches of PlanTenantRuntimeImageRollout, mirroring
+// RolloutTenantRuntime. The deeper branches require a Docker daemon.
+func TestBranchcov0723AmPlanTenantRuntimeImageRolloutPureBranches(t *testing.T) {
+ t.Parallel()
+
+ t.Run("nil cfg returns control plane config required", func(t *testing.T) {
+ t.Parallel()
+ _, err := PlanTenantRuntimeImageRollout(context.Background(), nil,
+ TenantRuntimeImageRolloutPlanOptions{Image: "pulse-runtime:latest"})
+ if err == nil {
+ t.Fatal("expected error for nil cfg, got nil")
+ }
+ if !strings.Contains(err.Error(), "control plane config is required") {
+ t.Fatalf("err = %q, want substring 'control plane config is required'", err.Error())
+ }
+ })
+
+ t.Run("missing image falls back to cfg then errors", func(t *testing.T) {
+ t.Parallel()
+ cfg := &CPConfig{}
+ _, err := PlanTenantRuntimeImageRollout(context.Background(), cfg,
+ TenantRuntimeImageRolloutPlanOptions{All: true})
+ if err == nil {
+ t.Fatal("expected error for missing image, got nil")
+ }
+ if !strings.Contains(err.Error(), "missing tenant runtime image") {
+ t.Fatalf("err = %q, want substring 'missing tenant runtime image'", err.Error())
+ }
+ })
+}
diff --git a/internal/cloudcp/tenant_runtime_rollout_branchcov0723am_test.go b/internal/cloudcp/tenant_runtime_rollout_branchcov0723am_test.go
new file mode 100644
index 0000000000..f2f2736485
--- /dev/null
+++ b/internal/cloudcp/tenant_runtime_rollout_branchcov0723am_test.go
@@ -0,0 +1,213 @@
+package cloudcp
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// These tests raise branch/function coverage of the two exported planner
+// wrappers in tenant_runtime_rollout.go:
+// - PlanTenantRuntimeContractReconcile
+// - PlanTenantRuntimeImageRollout
+//
+// Both wrappers build a real service via newTenantRuntimeRolloutServiceFromConfig
+// (which constructs a lazy Docker client and a local sqlite registry) and then
+// delegate to the (already covered) service.PlanContractReconcile /
+// service.PlanImageRollout methods. The genuinely deterministic, Docker-free
+// arms are exercised here:
+// * the happy path with an empty tenant registry and All=true (the plan loop
+// never runs, so s.docker.Inspect against the live daemon is never reached),
+// * the image-resolution fallbacks of PlanTenantRuntimeImageRollout
+// (opts.Image wins; otherwise cfg.PulseImage),
+// * constructor-error propagation when the tenants dir or control-plane dir
+// cannot be created.
+//
+// The tenant-populated planning branches (noop/rollout/skip/missing/drift) are
+// only reachable through the exported wrappers by calling s.docker.Inspect
+// against a live Docker daemon and are therefore out of scope per the purity
+// gate. They are already covered for the underlying (mocked) service methods in
+// tenant_runtime_rollout_test.go.
+
+// branchcov0723AmEmptyRegistryCfg returns a CPConfig whose DataDir points at a
+// fresh, writable temp directory, so newTenantRuntimeRolloutServiceFromConfig
+// can construct a real (empty) sqlite registry and lazy Docker client. Each
+// caller gets its own temp dir so subtests are fully independent.
+func branchcov0723AmEmptyRegistryCfg(t *testing.T, pulseImage string) *CPConfig {
+ t.Helper()
+ return &CPConfig{
+ DataDir: t.TempDir(),
+ PulseImage: pulseImage,
+ }
+}
+
+// branchcov0723AmBlockingFile places a regular file at <dir>/<name> so that a
+// subsequent os.MkdirAll on a path that descends through it fails with ENOTDIR.
+func branchcov0723AmBlockingFile(t *testing.T, dir, name string) {
+ t.Helper()
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatalf("mkdir %s: %v", dir, err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, name), []byte("block"), 0o600); err != nil {
+ t.Fatalf("write blocking file %s: %v", filepath.Join(dir, name), err)
+ }
+}
+
+func TestBranchcov0723AmPlanTenantRuntimeContractReconcile(t *testing.T) {
+ t.Run("EmptyRegistryReturnsNonNilEmptyPlan", func(t *testing.T) {
+ // All=true against an empty registry: selectContractReconcileTenants
+ // returns an empty list, the planning loop is skipped entirely (no
+ // live Docker Inspect), and an empty plan with a non-nil Tenants
+ // slice is returned. This exercises the full happy path of the
+ // wrapper, including successful service construction.
+ cfg := branchcov0723AmEmptyRegistryCfg(t, "pulse-runtime:stable")
+
+ plan, err := PlanTenantRuntimeContractReconcile(
+ context.Background(),
+ cfg,
+ TenantRuntimeContractReconcilePlanOptions{All: true},
+ )
+ if err != nil {
+ t.Fatalf("PlanTenantRuntimeContractReconcile() error = %v", err)
+ }
+ if plan == nil {
+ t.Fatal("plan = nil, want non-nil plan")
+ }
+ if plan.Tenants == nil {
+ t.Fatal("plan.Tenants = nil, want non-nil (empty) slice")
+ }
+ if len(plan.Tenants) != 0 {
+ t.Fatalf("len(plan.Tenants) = %d, want 0", len(plan.Tenants))
+ }
+ })
+
+ t.Run("TenantsDirNotCreatablePropagatesError", func(t *testing.T) {
+ // Point DataDir at a regular file so TenantsDir() = <file>/tenants
+ // cannot be created: newTenantRuntimeRolloutServiceFromConfig fails
+ // at the very first MkdirAll and the wrapper returns that error.
+ // No Docker client is constructed.
+ blockingDir := t.TempDir()
+ blockingFile := filepath.Join(blockingDir, "iamfile")
+ branchcov0723AmBlockingFile(t, blockingDir, "iamfile")
+
+ cfg := &CPConfig{DataDir: blockingFile, PulseImage: "pulse-runtime:stable"}
+ plan, err := PlanTenantRuntimeContractReconcile(
+ context.Background(),
+ cfg,
+ TenantRuntimeContractReconcilePlanOptions{All: true},
+ )
+ if err == nil {
+ t.Fatal("expected error when tenants dir is not creatable, got nil")
+ }
+ if !strings.Contains(err.Error(), "ensure tenants dir") {
+ t.Fatalf("err = %q, want substring 'ensure tenants dir'", err.Error())
+ }
+ if plan != nil {
+ t.Fatalf("plan = %v, want nil on constructor error", plan)
+ }
+ })
+
+ t.Run("ControlPlaneDirNotCreatablePropagatesError", func(t *testing.T) {
+ // TenantsDir() is creatable, but ControlPlaneDir() resolves to an
+ // existing regular file: the second MkdirAll fails and the wrapper
+ // returns the distinct "ensure control-plane dir" error.
+ dataDir := t.TempDir()
+ branchcov0723AmBlockingFile(t, dataDir, "control-plane")
+
+ cfg := &CPConfig{DataDir: dataDir, PulseImage: "pulse-runtime:stable"}
+ plan, err := PlanTenantRuntimeContractReconcile(
+ context.Background(),
+ cfg,
+ TenantRuntimeContractReconcilePlanOptions{All: true},
+ )
+ if err == nil {
+ t.Fatal("expected error when control-plane dir is not creatable, got nil")
+ }
+ if !strings.Contains(err.Error(), "ensure control-plane dir") {
+ t.Fatalf("err = %q, want substring 'ensure control-plane dir'", err.Error())
+ }
+ if plan != nil {
+ t.Fatalf("plan = %v, want nil on constructor error", plan)
+ }
+ })
+}
+
+func TestBranchcov0723AmPlanTenantRuntimeImageRollout(t *testing.T) {
+ t.Run("EmptyRegistryUsesOptsImageAndReturnsNonNilEmptyPlan", func(t *testing.T) {
+ // opts.Image is set and must win: the wrapper assigns it back to
+ // opts.Image (line opts.Image = image) and builds the service with
+ // that image. With an empty registry the plan loop never reaches
+ // s.docker.Inspect, so this is deterministic without a daemon.
+ cfg := branchcov0723AmEmptyRegistryCfg(t, "pulse-runtime:fallback")
+
+ plan, err := PlanTenantRuntimeImageRollout(
+ context.Background(),
+ cfg,
+ TenantRuntimeImageRolloutPlanOptions{All: true, Image: "pulse-runtime:next"},
+ )
+ if err != nil {
+ t.Fatalf("PlanTenantRuntimeImageRollout() error = %v", err)
+ }
+ if plan == nil {
+ t.Fatal("plan = nil, want non-nil plan")
+ }
+ if plan.Tenants == nil {
+ t.Fatal("plan.Tenants = nil, want non-nil (empty) slice")
+ }
+ if len(plan.Tenants) != 0 {
+ t.Fatalf("len(plan.Tenants) = %d, want 0", len(plan.Tenants))
+ }
+ })
+
+ t.Run("TenantsDirNotCreatablePropagatesError", func(t *testing.T) {
+ // Image is resolved successfully (so the nil/empty guards are passed)
+ // but the service constructor fails at the first MkdirAll. Covers the
+ // wrapper's error-propagation branch for a constructor failure, which
+ // the pure-branch tests do not reach.
+ blockingDir := t.TempDir()
+ blockingFile := filepath.Join(blockingDir, "iamfile")
+ branchcov0723AmBlockingFile(t, blockingDir, "iamfile")
+
+ cfg := &CPConfig{DataDir: blockingFile, PulseImage: "pulse-runtime:stable"}
+ plan, err := PlanTenantRuntimeImageRollout(
+ context.Background(),
+ cfg,
+ TenantRuntimeImageRolloutPlanOptions{All: true, Image: "pulse-runtime:next"},
+ )
+ if err == nil {
+ t.Fatal("expected error when tenants dir is not creatable, got nil")
+ }
+ if !strings.Contains(err.Error(), "ensure tenants dir") {
+ t.Fatalf("err = %q, want substring 'ensure tenants dir'", err.Error())
+ }
+ if plan != nil {
+ t.Fatalf("plan = %v, want nil on constructor error", plan)
+ }
+ })
+
+ t.Run("ControlPlaneDirNotCreatablePropagatesError", func(t *testing.T) {
+ // TenantsDir creatable, ControlPlaneDir blocked by a regular file:
+ // the second MkdirAll fails and the wrapper returns the distinct
+ // "ensure control-plane dir" error.
+ dataDir := t.TempDir()
+ branchcov0723AmBlockingFile(t, dataDir, "control-plane")
+
+ cfg := &CPConfig{DataDir: dataDir, PulseImage: "pulse-runtime:stable"}
+ plan, err := PlanTenantRuntimeImageRollout(
+ context.Background(),
+ cfg,
+ TenantRuntimeImageRolloutPlanOptions{All: true, Image: "pulse-runtime:next"},
+ )
+ if err == nil {
+ t.Fatal("expected error when control-plane dir is not creatable, got nil")
+ }
+ if !strings.Contains(err.Error(), "ensure control-plane dir") {
+ t.Fatalf("err = %q, want substring 'ensure control-plane dir'", err.Error())
+ }
+ if plan != nil {
+ t.Fatalf("plan = %v, want nil on constructor error", plan)
+ }
+ })
+}
diff --git a/internal/vmware/provider_fixture_branchcov0723am_test.go b/internal/vmware/provider_fixture_branchcov0723am_test.go
new file mode 100644
index 0000000000..6404e55dec
--- /dev/null
+++ b/internal/vmware/provider_fixture_branchcov0723am_test.go
@@ -0,0 +1,622 @@
+package vmware
+
+import (
+ "context"
+ "errors"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// TestBranchcov0723Am_FixtureFetcherFetch covers (f *FixtureFetcher) Fetch in
+// provider.go.
+//
+// NOTE: the spec described FixtureFetcher.Fetch as reading a fixture file
+// (missing path / invalid JSON / empty file). The actual implementation does
+// NO file I/O — it returns a defensive deep copy of the in-memory Snapshot
+// field, with a single nil-receiver guard. These subtests drive that real
+// behaviour: both arms of the nil-receiver guard, and real clone semantics
+// (the returned snapshot equals the source by value; mutating a returned
+// slice does not bleed back into the fetcher; two Fetch calls return
+// independent slices). The spec's "missing path / invalid JSON / empty file"
+// arms do not exist in the code and cannot be covered.
+func TestBranchcov0723Am_FixtureFetcherFetch(t *testing.T) {
+ t.Run("nil_receiver_returns_nil_nil", func(t *testing.T) {
+ var f *FixtureFetcher
+ got, err := f.Fetch(context.Background())
+ if err != nil {
+ t.Fatalf("nil-receiver Fetch err = %v, want nil", err)
+ }
+ if got != nil {
+ t.Fatalf("nil-receiver Fetch = %v, want nil", got)
+ }
+ })
+
+ t.Run("empty_snapshot_returns_non_nil_clone", func(t *testing.T) {
+ f := &FixtureFetcher{}
+ got, err := f.Fetch(context.Background())
+ if err != nil {
+ t.Fatalf("Fetch err = %v, want nil", err)
+ }
+ if got == nil {
+ t.Fatal("Fetch returned nil snapshot for non-nil receiver; want non-nil empty clone")
+ }
+ if len(got.Hosts) != 0 || len(got.VMs) != 0 || len(got.Datastores) != 0 || len(got.Networks) != 0 {
+ t.Fatalf("empty fixture produced non-empty snapshot: %+v", got)
+ }
+ })
+
+ populated := InventorySnapshot{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ VCenterHost: "vc.lab.local",
+ VIRelease: "8.0.3",
+ CollectedAt: time.Date(2026, time.July, 23, 9, 0, 0, 0, time.UTC),
+ Hosts: []InventoryHost{{
+ Host: "host-1",
+ Name: "esxi-1.lab.local",
+ ConnectionState: "CONNECTED",
+ PowerState: "POWERED_ON",
+ DatastoreIDs: []string{"ds-1"},
+ }},
+ VMs: []InventoryVM{{
+ VM: "vm-1",
+ Name: "app-1",
+ PowerState: "POWERED_ON",
+ }},
+ Datastores: []InventoryDatastore{{
+ Datastore: "ds-1",
+ Name: "nvme-primary",
+ Type: "VMFS",
+ }},
+ }
+
+ t.Run("populated_snapshot_round_trips_fields", func(t *testing.T) {
+ f := &FixtureFetcher{Snapshot: populated}
+ got, err := f.Fetch(context.Background())
+ if err != nil {
+ t.Fatalf("Fetch err = %v, want nil", err)
+ }
+ if got == nil {
+ t.Fatal("Fetch returned nil snapshot; want clone")
+ }
+ if got.ConnectionID != populated.ConnectionID {
+ t.Errorf("ConnectionID = %q, want %q", got.ConnectionID, populated.ConnectionID)
+ }
+ if got.ConnectionName != populated.ConnectionName {
+ t.Errorf("ConnectionName = %q, want %q", got.ConnectionName, populated.ConnectionName)
+ }
+ if got.VCenterHost != populated.VCenterHost {
+ t.Errorf("VCenterHost = %q, want %q", got.VCenterHost, populated.VCenterHost)
+ }
+ if got.VIRelease != populated.VIRelease {
+ t.Errorf("VIRelease = %q, want %q", got.VIRelease, populated.VIRelease)
+ }
+ if !got.CollectedAt.Equal(populated.CollectedAt) {
+ t.Errorf("CollectedAt = %v, want %v", got.CollectedAt, populated.CollectedAt)
+ }
+ if len(got.Hosts) != 1 || got.Hosts[0].Host != "host-1" {
+ t.Errorf("Hosts = %+v, want one entry with Host=host-1", got.Hosts)
+ }
+ if len(got.VMs) != 1 || got.VMs[0].VM != "vm-1" {
+ t.Errorf("VMs = %+v, want one entry with VM=vm-1", got.VMs)
+ }
+ if len(got.Datastores) != 1 || got.Datastores[0].Datastore != "ds-1" {
+ t.Errorf("Datastores = %+v, want one entry with Datastore=ds-1", got.Datastores)
+ }
+ })
+
+ t.Run("returned_snapshot_is_a_defensive_copy", func(t *testing.T) {
+ f := &FixtureFetcher{Snapshot: populated}
+ got, err := f.Fetch(context.Background())
+ if err != nil {
+ t.Fatalf("Fetch err = %v, want nil", err)
+ }
+ // Mutate the returned snapshot's slice and scalar fields. Because
+ // Fetch returns a deep clone, the fetcher's underlying snapshot must
+ // remain unchanged for subsequent calls.
+ got.Hosts[0].Host = "MUTATED"
+ got.Hosts = append(got.Hosts, InventoryHost{Host: "host-2"})
+ got.VMs = nil
+ got.CollectedAt = time.Time{}
+
+ again, err := f.Fetch(context.Background())
+ if err != nil {
+ t.Fatalf("second Fetch err = %v, want nil", err)
+ }
+ if len(again.Hosts) != 1 || again.Hosts[0].Host != "host-1" {
+ t.Fatalf("mutation bled into fetcher: again.Hosts = %+v, want one entry with Host=host-1", again.Hosts)
+ }
+ if len(again.VMs) != 1 {
+ t.Fatalf("mutation bled into fetcher: again.VMs = %+v, want one entry", again.VMs)
+ }
+ if !again.CollectedAt.Equal(populated.CollectedAt) {
+ t.Fatalf("mutation bled into fetcher: again.CollectedAt = %v, want %v", again.CollectedAt, populated.CollectedAt)
+ }
+ })
+
+ t.Run("two_consecutive_calls_return_independent_slices", func(t *testing.T) {
+ f := &FixtureFetcher{Snapshot: populated}
+ first, err := f.Fetch(context.Background())
+ if err != nil {
+ t.Fatalf("first Fetch err = %v, want nil", err)
+ }
+ second, err := f.Fetch(context.Background())
+ if err != nil {
+ t.Fatalf("second Fetch err = %v, want nil", err)
+ }
+ first.Hosts[0].Host = "FIRST-MUT"
+ if second.Hosts[0].Host == "FIRST-MUT" {
+ t.Fatal("second Fetch result shares storage with first; expected independent clones")
+ }
+ if first.Hosts[0].Host != "FIRST-MUT" {
+ t.Fatalf("mutating first result did not stick: got %q", first.Hosts[0].Host)
+ }
+ })
+}
+
+// TestBranchcov0723Am_ResetFeatureEnabledFromEnv covers
+// ResetFeatureEnabledFromEnv in client.go. The function re-reads the
+// PULSE_ENABLE_VMWARE env var, re-parses it through parseFeatureEnabled, and
+// stores the result in package-level state (featureVMwareEnabled). The four
+// subtests below are the spec-required inputs (enabled, disabled, unset,
+// garbage) and collectively cover every case body of parseFeatureEnabled
+// (true-arm, false-arm, default-arm) plus the env-unset path through
+// os.Getenv. Each subtest restores both the previous flag value and the
+// previous environment via t.Cleanup so no other test observes the mutation.
+func TestBranchcov0723Am_ResetFeatureEnabledFromEnv(t *testing.T) {
+ cases := []struct {
+ name string
+ value string
+ unset bool
+ want bool
+ }{
+ // parseFeatureEnabled true-arm.
+ {name: "enabled_token_enables", value: "1", want: true},
+ // parseFeatureEnabled false-arm.
+ {name: "disabled_token_disables", value: "false", want: false},
+ // os.Getenv returns "" when unset; parseFeatureEnabled("") hits the
+ // true-arm. Semantically distinct from value="1" because the env var
+ // is genuinely absent.
+ {name: "unset_env_defaults_to_enabled", unset: true, want: true},
+ // parseFeatureEnabled default-arm.
+ {name: "garbage_value_defaults_to_enabled", value: "maybe", want: true},
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ previous := IsFeatureEnabled()
+ t.Cleanup(func() { SetFeatureEnabled(previous) })
+
+ if tc.unset {
+ prevValue, hadPrev := os.LookupEnv(FeatureVMware)
+ if err := os.Unsetenv(FeatureVMware); err != nil {
+ t.Fatalf("os.Unsetenv: %v", err)
+ }
+ t.Cleanup(func() {
+ if !hadPrev {
+ return
+ }
+ if err := os.Setenv(FeatureVMware, prevValue); err != nil {
+ t.Logf("restore os.Setenv: %v", err)
+ }
+ })
+ } else {
+ t.Setenv(FeatureVMware, tc.value)
+ }
+
+ ResetFeatureEnabledFromEnv()
+ if got := IsFeatureEnabled(); got != tc.want {
+ t.Fatalf("IsFeatureEnabled() after ResetFeatureEnabledFromEnv(value=%q, unset=%v) = %v, want %v",
+ tc.value, tc.unset, got, tc.want)
+ }
+ })
+ }
+}
+
+// stubFetchSnapshot is a deterministic Fetcher used to drive the error and
+// nil-snapshot arms of (*Provider).Refresh without touching a real client.
+type stubFetchSnapshot struct {
+ snapshot *InventorySnapshot
+ err error
+}
+
+func (s *stubFetchSnapshot) Fetch(context.Context) (*InventorySnapshot, error) {
+ return s.snapshot, s.err
+}
+
+// stubCloseFetch is a Fetcher that also implements fetcherCloser (unexported,
+// same package) so (*Provider).Close's type-assertion arm is reachable and
+// observable through the closes counter.
+type stubCloseFetch struct {
+ closes atomic.Int32
+}
+
+func (s *stubCloseFetch) Fetch(context.Context) (*InventorySnapshot, error) {
+ return &InventorySnapshot{}, nil
+}
+
+func (s *stubCloseFetch) Close() { s.closes.Add(1) }
+
+// stubPlainFetch is a Fetcher without a Close method, used to drive the
+// type-assertion-fail (non-closer) arm of (*Provider).Close.
+type stubPlainFetch struct{}
+
+func (stubPlainFetch) Fetch(context.Context) (*InventorySnapshot, error) {
+ return &InventorySnapshot{}, nil
+}
+
+// TestBranchcov0723Am_ProviderRefresh covers (*Provider).Refresh in
+// provider.go. It drives all five return paths through deterministic stub
+// fetchers (no vCenter dial): nil receiver, nil fetcher, wrapped fetch error,
+// nil-snapshot error, and the success path which caches and sorts the
+// snapshot.
+func TestBranchcov0723Am_ProviderRefresh(t *testing.T) {
+ ctx := context.Background()
+
+ t.Run("nil_receiver_returns_provider_nil_error", func(t *testing.T) {
+ var p *Provider
+ err := p.Refresh(ctx)
+ if err == nil {
+ t.Fatal("nil-receiver Refresh err = nil, want error")
+ }
+ if !strings.Contains(err.Error(), "provider is nil") {
+ t.Errorf("nil-receiver Refresh err = %q, want it to mention 'provider is nil'", err.Error())
+ }
+ })
+
+ t.Run("nil_fetcher_returns_fetcher_nil_error", func(t *testing.T) {
+ p := &Provider{}
+ err := p.Refresh(ctx)
+ if err == nil {
+ t.Fatal("nil-fetcher Refresh err = nil, want error")
+ }
+ if !strings.Contains(err.Error(), "fetcher is nil") {
+ t.Errorf("nil-fetcher Refresh err = %q, want it to mention 'fetcher is nil'", err.Error())
+ }
+ })
+
+ sentinel := errors.New("stub fetch failure")
+ t.Run("fetcher_error_is_wrapped_with_refresh_prefix", func(t *testing.T) {
+ p := NewLiveProvider(&stubFetchSnapshot{err: sentinel})
+ err := p.Refresh(ctx)
+ if err == nil {
+ t.Fatal("Refresh err = nil, want wrapped error")
+ }
+ if !errors.Is(err, sentinel) {
+ t.Errorf("Refresh err = %q, want it to wrap %v via %%w", err.Error(), sentinel)
+ }
+ if !strings.Contains(err.Error(), "refresh vmware inventory") {
+ t.Errorf("Refresh err = %q, want it to mention 'refresh vmware inventory'", err.Error())
+ }
+ })
+
+ t.Run("fetcher_returns_nil_snapshot_returns_nil_inventory_error", func(t *testing.T) {
+ p := NewLiveProvider(&stubFetchSnapshot{snapshot: nil})
+ err := p.Refresh(ctx)
+ if err == nil {
+ t.Fatal("Refresh err = nil, want nil-inventory error")
+ }
+ if !strings.Contains(err.Error(), "nil inventory") {
+ t.Errorf("Refresh err = %q, want it to mention 'nil inventory'", err.Error())
+ }
+ })
+
+ t.Run("valid_snapshot_is_cached_and_sorted", func(t *testing.T) {
+ // Provide hosts in reverse sort order; Refresh calls
+ // sortInventorySnapshot, so the cached snapshot must come back sorted
+ // by vmwareSortKey (firstNonEmptyTrimmed of lower-cased id then name).
+ snapshot := &InventorySnapshot{
+ ConnectionID: "vc-1",
+ Hosts: []InventoryHost{
+ {Host: "host-9", Name: "esxi-9"},
+ {Host: "host-1", Name: "esxi-1"},
+ },
+ }
+ p := NewLiveProvider(&stubFetchSnapshot{snapshot: snapshot})
+ if err := p.Refresh(ctx); err != nil {
+ t.Fatalf("Refresh err = %v, want nil", err)
+ }
+ cached := p.Snapshot()
+ if cached == nil {
+ t.Fatal("Snapshot() = nil after successful Refresh; want cached snapshot")
+ }
+ if len(cached.Hosts) != 2 {
+ t.Fatalf("cached Hosts len = %d, want 2", len(cached.Hosts))
+ }
+ if got := cached.Hosts[0].Host; got != "host-1" {
+ t.Errorf("Refresh did not sort cached hosts: cached.Hosts[0].Host = %q, want host-1", got)
+ }
+ })
+}
+
+// TestBranchcov0723Am_ProviderClose covers (*Provider).Close in provider.go.
+// It drives the nil-receiver guard, the nil-fetcher guard, the
+// type-assertion-fail arm (a fetcher without a Close method), and the
+// type-assertion-success arm observed through the stub's closes counter.
+func TestBranchcov0723Am_ProviderClose(t *testing.T) {
+ t.Run("nil_receiver_is_a_documented_noop", func(t *testing.T) {
+ var p *Provider
+ defer func() {
+ if r := recover(); r != nil {
+ t.Fatalf("(*Provider).Close on nil receiver panicked: %v", r)
+ }
+ }()
+ p.Close()
+ })
+
+ t.Run("nil_fetcher_is_a_documented_noop", func(t *testing.T) {
+ p := &Provider{}
+ defer func() {
+ if r := recover(); r != nil {
+ t.Fatalf("(*Provider).Close with nil fetcher panicked: %v", r)
+ }
+ }()
+ p.Close()
+ })
+
+ t.Run("non_closer_fetcher_skips_close", func(t *testing.T) {
+ // stubPlainFetch has no Close method, so the fetcherCloser type
+ // assertion fails and Close must be a no-op rather than panicking.
+ p := NewLiveProvider(stubPlainFetch{})
+ defer func() {
+ if r := recover(); r != nil {
+ t.Fatalf("(*Provider).Close on non-closer fetcher panicked: %v", r)
+ }
+ }()
+ p.Close()
+ })
+
+ t.Run("closer_fetcher_close_invoked_exactly_once", func(t *testing.T) {
+ closer := &stubCloseFetch{}
+ p := NewLiveProvider(closer)
+ p.Close()
+ if got := closer.closes.Load(); got != 1 {
+ t.Fatalf("Provider.Close proxied %d calls to fetcher.Close, want exactly 1", got)
+ }
+ })
+}
+
+// TestBranchcov0723Am_NewAPIProvider covers NewAPIProvider in provider.go.
+// It asserts the returned Provider wraps the supplied client and metadata in
+// an *APIFetcher (field plumbing is the documented behaviour of the
+// constructor), and that the resulting fetcher also satisfies fetcherCloser
+// so Provider.Close proxies through to Client.Close.
+func TestBranchcov0723Am_NewAPIProvider(t *testing.T) {
+ client, err := NewClient(ClientConfig{Host: "vc.example.com", Port: 443})
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+ t.Cleanup(client.Close)
+
+ meta := ProviderMetadata{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ VCenterHost: "vc.lab.local",
+ }
+ p := NewAPIProvider(meta, client)
+
+ apiFetch, ok := p.fetcher.(*APIFetcher)
+ if !ok {
+ t.Fatalf("p.fetcher type = %T, want *APIFetcher", p.fetcher)
+ }
+ if apiFetch.Client != client {
+ t.Errorf("APIFetcher.Client = %p, want the exact client passed to NewAPIProvider (%p)", apiFetch.Client, client)
+ }
+ if apiFetch.Metadata != meta {
+ t.Errorf("APIFetcher.Metadata = %+v, want %+v", apiFetch.Metadata, meta)
+ }
+
+ // The wrapped *APIFetcher has a Close method, so (*Provider).Close must
+ // proxy through to Client.Close without panicking. (Client.Close on a
+ // never-used client is a benign drain of an empty idle pool.)
+ p.Close()
+}
+
+// TestBranchcov0723Am_APIFetcherFetchErrorArm covers (*APIFetcher).Fetch in
+// provider.go. Only the deterministic error arm (f == nil || f.Client == nil)
+// is reachable offline; the success arm calls Client.CollectInventory which
+// dials a live vCenter and is skipped per the spec's purity gate.
+func TestBranchcov0723Am_APIFetcherFetchErrorArm(t *testing.T) {
+ t.Run("nil_client_returns_client_nil_error", func(t *testing.T) {
+ f := &APIFetcher{}
+ got, err := f.Fetch(context.Background())
+ if got != nil {
+ t.Errorf("nil-client Fetch = %v, want nil", got)
+ }
+ if err == nil {
+ t.Fatal("nil-client Fetch err = nil, want error")
+ }
+ if !strings.Contains(err.Error(), "client is nil") {
+ t.Errorf("nil-client Fetch err = %q, want it to mention 'client is nil'", err.Error())
+ }
+ })
+
+ t.Run("nil_receiver_returns_client_nil_error", func(t *testing.T) {
+ // Distinct from nil-Client: this exercises Go's method-on-nil-pointer
+ // resolution plus the f == nil short-circuit in the guard.
+ var f *APIFetcher
+ got, err := f.Fetch(context.Background())
+ if got != nil {
+ t.Errorf("nil-receiver Fetch = %v, want nil", got)
+ }
+ if err == nil {
+ t.Fatal("nil-receiver Fetch err = nil, want error")
+ }
+ if !strings.Contains(err.Error(), "client is nil") {
+ t.Errorf("nil-receiver Fetch err = %q, want it to mention 'client is nil'", err.Error())
+ }
+ })
+}
+
+// newCloseCountingClient constructs a *Client pointed at a loopback TLS test
+// server that counts accepted TCP connections (via http.Server.ConnState on
+// StateNew). The returned doReq closure issues a GET against the server
+// through the client's own http client, so callers can observe whether the
+// client reused an idle connection (accept count unchanged) or dialled a new
+// one (accept count incremented). This is offline (127.0.0.1 only) and does
+// not dial any vCenter. The server is cleaned up via t.Cleanup.
+func newCloseCountingClient(t *testing.T) (client *Client, doReq func(), accepted func() int32) {
+ t.Helper()
+ var count atomic.Int32
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+ srv := httptest.NewUnstartedServer(handler)
+ srv.Config.ConnState = func(_ net.Conn, state http.ConnState) {
+ if state == http.StateNew {
+ count.Add(1)
+ }
+ }
+ srv.StartTLS()
+ t.Cleanup(srv.Close)
+
+ host := strings.TrimPrefix(srv.URL, "https://")
+ c, err := NewClient(ClientConfig{
+ Host: host,
+ InsecureSkipVerify: true,
+ })
+ if err != nil {
+ t.Fatalf("NewClient(%q): %v", host, err)
+ }
+
+ doReq = func() {
+ t.Helper()
+ req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://"+c.baseURL.Host+"/", nil)
+ if err != nil {
+ t.Fatalf("http.NewRequestWithContext: %v", err)
+ }
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ t.Fatalf("httpClient.Do: %v", err)
+ }
+ _, _ = io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ }
+ return c, doReq, func() int32 { return count.Load() }
+}
+
+// waitForAcceptCount polls the accepted-connection count for up to 2 seconds
+// so the test does not race the server-side ConnState callback (which fires
+// from the server's goroutine on each new connection).
+func waitForAcceptCount(t *testing.T, accepted func() int32, want int32) {
+ t.Helper()
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ if accepted() >= want {
+ return
+ }
+ time.Sleep(2 * time.Millisecond)
+ }
+ t.Fatalf("accepted connection count = %d, want >= %d", accepted(), want)
+}
+
+// TestBranchcov0723Am_ClientClose covers (*Client).Close in client.go. The
+// meaningful, observable arm — the (*http.Transport) type assertion
+// succeeding and calling transport.CloseIdleConnections — is asserted
+// behaviourally via a loopback TLS server whose ConnState callback counts
+// accepted TCP connections: after Close, a follow-up request must open a
+// fresh connection rather than reuse a pooled idle one. The nil-receiver and
+// nil-httpClient guard arms are covered as documented nil-safety contracts
+// (explicit recover-based assertions).
+func TestBranchcov0723Am_ClientClose(t *testing.T) {
+ t.Run("nil_receiver_is_a_documented_noop", func(t *testing.T) {
+ var c *Client
+ defer func() {
+ if r := recover(); r != nil {
+ t.Fatalf("(*Client).Close on nil receiver panicked: %v", r)
+ }
+ }()
+ c.Close()
+ })
+
+ t.Run("nil_http_client_short_circuits", func(t *testing.T) {
+ c := &Client{}
+ defer func() {
+ if r := recover(); r != nil {
+ t.Fatalf("(*Client).Close with nil httpClient panicked: %v", r)
+ }
+ }()
+ c.Close()
+ })
+
+ t.Run("transport_arm_drains_idle_connections", func(t *testing.T) {
+ client, doReq, accepted := newCloseCountingClient(t)
+
+ // First request opens connection #1.
+ doReq()
+ waitForAcceptCount(t, accepted, 1)
+
+ // Second request must reuse the pooled idle connection rather than
+ // opening a new one: the accept count must stay at 1.
+ doReq()
+ waitForAcceptCount(t, accepted, 1)
+ if got := accepted(); got != 1 {
+ t.Fatalf("idle conn was not reused: server accepted %d conns after two requests, want 1", got)
+ }
+
+ client.Close() // drain the idle pool
+
+ // Third request must dial a fresh connection because Close reaped the
+ // idle one: the accept count must climb to 2.
+ doReq()
+ waitForAcceptCount(t, accepted, 2)
+ if got := accepted(); got != 2 {
+ t.Fatalf("Close did not drain idle pool: third request reused a pooled conn (accepted=%d), want a fresh conn (2)", got)
+ }
+ })
+}
+
+// TestBranchcov0723Am_APIFetcherClose covers (*APIFetcher).Close in
+// provider.go. The proxies-to-Client.Close arm is asserted behaviourally with
+// the same loopback TLS server machinery used for (*Client).Close, proving
+// the call chains down to transport.CloseIdleConnections. The nil-receiver
+// and nil-Client guard arms are covered as documented nil-safety contracts.
+func TestBranchcov0723Am_APIFetcherClose(t *testing.T) {
+ t.Run("nil_receiver_is_a_documented_noop", func(t *testing.T) {
+ var f *APIFetcher
+ defer func() {
+ if r := recover(); r != nil {
+ t.Fatalf("(*APIFetcher).Close on nil receiver panicked: %v", r)
+ }
+ }()
+ f.Close()
+ })
+
+ t.Run("nil_client_short_circuits", func(t *testing.T) {
+ f := &APIFetcher{}
+ defer func() {
+ if r := recover(); r != nil {
+ t.Fatalf("(*APIFetcher).Close with nil Client panicked: %v", r)
+ }
+ }()
+ f.Close()
+ })
+
+ t.Run("proxies_through_to_client_close_draining_idle_pool", func(t *testing.T) {
+ client, doReq, accepted := newCloseCountingClient(t)
+ f := &APIFetcher{Client: client}
+
+ doReq()
+ waitForAcceptCount(t, accepted, 1)
+ doReq()
+ if got := accepted(); got != 1 {
+ t.Fatalf("idle conn was not reused: server accepted %d conns after two requests, want 1", got)
+ }
+
+ f.Close() // must chain through to Client.Close -> transport.CloseIdleConnections
+
+ doReq()
+ waitForAcceptCount(t, accepted, 2)
+ if got := accepted(); got != 2 {
+ t.Fatalf("APIFetcher.Close did not drain idle pool through Client.Close: third request reused a pooled conn (accepted=%d), want a fresh conn (2)", got)
+ }
+ })
+}