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 agent policy, alias normalization and agent report helpers
rcourtman133a47d284e3
diff --git a/internal/agentexec/policy_sudo_branchcov0723am_test.go b/internal/agentexec/policy_sudo_branchcov0723am_test.gonew file mode 100644index 0000000000..30b3b2e9e3--- /dev/null+++ b/internal/agentexec/policy_sudo_branchcov0723am_test.go@@ -0,0 +1,147 @@+package agentexec++import (+ "errors"+ "fmt"+ "testing"+)++// branchcovSentinelErr is a concrete sentinel error type used to verify that+// errors.Is/errors.As traverse the ApprovalGrantVerificationError wrapper.+type branchcovSentinelErr struct{ msg string }++func (e *branchcovSentinelErr) Error() string { return e.msg }++// TestBranchcov0723AmSudoLongOptionNeedsValue exhaustively covers every long+// option that sudoLongOptionNeedsValue identifies as value-requiring, plus the+// negative arms: value-less long option, inline =value form (which the source+// treats as an exact-match miss), unknown long option, short option, empty+// string and whitespace-only string.+func TestBranchcov0723AmSudoLongOptionNeedsValue(t *testing.T) {+ cases := []struct {+ name string+ token string+ want bool+ }{+ // Every option the source lists as value-requiring must return true.+ {"user needs value", "--user", true},+ {"group needs value", "--group", true},+ {"host needs value", "--host", true},+ {"prompt needs value", "--prompt", true},+ {"chdir needs value", "--chdir", true},+ {"close-from needs value", "--close-from", true},+ {"command-timeout needs value", "--command-timeout", true},+ {"role needs value", "--role", true},+ {"type needs value", "--type", true},++ // Long option that does NOT need a value: source falls into default arm.+ {"help does not need value", "--help", false},++ // Inline =value form: the source performs an exact string match against+ // the bare option name, so "--user=root" is not equal to "--user" and+ // the function returns false. (extractSudoCommand pre-filters the+ // "=value" form before calling this, but this function in isolation+ // does not special-case it.)+ {"inline equals form does not match", "--user=root", false},++ // Unknown long option: default arm.+ {"unknown long option", "--not-a-real-sudo-flag", false},++ // Short option (not a long option): default arm.+ {"short option", "-u", false},++ // Empty string: default arm.+ {"empty string", "", false},++ // Whitespace-only string: default arm.+ {"whitespace only", " ", false},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := sudoLongOptionNeedsValue(tc.token)+ if got != tc.want {+ t.Fatalf("sudoLongOptionNeedsValue(%q) = %v, want %v", tc.token, got, tc.want)+ }+ })+ }+}++// TestBranchcov0723AmApprovalGrantVerificationErrorUnwrap covers both arms of+// Unwrap(): nil receiver and a receiver wrapping a cause. It asserts that the+// standard errors.Is/errors.As machinery reaches the wrapped cause THROUGH the+// wrapper rather than merely checking that Unwrap returns non-nil.+func TestBranchcov0723AmApprovalGrantVerificationErrorUnwrap(t *testing.T) {+ t.Run("wrapped cause is reachable via errors.Is and errors.As", func(t *testing.T) {+ cause := &branchcovSentinelErr{msg: "boom"}+ // Wrap once more with %w so we exercise two Unwrap hops before reaching+ // the sentinel: ApprovalGrantVerificationError -> fmt wrap -> sentinel.+ nested := fmt.Errorf("outer wrap: %w", cause)+ verr := &ApprovalGrantVerificationError{Reason: "test", Err: nested}++ if !errors.Is(verr, cause) {+ t.Fatalf("errors.Is must find sentinel cause through ApprovalGrantVerificationError wrapper")+ }++ var found *branchcovSentinelErr+ if !errors.As(verr, &found) {+ t.Fatalf("errors.As must extract sentinel cause through ApprovalGrantVerificationError wrapper")+ }+ if found != cause {+ t.Fatalf("errors.As resolved wrong instance: got %p, want %p", found, cause)+ }+ })++ t.Run("nil cause yields nil unwrap and no false matches", func(t *testing.T) {+ verr := &ApprovalGrantVerificationError{Reason: "test", Err: nil}++ if got := verr.Unwrap(); got != nil {+ t.Fatalf("Unwrap() = %v, want nil when cause is nil", got)+ }++ sentinel := errors.New("unrelated sentinel")+ if errors.Is(verr, sentinel) {+ t.Fatalf("errors.Is must be false when cause is nil")+ }+ })++ t.Run("nil receiver yields nil unwrap", func(t *testing.T) {+ var nilVerr *ApprovalGrantVerificationError+ if got := nilVerr.Unwrap(); got != nil {+ t.Fatalf("Unwrap() on nil receiver = %v, want nil", got)+ }+ })+}++// TestBranchcov0723AmApprovalGrantVerificationErrorMessage covers Error() for+// all three branches: wrapped cause (returns e.Err.Error()), nil cause, and+// nil receiver (both fall back to the default message).+func TestBranchcov0723AmApprovalGrantVerificationErrorMessage(t *testing.T) {+ t.Run("wrapped cause surfaces underlying message", func(t *testing.T) {+ cause := errors.New("the underlying message")+ verr := &ApprovalGrantVerificationError{Reason: "test", Err: cause}++ const want = "the underlying message"+ if got := verr.Error(); got != want {+ t.Fatalf("Error() = %q, want %q", got, want)+ }+ })++ t.Run("nil cause returns default message", func(t *testing.T) {+ verr := &ApprovalGrantVerificationError{Reason: "test", Err: nil}++ const want = "approval grant verification failed"+ if got := verr.Error(); got != want {+ t.Fatalf("Error() = %q, want %q", got, want)+ }+ })++ t.Run("nil receiver returns default message", func(t *testing.T) {+ var nilVerr *ApprovalGrantVerificationError++ const want = "approval grant verification failed"+ if got := nilVerr.Error(); got != want {+ t.Fatalf("Error() on nil receiver = %q, want %q", got, want)+ }+ })+}diff --git a/internal/alerts/config_facade_alias_branchcov0723am_test.go b/internal/alerts/config_facade_alias_branchcov0723am_test.gonew file mode 100644index 0000000000..087bb15d76--- /dev/null+++ b/internal/alerts/config_facade_alias_branchcov0723am_test.go@@ -0,0 +1,173 @@+package alerts++import (+ "reflect"+ "testing"+)++// TestBranchcov0723Am raises branch coverage of NormalizeAlertConfigAliases+// (the alerts-package facade at internal/alerts/config_facade.go:65, which+// delegates to internal/alerts/config/types.go:294).+//+// The function strips deprecated legacy resource-type keys from+// TimeThresholds and MetricTimeThresholds. Its branches are:+// - nil config guard+// - nil TimeThresholds (skip the first loop)+// - per-key: CanonicalAlertResourceType(key) == "" or "all" -> continue (keep)+// - per-key: isUnsupportedLegacyAlertResourceType(typeKey) -> delete, else keep+// - len(MetricTimeThresholds) == 0 -> early return+// - the same per-key arms on MetricTimeThresholds+//+// Each subtest is independent: it builds its own AlertConfig and asserts the+// concrete post-call map contents (and that the function never renames keys,+// only deletes).+func TestBranchcov0723Am(t *testing.T) {+ t.Run("nil_config_does_not_panic", func(t *testing.T) {+ // Drives the `config == nil` early-return guard.+ defer func() {+ if r := recover(); r != nil {+ t.Fatalf("NormalizeAlertConfigAliases(nil) panicked: %v", r)+ }+ }()+ NormalizeAlertConfigAliases(nil)+ })++ tests := []struct {+ name string+ time map[string]int+ metric map[string]map[string]int+ // Pointers so nil vs empty-non-nil map distinctions are explicit.+ wantTime map[string]int+ wantMetric map[string]map[string]int+ }{+ {+ // TimeThresholds == nil exercises the `!= nil` skip; the non-empty+ // metric map forces the metric loop to run so we can observe the+ // function reached it (the supported "guest" key is retained).+ name: "time_thresholds_nil_map_skipped_metric_loop_runs",+ time: nil,+ metric: map[string]map[string]int{"guest": {"cpu": 5}},+ wantTime: nil,+ wantMetric: map[string]map[string]int{"guest": {"cpu": 5}},+ },+ {+ // Legacy keys are deleted; supported canonical keys are retained+ // with their original values. Both "host" and "docker_host" are in+ // the CanonicalizeLegacyResourceTypeAlias map, so both are caught by+ // the IsUnsupportedLegacyResourceTypeAlias arm before the local+ // switch is reached. The local-switch arm is exercised separately by+ // "docker" in the metric-threshold case below, which the alias map+ // does not recognise.+ name: "time_thresholds_strips_legacy_keeps_supported",+ time: map[string]int{+ "host": 1,+ "docker_host": 6,+ "guest": 2,+ "agent": 4,+ },+ metric: nil,+ wantTime: map[string]int{"guest": 2, "agent": 4},+ wantMetric: nil,+ },+ {+ // typeKey == "" (empty/whitespace raw key) and typeKey == "all"+ // both hit the `continue` arm and are preserved verbatim.+ name: "time_thresholds_preserves_all_blank_whitespace_keys",+ time: map[string]int{+ "all": 9,+ "": 8,+ " ": 7,+ },+ metric: nil,+ wantTime: map[string]int{"all": 9, "": 8, " ": 7},+ wantMetric: nil,+ },+ {+ // "kubernetes cluster" canonicalizes to "k8s-cluster" (supported),+ // so it is neither deleted nor renamed -- the function only strips,+ // it never rewrites the stored key. Asserts the original key survives.+ name: "time_thresholds_canonicalized_type_not_renamed",+ time: map[string]int{"kubernetes cluster": 11},+ metric: nil,+ wantTime: map[string]int{"kubernetes cluster": 11},+ wantMetric: nil,+ },+ {+ // MetricTimeThresholds legacy strip + supported retain. TimeThresholds+ // is nil, which also exercises the `len(metric) != 0` path (i.e. the+ // early-return arm is NOT taken here).+ name: "metric_strips_legacy_keeps_supported",+ time: nil,+ metric: map[string]map[string]int{+ "docker": {"cpu": 9},+ "node": {"mem": 3},+ },+ wantTime: nil,+ wantMetric: map[string]map[string]int{+ "node": {"mem": 3},+ },+ },+ {+ // typeKey == "" and typeKey == "all" hit the metric-loop `continue`+ // arm and are preserved.+ name: "metric_preserves_all_blank_keys",+ time: nil,+ metric: map[string]map[string]int{+ "all": {"cpu": 1},+ "": {"x": 2},+ },+ wantTime: nil,+ wantMetric: map[string]map[string]int{+ "all": {"cpu": 1},+ "": {"x": 2},+ },+ },+ {+ // len(MetricTimeThresholds) == 0 (empty non-nil map) takes the+ // early return; meanwhile the TimeThresholds loop still ran and+ // stripped "host", proving the two paths are independent.+ name: "metric_empty_map_returns_early",+ time: map[string]int{"host": 1},+ metric: map[string]map[string]int{},+ wantTime: map[string]int{},+ wantMetric: map[string]map[string]int{},+ },+ {+ // Both maps populated with a legacy + supported pair; each is+ // reduced independently of the other.+ name: "both_maps_strip_legacy_independently",+ time: map[string]int{+ "host": 1,+ "guest": 2,+ },+ metric: map[string]map[string]int{+ "docker": {"cpu": 9},+ "node": {"mem": 3},+ },+ wantTime: map[string]int{"guest": 2},+ wantMetric: map[string]map[string]int{+ "node": {"mem": 3},+ },+ },+ }++ for _, tc := range tests {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ cfg := &AlertConfig{+ TimeThresholds: tc.time,+ MetricTimeThresholds: tc.metric,+ }+ NormalizeAlertConfigAliases(cfg)++ if !reflect.DeepEqual(cfg.TimeThresholds, tc.wantTime) {+ t.Fatalf("TimeThresholds mismatch:\n got: %#v\nwant: %#v",+ cfg.TimeThresholds, tc.wantTime)+ }+ if !reflect.DeepEqual(cfg.MetricTimeThresholds, tc.wantMetric) {+ t.Fatalf("MetricTimeThresholds mismatch:\n got: %#v\nwant: %#v",+ cfg.MetricTimeThresholds, tc.wantMetric)+ }+ })+ }+}diff --git a/internal/alerts/specs/rollup_evidence_branchcov0723am_test.go b/internal/alerts/specs/rollup_evidence_branchcov0723am_test.gonew file mode 100644index 0000000000..079ee8dda3--- /dev/null+++ b/internal/alerts/specs/rollup_evidence_branchcov0723am_test.go@@ -0,0 +1,69 @@+package specs++import "testing"++// TestBranchcov0723AmResourceIncidentRollupEvidenceValidate exercises every+// branch of ResourceIncidentRollupEvidence.Validate (types.go:950), which has+// two arms (empty code, non-positive incident count) plus the happy path.+func TestBranchcov0723AmResourceIncidentRollupEvidenceValidate(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ evidence ResourceIncidentRollupEvidence+ wantErr string // exact error message; empty means Validate must return nil+ }{+ {+ name: "zero value surfaces code error first",+ evidence: ResourceIncidentRollupEvidence{},+ wantErr: "code is required",+ },+ {+ // Non-empty string that trims to empty: pins the strings.TrimSpace+ // behaviour of the guard (a plain "Code == \"\"" check would pass this).+ name: "whitespace-only code is treated as missing",+ evidence: ResourceIncidentRollupEvidence{Code: " \t\n", IncidentCount: 5},+ wantErr: "code is required",+ },+ {+ // Ordering proof: when the code guard passes but the count guard+ // fails, the count error is what surfaces.+ name: "valid code with zero count rejected at count guard",+ evidence: ResourceIncidentRollupEvidence{Code: "capacity_runway_low", IncidentCount: 0},+ wantErr: "incident count must be positive",+ },+ {+ // Boundary: one above the <= 0 threshold is the minimum valid count.+ name: "minimum positive count is valid",+ evidence: ResourceIncidentRollupEvidence{Code: "capacity_runway_low", IncidentCount: 1},+ wantErr: "",+ },+ {+ // Confirms there is no upper bound on incident count.+ name: "large positive count is valid",+ evidence: ResourceIncidentRollupEvidence{Code: "replica_flapping", IncidentCount: 10_000},+ wantErr: "",+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()++ err := tc.evidence.Validate()+ if tc.wantErr == "" {+ if err != nil {+ t.Fatalf("Validate() unexpected error = %v", err)+ }+ return+ }+ if err == nil {+ t.Fatalf("Validate() expected error %q, got nil", tc.wantErr)+ }+ if err.Error() != tc.wantErr {+ t.Fatalf("Validate() error = %q, want %q", err.Error(), tc.wantErr)+ }+ })+ }+}diff --git a/internal/cloudcp/docker/manager_routing_branchcov0723am_test.go b/internal/cloudcp/docker/manager_routing_branchcov0723am_test.gonew file mode 100644index 0000000000..90e43a1f28--- /dev/null+++ b/internal/cloudcp/docker/manager_routing_branchcov0723am_test.go@@ -0,0 +1,192 @@+package docker++import (+ "errors"+ "fmt"+ "testing"++ "github.com/containerd/errdefs"+)++// customNotFoundErr implements errdefs' private notFound interface (a method+// named NotFound()) without embedding errdefs.ErrNotFound, so it exercises the+// isInterface arm of errdefs.IsNotFound rather than the errors.Is arm.+type customNotFoundErr struct{ msg string }++func (c customNotFoundErr) Error() string { return "missing: " + c.msg }+func (c customNotFoundErr) NotFound() {}++func TestBranchcov0723AmIsNotFound(t *testing.T) {+ t.Parallel()++ notFoundWrapped := fmt.Errorf("inspect image pulse:test: %w", errdefs.ErrNotFound)++ tests := []struct {+ name string+ err error+ want bool+ }{+ {name: "nil error is not not-found", err: nil, want: false},+ {name: "plain errors.New is not not-found", err: errors.New("boom"), want: false},+ {name: "verbatim errdefs.ErrNotFound matches", err: errdefs.ErrNotFound, want: true},+ {name: "wrapped errdefs.ErrNotFound via fmt.Errorf %w matches", err: notFoundWrapped, want: true},+ {name: "unrelated typed errdefs error does not match", err: errdefs.ErrAlreadyExists, want: false},+ {name: "similarly-worded string error must not match", err: errors.New("not found: image pulse:test"), want: false},+ {name: "custom error implementing NotFound() matches via interface arm", err: customNotFoundErr{msg: "image pulse:test"}, want: true},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if got := IsNotFound(tc.err); got != tc.want {+ t.Fatalf("IsNotFound(%v) = %v, want %v", tc.err, got, tc.want)+ }+ })+ }+}++func TestBranchcov0723AmParseTraefikHostRule(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ rule string+ want string+ }{+ {name: "empty rule yields empty host", rule: "", want: ""},+ {name: "whitespace-only rule yields empty host", rule: " \t\n ", want: ""},+ {name: "rule without Host clause yields empty host", rule: "PathPrefix(`/api`)", want: ""},+ {name: "well-formed backtick Host returns exact hostname", rule: "Host(`example.com`)", want: "example.com"},+ {name: "surrounding whitespace is trimmed before matching", rule: " Host(`example.com`) ", want: "example.com"},+ {name: "single-quote variant is rejected (source matches backticks only)", rule: "Host('example.com')", want: ""},+ {name: "double-quote variant is rejected (source matches backticks only)", rule: "Host(\"example.com\")", want: ""},+ // NOTE: the source checks prefix "Host(`" and suffix "`)" independently+ // rather than verifying the rule is a single Host clause. Combined+ // rules that happen to start with Host(` and end with `) therefore+ // pass both checks and return the malformed text in between. The+ // following two cases assert that real (buggy) behaviour rather than+ // the intuitive empty string; see REPORT for the suspected source bug.+ {name: "Host combined with PathPrefix via && is NOT rejected (lenient parser)", rule: "Host(`example.com`) && PathPrefix(`/api`)", want: "example.com`) && PathPrefix(`/api"},+ {name: "Host combined with another Host via || is NOT rejected (lenient parser)", rule: "Host(`a.com`) || Host(`b.com`)", want: "a.com`) || Host(`b.com"},+ {name: "PathPrefix first then Host is rejected (prefix mismatch)", rule: "PathPrefix(`/api`) && Host(`example.com`)", want: ""},+ {name: "trailing content after closing backtick-paren is rejected", rule: "Host(`example.com`)foo", want: ""},+ {name: "unterminated Host clause yields empty host", rule: "Host(`example.com", want: ""},+ {name: "missing opening backtick yields empty host", rule: "Host(example.com`)", want: ""},+ {name: "Host with empty hostname between backticks yields empty host", rule: "Host(``)", want: ""},+ {name: "host containing a dot inside backticks is preserved verbatim", rule: "Host(`sub.example.com`)", want: "sub.example.com"},+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ if got := parseTraefikHostRule(tc.rule); got != tc.want {+ t.Fatalf("parseTraefikHostRule(%q) = %q, want %q", tc.rule, got, tc.want)+ }+ })+ }+}++func TestBranchcov0723AmRouteHostFromLabels(t *testing.T) {+ t.Parallel()++ tests := []struct {+ name string+ // wantSet, when non-nil, is used when the source's behaviour is+ // intentionally non-deterministic (Go map iteration order is random).+ // The subtest passes if the result is any one of wantSet's entries.+ wantSet map[string]bool+ labels map[string]string+ want string+ }{+ {name: "nil map returns empty host", labels: nil, want: ""},+ {name: "empty map returns empty host", labels: map[string]string{}, want: ""},+ {+ name: "matching key with well-formed Host rule returns the host",+ labels: map[string]string{"traefik.http.routers.pulse-t-acme.rule": "Host(`t-acme.cloud.example.com`)"},+ want: "t-acme.cloud.example.com",+ },+ {name: "matching key with empty rule returns empty host", labels: map[string]string{"traefik.http.routers.pulse.rule": ""}, want: ""},+ {name: "matching key with non-Host rule returns empty host", labels: map[string]string{"traefik.http.routers.pulse.rule": "PathPrefix(`/api`)"}, want: ""},+ {name: "matching key with unterminated Host returns empty host", labels: map[string]string{"traefik.http.routers.pulse.rule": "Host(`example.com"}, want: ""},+ {+ // Inherits parseTraefikHostRule's lenient behaviour: a combined+ // matcher rule starting with Host(` and ending with `) parses to a+ // non-empty (but malformed) value, so routeHostFromLabels returns+ // that value rather than the empty string. See REPORT for the+ // suspected source bug in parseTraefikHostRule.+ name: "router-rule key with combined matcher rule returns the parser's malformed output",+ labels: map[string]string{+ "traefik.http.routers.pulse.rule": "Host(`example.com`) && PathPrefix(`/api`)",+ },+ want: "example.com`) && PathPrefix(`/api",+ },+ {+ name: "non-router prefix label is filtered out even when its value would parse",+ labels: map[string]string{+ "traefik.http.services.pulse.rule": "Host(`example.com`)",+ },+ want: "",+ },+ {+ name: "non-rule suffix label is filtered out even when its value would parse",+ labels: map[string]string{+ "traefik.http.routers.pulse.middlewares": "Host(`example.com`)",+ },+ want: "",+ },+ {+ name: "unrelated label is ignored and returns empty host",+ labels: map[string]string{+ "pulse.tenant.id": "t-acme",+ "com.example.foo": "bar",+ },+ want: "",+ },+ {+ name: "single valid Host rule among several malformed matching labels is returned",+ labels: map[string]string{+ "traefik.http.routers.alpha.rule": "",+ "traefik.http.routers.beta.rule": "PathPrefix(`/api`)",+ "traefik.http.routers.gamma.rule": "Host(`gamma.example.com`)",+ "traefik.http.routers.delta.rule": "Host(`delta.example`)foo",+ },+ want: "gamma.example.com",+ },+ {+ name: "multiple matching labels that all yield empty hosts return empty",+ labels: map[string]string{+ "traefik.http.routers.alpha.rule": "",+ "traefik.http.routers.beta.rule": "PathPrefix(`/api`)",+ },+ want: "",+ },+ {+ // The source iterates a Go map (random order) and returns the first+ // label that parses to a non-empty host; with two equally-valid+ // Host rules the result is non-deterministic. Assert the result is+ // one of the valid candidates rather than a specific winner.+ name: "two equally-valid matching labels: result is one of the valid hosts",+ labels: map[string]string{+ "traefik.http.routers.alpha.rule": "Host(`alpha.example.com`)",+ "traefik.http.routers.beta.rule": "Host(`beta.example.com`)",+ },+ wantSet: map[string]bool{"alpha.example.com": true, "beta.example.com": true},+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()+ got := routeHostFromLabels(tc.labels)+ if tc.wantSet != nil {+ if !tc.wantSet[got] {+ t.Fatalf("routeHostFromLabels(%v) = %q, want one of %v", tc.labels, got, tc.wantSet)+ }+ return+ }+ if got != tc.want {+ t.Fatalf("routeHostFromLabels(%v) = %q, want %q", tc.labels, got, tc.want)+ }+ })+ }+}diff --git a/internal/cloudcp/portal/bootstrap_anonymous_branchcov0723am_test.go b/internal/cloudcp/portal/bootstrap_anonymous_branchcov0723am_test.gonew file mode 100644index 0000000000..3d329a47d6--- /dev/null+++ b/internal/cloudcp/portal/bootstrap_anonymous_branchcov0723am_test.go@@ -0,0 +1,236 @@+package portal++import (+ "reflect"+ "testing"+)++// TestBranchcov0723Am_AnonymousBootstrap_ZeroEnvironment_AssertsEveryField+// drives BuildAnonymousBootstrapDataWithEnvironment with a zero-value+// PortalEnvironment and asserts every field of the returned BootstrapData,+// including that Accounts is a non-nil empty slice (the source uses make over+// the nil accounts input rather than leaving the field nil).+func TestBranchcov0723Am_AnonymousBootstrap_ZeroEnvironment_AssertsEveryField(t *testing.T) {+ got := BuildAnonymousBootstrapDataWithEnvironment(PortalEnvironment{})++ want := BootstrapData{+ // Identity/security-relevant fields: anonymous must leave all of these unset.+ Authenticated: false,+ Email: "",+ HasSelfHostedCommercial: false,+ // Environment-derived fields: a zero PortalEnvironment propagates zero.+ EmailSignInAvailable: false,+ ProviderHostedMode: false,+ SignupPath: "",+ // Static defaults copied from the package-level default*/Portal* constants.+ PublicSiteURL: "https://pulserelay.pro",+ SupportEmail: "[email protected]",+ CommercialAPIBaseURL: "/api/portal/commercial",+ CommercialAPIBasePath: "/api/portal/commercial",+ PortalPath: "/portal",+ BootstrapPath: "/api/portal/bootstrap",+ MagicLinkRequestPath: "/api/public/magic-link/request",+ LogoutPath: "/auth/logout",+ AccountAPIBasePath: "/api/accounts",+ PortalAPIBasePath: "/api/portal",+ // Source runs make([]BootstrapAccount, 0, len(nil)) -> non-nil empty slice.+ Accounts: []BootstrapAccount{},+ }++ if !reflect.DeepEqual(got, want) {+ t.Fatalf("BuildAnonymousBootstrapDataWithEnvironment(zero env) mismatch:\n got = %#v\nwant = %#v", got, want)+ }+ if got.Accounts == nil {+ t.Errorf("Accounts = nil, want non-nil empty slice (source uses make())")+ }+}++// TestBranchcov0723Am_AnonymousBootstrap_PopulatedEnvironment_AssertsEveryField+// drives every PortalEnvironment field from the populated side and asserts+// each propagates onto the result while every static default and the anonymity+// invariant remain unchanged.+func TestBranchcov0723Am_AnonymousBootstrap_PopulatedEnvironment_AssertsEveryField(t *testing.T) {+ env := PortalEnvironment{+ SignupPath: "/custom-signup",+ EmailSignInAvailable: true,+ ProviderHostedMode: true,+ }+ got := BuildAnonymousBootstrapDataWithEnvironment(env)++ want := BootstrapData{+ // Still anonymous: identity fields stay empty regardless of env.+ Authenticated: false,+ Email: "",+ HasSelfHostedCommercial: false,+ // Environment-derived: every env field propagates.+ EmailSignInAvailable: true,+ ProviderHostedMode: true,+ SignupPath: "/custom-signup",+ // Static defaults are env-independent.+ PublicSiteURL: "https://pulserelay.pro",+ SupportEmail: "[email protected]",+ CommercialAPIBaseURL: "/api/portal/commercial",+ CommercialAPIBasePath: "/api/portal/commercial",+ PortalPath: "/portal",+ BootstrapPath: "/api/portal/bootstrap",+ MagicLinkRequestPath: "/api/public/magic-link/request",+ LogoutPath: "/auth/logout",+ AccountAPIBasePath: "/api/accounts",+ PortalAPIBasePath: "/api/portal",+ Accounts: []BootstrapAccount{},+ }++ if !reflect.DeepEqual(got, want) {+ t.Fatalf("BuildAnonymousBootstrapDataWithEnvironment(populated env) mismatch:\n got = %#v\nwant = %#v", got, want)+ }+ if got.Accounts == nil {+ t.Errorf("Accounts = nil, want non-nil empty slice")+ }+}++// TestBranchcov0723Am_AnonymousBootstrap_EnvironmentFieldPropagation drives+// each PortalEnvironment-driven conditional from both arms independently so+// the propagation of SignupPath, EmailSignInAvailable and ProviderHostedMode+// is exercised in isolation rather than only via the all-zero/all-set cases.+func TestBranchcov0723Am_AnonymousBootstrap_EnvironmentFieldPropagation(t *testing.T) {+ cases := []struct {+ name string+ env PortalEnvironment+ wantSignupPath string+ wantEmailSignIn bool+ wantProviderHost bool+ }{+ {+ name: "signup_path_empty",+ env: PortalEnvironment{SignupPath: ""},+ wantSignupPath: "",+ wantEmailSignIn: false,+ wantProviderHost: false,+ },+ {+ name: "signup_path_populated",+ env: PortalEnvironment{SignupPath: "/sign-up-here"},+ wantSignupPath: "/sign-up-here",+ wantEmailSignIn: false,+ wantProviderHost: false,+ },+ {+ name: "email_sign_in_off",+ env: PortalEnvironment{EmailSignInAvailable: false},+ wantSignupPath: "",+ wantEmailSignIn: false,+ wantProviderHost: false,+ },+ {+ name: "email_sign_in_on",+ env: PortalEnvironment{EmailSignInAvailable: true},+ wantSignupPath: "",+ wantEmailSignIn: true,+ wantProviderHost: false,+ },+ {+ name: "provider_hosted_off",+ env: PortalEnvironment{ProviderHostedMode: false},+ wantSignupPath: "",+ wantEmailSignIn: false,+ wantProviderHost: false,+ },+ {+ name: "provider_hosted_on",+ env: PortalEnvironment{ProviderHostedMode: true},+ wantSignupPath: "",+ wantEmailSignIn: false,+ wantProviderHost: true,+ },+ }++ for _, tc := range cases {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ got := BuildAnonymousBootstrapDataWithEnvironment(tc.env)+ if got.SignupPath != tc.wantSignupPath {+ t.Errorf("SignupPath = %q, want %q", got.SignupPath, tc.wantSignupPath)+ }+ if got.EmailSignInAvailable != tc.wantEmailSignIn {+ t.Errorf("EmailSignInAvailable = %v, want %v", got.EmailSignInAvailable, tc.wantEmailSignIn)+ }+ if got.ProviderHostedMode != tc.wantProviderHost {+ t.Errorf("ProviderHostedMode = %v, want %v", got.ProviderHostedMode, tc.wantProviderHost)+ }+ })+ }+}++// TestBranchcov0723Am_AnonymousBootstrap_NeverPopulatesIdentityFields locks+// the security-relevant invariant of the anonymous builder: no tenant/user+// identity may leak onto the bootstrap payload even when every environment+// feature flag is enabled.+func TestBranchcov0723Am_AnonymousBootstrap_NeverPopulatesIdentityFields(t *testing.T) {+ env := PortalEnvironment{+ SignupPath: "/signup",+ EmailSignInAvailable: true,+ ProviderHostedMode: true,+ }+ got := BuildAnonymousBootstrapDataWithEnvironment(env)++ if got.Authenticated {+ t.Errorf("Authenticated = true on anonymous bootstrap; must always be false")+ }+ if got.Email != "" {+ t.Errorf("Email = %q on anonymous bootstrap; must be empty (no user identity)", got.Email)+ }+ if got.HasSelfHostedCommercial {+ t.Errorf("HasSelfHostedCommercial = true on anonymous bootstrap; must be false")+ }+ if len(got.Accounts) != 0 {+ t.Errorf("len(Accounts) = %d on anonymous bootstrap; must be 0 (no tenant data)", len(got.Accounts))+ }+ for i, acc := range got.Accounts {+ t.Errorf("Accounts[%d] = %+v on anonymous bootstrap; no tenant data permitted", i, acc)+ }+}++// TestBranchcov0723Am_AnonymousBootstrap_ResultIndependentOfEnvAfterReturn+// confirms the returned BootstrapData is decoupled from the caller's+// PortalEnvironment: mutating the input after the call must not change the+// result, and the returned Accounts slice must be a fresh allocation per call+// (not aliased to any package-level shared slice).+func TestBranchcov0723Am_AnonymousBootstrap_ResultIndependentOfEnvAfterReturn(t *testing.T) {+ env := PortalEnvironment{+ SignupPath: "/before",+ EmailSignInAvailable: true,+ ProviderHostedMode: true,+ }+ got := BuildAnonymousBootstrapDataWithEnvironment(env)++ wantSignup := got.SignupPath+ wantEmailSignIn := got.EmailSignInAvailable+ wantProviderHost := got.ProviderHostedMode+ wantAccountsLen := len(got.Accounts)++ // Mutate the input environment after the call.+ env.SignupPath = "/mutated"+ env.EmailSignInAvailable = false+ env.ProviderHostedMode = false++ if got.SignupPath != wantSignup {+ t.Errorf("SignupPath changed after env mutation: got %q, want %q", got.SignupPath, wantSignup)+ }+ if got.EmailSignInAvailable != wantEmailSignIn {+ t.Errorf("EmailSignInAvailable changed after env mutation: got %v, want %v", got.EmailSignInAvailable, wantEmailSignIn)+ }+ if got.ProviderHostedMode != wantProviderHost {+ t.Errorf("ProviderHostedMode changed after env mutation: got %v, want %v", got.ProviderHostedMode, wantProviderHost)+ }+ if len(got.Accounts) != wantAccountsLen {+ t.Errorf("len(Accounts) changed after env mutation: got %d, want %d", len(got.Accounts), wantAccountsLen)+ }++ // Mutate the returned slice header and confirm a second call still returns+ // a fresh empty slice, proving no shared state between calls.+ got.Accounts = append(got.Accounts, BootstrapAccount{ID: "injected"})+ got2 := BuildAnonymousBootstrapDataWithEnvironment(env)+ if len(got2.Accounts) != 0 {+ t.Errorf("second call returned %d accounts; builder must not share slice state, want 0", len(got2.Accounts))+ }+}diff --git a/internal/config/sso_legacy_env_branchcov0723am_test.go b/internal/config/sso_legacy_env_branchcov0723am_test.gonew file mode 100644index 0000000000..53fc232b2b--- /dev/null+++ b/internal/config/sso_legacy_env_branchcov0723am_test.go@@ -0,0 +1,356 @@+package config++import (+ "reflect"+ "strings"+ "testing"+)++// legacyOIDCEnvKeys is the complete set of v5 OIDC_* environment variables read+// by LegacyOIDCConfigFromEnv. setLegacyOIDCEnv baseline-clears every one of them+// so each subtest is fully independent of the ambient process environment.+var legacyOIDCEnvKeys = []string{+ "OIDC_ENABLED",+ "OIDC_ISSUER_URL",+ "OIDC_CLIENT_ID",+ "OIDC_CLIENT_SECRET",+ "OIDC_REDIRECT_URL",+ "OIDC_LOGOUT_URL",+ "OIDC_USERNAME_CLAIM",+ "OIDC_EMAIL_CLAIM",+ "OIDC_GROUPS_CLAIM",+ "OIDC_CA_BUNDLE",+ "OIDC_SCOPES",+ "OIDC_ALLOWED_GROUPS",+ "OIDC_ALLOWED_DOMAINS",+ "OIDC_ALLOWED_EMAILS",+ "OIDC_GROUP_ROLE_MAPPINGS",+}++// setLegacyOIDCEnv resets every legacy OIDC_* variable to empty and then applies+// the given overrides, using t.Setenv so values are restored when the subtest+// ends.+func setLegacyOIDCEnv(t *testing.T, overrides map[string]string) {+ t.Helper()+ for _, key := range legacyOIDCEnvKeys {+ t.Setenv(key, "")+ }+ for key, value := range overrides {+ t.Setenv(key, value)+ }+}++// TestBranchcov0723Am exercises every branch of ApplyLegacyOIDCEnvProvider by+// driving it with concrete (env, SSOConfig, publicURL) inputs and asserting the+// concrete resulting state. Each subtest is independent: it builds its own+// config and scopes its environment via t.Setenv.+func TestBranchcov0723Am(t *testing.T) {+ minEnv := map[string]string{+ "OIDC_ENABLED": "true",+ "OIDC_ISSUER_URL": "https://idp.example.com",+ "OIDC_CLIENT_ID": "client-123",+ }++ t.Run("nil_config_returns_false", func(t *testing.T) {+ got := ApplyLegacyOIDCEnvProvider(nil, "https://app.example.com")+ if got {+ t.Fatalf("ApplyLegacyOIDCEnvProvider(nil, ...) = true, want false")+ }+ })++ t.Run("no_legacy_env_returns_false_and_leaves_config_untouched", func(t *testing.T) {+ setLegacyOIDCEnv(t, nil) // every OIDC_* var empty -> OIDC_ENABLED falsy+ cfg := NewSSOConfig()++ got := ApplyLegacyOIDCEnvProvider(cfg, "https://app.example.com")+ if got {+ t.Fatalf("ApplyLegacyOIDCEnvProvider = true, want false when no legacy env is set")+ }+ if len(cfg.Providers) != 0 {+ t.Errorf("Providers len = %d, want 0 (config must be untouched)", len(cfg.Providers))+ }+ if cfg.DefaultProviderID != "" {+ t.Errorf("DefaultProviderID = %q, want empty (config must be untouched)", cfg.DefaultProviderID)+ }+ })++ t.Run("partially_set_env_no_issuer_returns_false_no_half_write", func(t *testing.T) {+ // OIDC_ENABLED truthy but no IssuerURL/ClientID -> provider cannot be+ // built, so nothing is written onto the config.+ setLegacyOIDCEnv(t, map[string]string{"OIDC_ENABLED": "true"})+ cfg := NewSSOConfig()++ got := ApplyLegacyOIDCEnvProvider(cfg, "https://app.example.com")+ if got {+ t.Fatalf("ApplyLegacyOIDCEnvProvider = true, want false when issuer/client id are missing")+ }+ if len(cfg.Providers) != 0 {+ t.Errorf("Providers len = %d, want 0 (no half-written provider)", len(cfg.Providers))+ }+ if cfg.DefaultProviderID != "" {+ t.Errorf("DefaultProviderID = %q, want empty (no half-write)", cfg.DefaultProviderID)+ }+ })++ t.Run("minimum_required_set_adds_provider_and_writes_every_field", func(t *testing.T) {+ setLegacyOIDCEnv(t, minEnv)+ cfg := NewSSOConfig()++ got := ApplyLegacyOIDCEnvProvider(cfg, "https://app.example.com")+ if !got {+ t.Fatalf("ApplyLegacyOIDCEnvProvider = false, want true")+ }+ if len(cfg.Providers) != 1 {+ t.Fatalf("Providers len = %d, want 1", len(cfg.Providers))+ }+ p := cfg.Providers[0]+ if p.ID != LegacyOIDCProviderID {+ t.Errorf("provider.ID = %q, want %q", p.ID, LegacyOIDCProviderID)+ }+ if p.Name != "Single Sign-On" {+ t.Errorf("provider.Name = %q, want %q", p.Name, "Single Sign-On")+ }+ if p.Type != SSOProviderTypeOIDC {+ t.Errorf("provider.Type = %q, want %q", p.Type, SSOProviderTypeOIDC)+ }+ if !p.Enabled {+ t.Errorf("provider.Enabled = false, want true")+ }+ if p.DisplayName != "Single Sign-On" {+ t.Errorf("provider.DisplayName = %q, want %q", p.DisplayName, "Single Sign-On")+ }+ if !p.RuntimeManaged {+ t.Errorf("provider.RuntimeManaged = false, want true")+ }+ if p.OIDC == nil {+ t.Fatal("provider.OIDC is nil, want populated OIDC config")+ }+ if p.OIDC.IssuerURL != "https://idp.example.com" {+ t.Errorf("OIDC.IssuerURL = %q, want %q", p.OIDC.IssuerURL, "https://idp.example.com")+ }+ if p.OIDC.ClientID != "client-123" {+ t.Errorf("OIDC.ClientID = %q, want %q", p.OIDC.ClientID, "client-123")+ }+ if p.OIDC.ClientSecret != "" {+ t.Errorf("OIDC.ClientSecret = %q, want empty", p.OIDC.ClientSecret)+ }+ wantRedirect := "https://app.example.com" + DefaultOIDCCallbackPath+ if p.OIDC.RedirectURL != wantRedirect {+ t.Errorf("OIDC.RedirectURL = %q, want %q", p.OIDC.RedirectURL, wantRedirect)+ }+ if p.OIDC.LogoutURL != "" {+ t.Errorf("OIDC.LogoutURL = %q, want empty", p.OIDC.LogoutURL)+ }+ if p.OIDC.UsernameClaim != "preferred_username" {+ t.Errorf("OIDC.UsernameClaim = %q, want %q", p.OIDC.UsernameClaim, "preferred_username")+ }+ if p.OIDC.EmailClaim != "email" {+ t.Errorf("OIDC.EmailClaim = %q, want %q", p.OIDC.EmailClaim, "email")+ }+ if p.OIDC.CABundle != "" {+ t.Errorf("OIDC.CABundle = %q, want empty", p.OIDC.CABundle)+ }+ if p.OIDC.ClientSecretSet {+ t.Errorf("OIDC.ClientSecretSet = true, want false (no secret provided)")+ }+ wantScopes := []string{"openid", "profile", "email"}+ if !reflect.DeepEqual(p.OIDC.Scopes, wantScopes) {+ t.Errorf("OIDC.Scopes = %v, want %v", p.OIDC.Scopes, wantScopes)+ }+ if p.OIDC.EnvOverrides == nil {+ t.Error("OIDC.EnvOverrides is nil, want non-nil override map")+ } else if !p.OIDC.EnvOverrides["enabled"] || !p.OIDC.EnvOverrides["issuerUrl"] || !p.OIDC.EnvOverrides["clientId"] {+ t.Errorf("OIDC.EnvOverrides = %v, want enabled/issuerUrl/clientId all true", p.OIDC.EnvOverrides)+ }+ if cfg.DefaultProviderID != LegacyOIDCProviderID {+ t.Errorf("DefaultProviderID = %q, want %q (empty default should be assigned)", cfg.DefaultProviderID, LegacyOIDCProviderID)+ }+ })++ t.Run("empty_public_url_yields_empty_redirect_url", func(t *testing.T) {+ setLegacyOIDCEnv(t, minEnv)+ cfg := NewSSOConfig()++ got := ApplyLegacyOIDCEnvProvider(cfg, "")+ if !got {+ t.Fatalf("ApplyLegacyOIDCEnvProvider = false, want true")+ }+ p := cfg.Providers[0]+ if p.OIDC == nil || p.OIDC.RedirectURL != "" {+ t.Errorf("derived RedirectURL = %q, want empty when publicURL is empty", p.OIDC.RedirectURL)+ }+ })++ t.Run("trailing_slash_public_url_produces_no_double_slash", func(t *testing.T) {+ setLegacyOIDCEnv(t, minEnv)+ cfg := NewSSOConfig()++ got := ApplyLegacyOIDCEnvProvider(cfg, "https://app.example.com/")+ if !got {+ t.Fatalf("ApplyLegacyOIDCEnvProvider = false, want true")+ }+ p := cfg.Providers[0]+ wantRedirect := "https://app.example.com" + DefaultOIDCCallbackPath+ if p.OIDC.RedirectURL != wantRedirect {+ t.Errorf("RedirectURL = %q, want %q (no double slash)", p.OIDC.RedirectURL, wantRedirect)+ }+ if strings.Contains(p.OIDC.RedirectURL, "//api") {+ t.Errorf("RedirectURL %q contains a double slash before the callback path", p.OIDC.RedirectURL)+ }+ })++ t.Run("client_secret_propagates_and_sets_secret_flag", func(t *testing.T) {+ setLegacyOIDCEnv(t, mergeEnv(minEnv, map[string]string{"OIDC_CLIENT_SECRET": "s3cr3t"}))+ cfg := NewSSOConfig()++ got := ApplyLegacyOIDCEnvProvider(cfg, "https://app.example.com")+ if !got {+ t.Fatalf("ApplyLegacyOIDCEnvProvider = false, want true")+ }+ p := cfg.Providers[0]+ if p.OIDC.ClientSecret != "s3cr3t" {+ t.Errorf("OIDC.ClientSecret = %q, want %q", p.OIDC.ClientSecret, "s3cr3t")+ }+ if !p.OIDC.ClientSecretSet {+ t.Errorf("OIDC.ClientSecretSet = false, want true when a secret is provided")+ }+ if p.OIDC.EnvOverrides == nil || !p.OIDC.EnvOverrides["clientSecret"] {+ t.Errorf("OIDC.EnvOverrides[clientSecret] not marked true, want true")+ }+ })++ t.Run("dangling_default_id_reassigned_to_legacy_provider", func(t *testing.T) {+ setLegacyOIDCEnv(t, minEnv)+ cfg := NewSSOConfig()+ cfg.DefaultProviderID = "does-not-exist" // points at no real provider++ got := ApplyLegacyOIDCEnvProvider(cfg, "https://app.example.com")+ if !got {+ t.Fatalf("ApplyLegacyOIDCEnvProvider = false, want true")+ }+ if cfg.DefaultProviderID != LegacyOIDCProviderID {+ t.Errorf("DefaultProviderID = %q, want %q (dangling default should be reassigned)", cfg.DefaultProviderID, LegacyOIDCProviderID)+ }+ if len(cfg.Providers) != 1 {+ t.Errorf("Providers len = %d, want 1", len(cfg.Providers))+ }+ })++ t.Run("existing_valid_default_id_is_preserved", func(t *testing.T) {+ setLegacyOIDCEnv(t, minEnv)+ cfg := NewSSOConfig()+ if err := cfg.AddProvider(SSOProvider{ID: "other", Name: "Other", Type: SSOProviderTypeOIDC, Enabled: true}); err != nil {+ t.Fatalf("AddProvider failed: %v", err)+ }+ cfg.DefaultProviderID = "other"++ got := ApplyLegacyOIDCEnvProvider(cfg, "https://app.example.com")+ if !got {+ t.Fatalf("ApplyLegacyOIDCEnvProvider = false, want true")+ }+ if cfg.DefaultProviderID != "other" {+ t.Errorf("DefaultProviderID = %q, want %q (valid existing default must be preserved)", cfg.DefaultProviderID, "other")+ }+ if len(cfg.Providers) != 2 {+ t.Errorf("Providers len = %d, want 2", len(cfg.Providers))+ }+ })++ t.Run("existing_runtime_managed_provider_is_overwritten", func(t *testing.T) {+ setLegacyOIDCEnv(t, minEnv)+ cfg := &SSOConfig{+ Providers: []SSOProvider{+ {+ ID: LegacyOIDCProviderID,+ Name: "Old Runtime",+ Type: SSOProviderTypeOIDC,+ Enabled: true,+ RuntimeManaged: true,+ OIDC: &OIDCProviderConfig{+ IssuerURL: "https://old.example.com",+ ClientID: "old-client",+ },+ },+ },+ DefaultProviderID: LegacyOIDCProviderID,+ }++ got := ApplyLegacyOIDCEnvProvider(cfg, "https://app.example.com")+ if got {+ t.Fatalf("ApplyLegacyOIDCEnvProvider = true, want false when a provider with the same ID already exists")+ }+ if len(cfg.Providers) != 1 {+ t.Fatalf("Providers len = %d, want 1 (existing should be replaced in place, not appended)", len(cfg.Providers))+ }+ p := cfg.Providers[0]+ if p.Name != "Single Sign-On" {+ t.Errorf("provider.Name = %q, want %q (runtime-managed provider should be overwritten)", p.Name, "Single Sign-On")+ }+ if p.OIDC == nil || p.OIDC.IssuerURL != "https://idp.example.com" {+ got := "<nil>"+ if p.OIDC != nil {+ got = p.OIDC.IssuerURL+ }+ t.Errorf("provider.OIDC.IssuerURL = %q, want %q (runtime-managed provider should be overwritten)", got, "https://idp.example.com")+ }+ if p.OIDC == nil || p.OIDC.ClientID != "client-123" {+ t.Errorf("provider.OIDC.ClientID not overwritten, want %q", "client-123")+ }+ if !p.RuntimeManaged {+ t.Errorf("provider.RuntimeManaged = false, want true (overwrite must keep runtime flag)")+ }+ })++ t.Run("existing_persisted_provider_is_left_untouched", func(t *testing.T) {+ setLegacyOIDCEnv(t, minEnv)+ cfg := &SSOConfig{+ Providers: []SSOProvider{+ {+ ID: LegacyOIDCProviderID,+ Name: "Persisted",+ Type: SSOProviderTypeOIDC,+ Enabled: true,+ RuntimeManaged: false, // persisted provider+ OIDC: &OIDCProviderConfig{+ IssuerURL: "https://persisted.example.com",+ ClientID: "persisted-client",+ },+ },+ },+ DefaultProviderID: LegacyOIDCProviderID,+ }++ got := ApplyLegacyOIDCEnvProvider(cfg, "https://app.example.com")+ if got {+ t.Fatalf("ApplyLegacyOIDCEnvProvider = true, want false when a persisted provider with the same ID already exists")+ }+ if len(cfg.Providers) != 1 {+ t.Fatalf("Providers len = %d, want 1", len(cfg.Providers))+ }+ p := cfg.Providers[0]+ if p.Name != "Persisted" {+ t.Errorf("provider.Name = %q, want %q (persisted provider must not be overwritten by legacy env)", p.Name, "Persisted")+ }+ if p.OIDC == nil || p.OIDC.IssuerURL != "https://persisted.example.com" {+ t.Errorf("provider.OIDC.IssuerURL changed, want %q left untouched", "https://persisted.example.com")+ }+ if p.OIDC == nil || p.OIDC.ClientID != "persisted-client" {+ t.Errorf("provider.OIDC.ClientID changed, want %q left untouched", "persisted-client")+ }+ if p.RuntimeManaged {+ t.Errorf("provider.RuntimeManaged = true, want false (persisted provider must not gain runtime flag)")+ }+ })+}++// mergeEnv returns a new map combining base with overrides (overrides win).+func mergeEnv(base, overrides map[string]string) map[string]string {+ merged := make(map[string]string, len(base)+len(overrides))+ for k, v := range base {+ merged[k] = v+ }+ for k, v := range overrides {+ merged[k] = v+ }+ return merged+}diff --git a/internal/dockeragent/update_all_decode_branchcov0723am_test.go b/internal/dockeragent/update_all_decode_branchcov0723am_test.gonew file mode 100644index 0000000000..523ae94372--- /dev/null+++ b/internal/dockeragent/update_all_decode_branchcov0723am_test.go@@ -0,0 +1,247 @@+package dockeragent++import (+ "errors"+ "reflect"+ "strings"+ "testing"++ "github.com/moby/moby/client"+)++func TestBranchcov0723AmDecodeUpdateAllPayload(t *testing.T) {+ t.Run("nil map yields missing-containerIds error and zero-value struct", func(t *testing.T) {+ got, err := decodeUpdateAllPayload(nil)+ if err == nil {+ t.Fatal("expected error for nil payload")+ }+ if !strings.Contains(err.Error(), "missing containerIds in payload") {+ t.Fatalf("unexpected error: %v", err)+ }+ if got.ContainerIDs != nil {+ t.Fatalf("expected zero-value payload, got %+v", got)+ }+ })++ t.Run("empty map yields missing-containerIds error", func(t *testing.T) {+ got, err := decodeUpdateAllPayload(map[string]any{})+ if err == nil {+ t.Fatal("expected error for empty payload")+ }+ if !strings.Contains(err.Error(), "missing containerIds in payload") {+ t.Fatalf("unexpected error: %v", err)+ }+ if got.ContainerIDs != nil {+ t.Fatalf("expected zero-value payload, got %+v", got)+ }+ })++ t.Run("absent field versus empty slice not distinguished at error level", func(t *testing.T) {+ // The ERROR is identical for an absent containerIds field and an+ // explicitly empty containerIds slice: the source applies no+ // defaulting and reports "missing containerIds" for both. The+ // returned structs do differ (nil vs a non-nil empty slice), which+ // simply reflects what encoding/json left on the field.+ absent, errAbsent := decodeUpdateAllPayload(map[string]any{"other": "x"})+ if errAbsent == nil {+ t.Fatal("expected error when containerIds is absent")+ }+ if !strings.Contains(errAbsent.Error(), "missing containerIds in payload") {+ t.Fatalf("unexpected error for absent field: %v", errAbsent)+ }+ if absent.ContainerIDs != nil {+ t.Fatalf("absent field should leave ContainerIDs nil, got %+v", absent.ContainerIDs)+ }++ emptySlice, errEmpty := decodeUpdateAllPayload(map[string]any{"containerIds": []any{}})+ if errEmpty == nil {+ t.Fatal("expected error for empty containerIds slice")+ }+ if errEmpty.Error() != errAbsent.Error() {+ t.Fatalf("expected absent and empty-slice to yield identical errors, got %q vs %q", errEmpty.Error(), errAbsent.Error())+ }+ if emptySlice.ContainerIDs == nil || len(emptySlice.ContainerIDs) != 0 {+ t.Fatalf("empty-slice field should yield non-nil empty ContainerIDs, got %+v", emptySlice.ContainerIDs)+ }+ })++ t.Run("entries normalising to empty yield no-valid-IDs error and raw struct", func(t *testing.T) {+ // Every entry is empty or whitespace-only after trimming, so the+ // normalised slice ends up empty: the function must report a distinct+ // error from the missing-field case. On this error path the returned+ // struct still carries the RAW decoded slice (the `= normalized`+ // assignment only runs on success).+ raw := []any{"", " ", "\t"}+ got, err := decodeUpdateAllPayload(map[string]any{"containerIds": raw})+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(err.Error(), "containerIds contained no valid container IDs") {+ t.Fatalf("unexpected error: %v", err)+ }+ if !reflect.DeepEqual(got.ContainerIDs, []string{"", " ", "\t"}) {+ t.Fatalf("expected raw un-normalised ContainerIDs on error, got %+v", got.ContainerIDs)+ }+ })++ t.Run("marshal error is wrapped", func(t *testing.T) {+ marshalErr := errors.New("boom")+ swap(t, &jsonMarshalFn, func(any) ([]byte, error) {+ return nil, marshalErr+ })++ got, err := decodeUpdateAllPayload(map[string]any{"containerIds": []any{"a"}})+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(err.Error(), "marshal update_all command payload") {+ t.Fatalf("expected marshal wrap, got: %v", err)+ }+ if !errors.Is(err, marshalErr) {+ t.Fatalf("expected wrapped marshal error, got: %v", err)+ }+ if got.ContainerIDs != nil {+ t.Fatalf("expected zero-value payload, got %+v", got)+ }+ })++ t.Run("wrong field type yields decode error", func(t *testing.T) {+ got, err := decodeUpdateAllPayload(map[string]any{"containerIds": 123})+ if err == nil {+ t.Fatal("expected error")+ }+ if !strings.Contains(err.Error(), "decode update_all command payload") {+ t.Fatalf("expected decode wrap, got: %v", err)+ }+ if !strings.Contains(err.Error(), "cannot unmarshal") {+ t.Fatalf("expected json unmarshal error, got: %v", err)+ }+ if got.ContainerIDs != nil {+ t.Fatalf("expected zero-value payload, got %+v", got)+ }+ })++ t.Run("valid single id", func(t *testing.T) {+ got, err := decodeUpdateAllPayload(map[string]any{"containerIds": []any{"a"}})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !reflect.DeepEqual(got.ContainerIDs, []string{"a"}) {+ t.Fatalf("unexpected payload: %+v", got)+ }+ })++ t.Run("multiple ids preserve input order", func(t *testing.T) {+ got, err := decodeUpdateAllPayload(map[string]any{"containerIds": []any{"b", "a"}})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !reflect.DeepEqual(got.ContainerIDs, []string{"b", "a"}) {+ t.Fatalf("unexpected payload: %+v", got)+ }+ })++ t.Run("surrounding whitespace is trimmed", func(t *testing.T) {+ got, err := decodeUpdateAllPayload(map[string]any{"containerIds": []any{" a "}})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !reflect.DeepEqual(got.ContainerIDs, []string{"a"}) {+ t.Fatalf("unexpected payload: %+v", got)+ }+ })++ t.Run("exact duplicates are deduped", func(t *testing.T) {+ got, err := decodeUpdateAllPayload(map[string]any{"containerIds": []any{"a", "a"}})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !reflect.DeepEqual(got.ContainerIDs, []string{"a"}) {+ t.Fatalf("unexpected payload: %+v", got)+ }+ })++ t.Run("duplicates after trim are deduped", func(t *testing.T) {+ // Verifies the source orders trim-before-dedupe: " a " collapses to+ // "a" and is then deduped against the literal "a".+ got, err := decodeUpdateAllPayload(map[string]any{"containerIds": []any{" a ", "a"}})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !reflect.DeepEqual(got.ContainerIDs, []string{"a"}) {+ t.Fatalf("unexpected payload: %+v", got)+ }+ })+}++func TestBranchcov0723AmDockerFiltersToClientFilters(t *testing.T) {+ t.Run("zero value returns nil", func(t *testing.T) {+ // A zero-value (nil) dockerFilters maps to a nil client.Filters, not+ // to an initialised empty map.+ var f dockerFilters+ if got := f.toClientFilters(); got != nil {+ t.Fatalf("expected nil Filters for zero-value dockerFilters, got %+v", got)+ }+ })++ t.Run("single filter single value", func(t *testing.T) {+ f := newDockerFilters()+ f.Add("status", "running")+ got := f.toClientFilters()+ want := client.Filters{"status": {"running": true}}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("got %+v, want %+v", got, want)+ }+ })++ t.Run("single key multiple values", func(t *testing.T) {+ f := newDockerFilters()+ f.Add("label", "a")+ f.Add("label", "b")+ got := f.toClientFilters()+ want := client.Filters{"label": {"a": true, "b": true}}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("got %+v, want %+v", got, want)+ }+ })++ t.Run("multiple keys", func(t *testing.T) {+ f := newDockerFilters()+ f.Add("status", "running")+ f.Add("name", "web")+ got := f.toClientFilters()+ want := client.Filters{+ "name": {"web": true},+ "status": {"running": true},+ }+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("got %+v, want %+v", got, want)+ }+ })++ t.Run("preserves false value", func(t *testing.T) {+ // Add() only ever writes true; constructing a false value directly+ // confirms toClientFilters copies each bool faithfully rather than+ // coercing it.+ f := dockerFilters{"disabled": {"v": false}}+ got := f.toClientFilters()+ want := client.Filters{"disabled": {"v": false}}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("got %+v, want %+v", got, want)+ }+ })++ t.Run("result is a deep copy", func(t *testing.T) {+ f := newDockerFilters()+ f.Add("status", "running")+ got := f.toClientFilters()++ got["status"]["running"] = false+ if got["status"]["running"] != false {+ t.Fatal("expected mutation of result to take effect on the result")+ }+ if f["status"]["running"] != true {+ t.Fatalf("expected original dockerFilters unchanged after mutating result, got %v", f["status"]["running"])+ }+ })+}diff --git a/internal/kubernetesagent/agent_role_branchcov0723am_test.go b/internal/kubernetesagent/agent_role_branchcov0723am_test.gonew file mode 100644index 0000000000..ded1396691--- /dev/null+++ b/internal/kubernetesagent/agent_role_branchcov0723am_test.go@@ -0,0 +1,568 @@+package kubernetesagent++import (+ "testing"+ "time"++ appsv1 "k8s.io/api/apps/v1"+ batchv1 "k8s.io/api/batch/v1"+ corev1 "k8s.io/api/core/v1"+ discoveryv1 "k8s.io/api/discovery/v1"+ networkingv1 "k8s.io/api/networking/v1"+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"+)++// TestBranchcov0723Am_KubernetesTargetRole covers every arm of+// kubernetesTargetRole. The source implementation only inspects the+// TargetConfig.Authoritative boolean (there is no Role string field, so+// case/whitespace/unknown-role branches described in some specs simply do not+// exist in the code).+func TestBranchcov0723Am_KubernetesTargetRole(t *testing.T) {+ t.Run("zero_value_returns_observer", func(t *testing.T) {+ // Zero-value TargetConfig has Authoritative == false.+ if got := kubernetesTargetRole(TargetConfig{}); got != "observer" {+ t.Fatalf("kubernetesTargetRole(zero) = %q, want %q", got, "observer")+ }+ })++ t.Run("authoritative_returns_primary", func(t *testing.T) {+ cfg := TargetConfig{Authoritative: true}+ if got := kubernetesTargetRole(cfg); got != "primary" {+ t.Fatalf("kubernetesTargetRole(Authoritative) = %q, want %q", got, "primary")+ }+ })+}++func TestBranchcov0723Am_TimePtrFromMeta(t *testing.T) {+ t.Run("zero_time_returns_nil", func(t *testing.T) {+ if got := timePtrFromMeta(metav1.Time{}); got != nil {+ t.Fatalf("timePtrFromMeta(zero) = %v, want nil", *got)+ }+ })++ t.Run("non_zero_time_returns_pointer_copy", func(t *testing.T) {+ ts := time.Date(2024, 1, 2, 3, 4, 5, 0, time.UTC)+ got := timePtrFromMeta(metav1.Time{Time: ts})+ if got == nil {+ t.Fatal("expected non-nil pointer")+ }+ if !got.Equal(ts) {+ t.Fatalf("timePtrFromMeta = %v, want %v", *got, ts)+ }+ // Returned pointer must be a copy, not alias the input's field.+ mt := metav1.Time{Time: ts}+ p := timePtrFromMeta(mt)+ mt.Time = mt.Time.Add(time.Hour)+ if !p.Equal(ts) {+ t.Fatalf("timePtrFromMeta aliased input: now %v, want %v", *p, ts)+ }+ })+}++func TestBranchcov0723Am_TimePtrFromMicro(t *testing.T) {+ t.Run("zero_time_returns_nil", func(t *testing.T) {+ if got := timePtrFromMicro(metav1.MicroTime{}); got != nil {+ t.Fatalf("timePtrFromMicro(zero) = %v, want nil", *got)+ }+ })++ t.Run("non_zero_time_returns_pointer_copy", func(t *testing.T) {+ ts := time.Date(2024, 5, 6, 7, 8, 9, 123456, time.UTC)+ got := timePtrFromMicro(metav1.MicroTime{Time: ts})+ if got == nil {+ t.Fatal("expected non-nil pointer")+ }+ if !got.Equal(ts) {+ t.Fatalf("timePtrFromMicro = %v, want %v", *got, ts)+ }+ })+}++func TestBranchcov0723Am_TimePtrFromMetaPtr(t *testing.T) {+ t.Run("nil_returns_nil", func(t *testing.T) {+ if got := timePtrFromMetaPtr(nil); got != nil {+ t.Fatalf("timePtrFromMetaPtr(nil) = %v, want nil", *got)+ }+ })++ t.Run("nil_safe_zero_time_returns_nil", func(t *testing.T) {+ mt := metav1.Time{}+ if got := timePtrFromMetaPtr(&mt); got != nil {+ t.Fatalf("timePtrFromMetaPtr(&zero) = %v, want nil", *got)+ }+ })++ t.Run("non_zero_time_returns_pointer", func(t *testing.T) {+ ts := time.Date(2024, 1, 2, 3, 4, 5, 0, time.UTC)+ mt := metav1.Time{Time: ts}+ got := timePtrFromMetaPtr(&mt)+ if got == nil {+ t.Fatal("expected non-nil pointer")+ }+ if !got.Equal(ts) {+ t.Fatalf("timePtrFromMetaPtr = %v, want %v", *got, ts)+ }+ })+}++func TestBranchcov0723Am_AccessModes(t *testing.T) {+ t.Run("empty_returns_nil", func(t *testing.T) {+ if got := accessModes(nil); got != nil {+ t.Fatalf("accessModes(nil) = %v, want nil", got)+ }+ if got := accessModes([]corev1.PersistentVolumeAccessMode{}); got != nil {+ t.Fatalf("accessModes([]) = %v, want nil", got)+ }+ })++ t.Run("whitespace_only_entries_filtered", func(t *testing.T) {+ got := accessModes([]corev1.PersistentVolumeAccessMode{" ", ""})+ if len(got) != 0 {+ t.Fatalf("accessModes(whitespace) = %v, want empty", got)+ }+ })++ t.Run("modes_returned_trimmed", func(t *testing.T) {+ got := accessModes([]corev1.PersistentVolumeAccessMode{+ corev1.ReadWriteOnce,+ corev1.ReadOnlyMany,+ corev1.ReadWriteMany,+ })+ want := []string{+ string(corev1.ReadWriteOnce),+ string(corev1.ReadOnlyMany),+ string(corev1.ReadWriteMany),+ }+ if len(got) != len(want) {+ t.Fatalf("accessModes len = %d, want %d (%v)", len(got), len(want), got)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("accessModes[%d] = %q, want %q", i, got[i], want[i])+ }+ }+ })+}++func TestBranchcov0723Am_StorageClassNamePtr(t *testing.T) {+ t.Run("nil_returns_empty", func(t *testing.T) {+ if got := storageClassNamePtr(nil); got != "" {+ t.Fatalf("storageClassNamePtr(nil) = %q, want empty", got)+ }+ })++ t.Run("value_trimmed", func(t *testing.T) {+ name := " fast-ssd "+ if got := storageClassNamePtr(&name); got != "fast-ssd" {+ t.Fatalf("storageClassNamePtr = %q, want %q", got, "fast-ssd")+ }+ })++ t.Run("plain_value_passes_through", func(t *testing.T) {+ name := "standard"+ if got := storageClassNamePtr(&name); got != "standard" {+ t.Fatalf("storageClassNamePtr = %q, want %q", got, "standard")+ }+ })+}++func TestBranchcov0723Am_BoolPtrCopy(t *testing.T) {+ t.Run("nil_returns_nil", func(t *testing.T) {+ if got := boolPtrCopy(nil); got != nil {+ t.Fatalf("boolPtrCopy(nil) = %v, want nil", *got)+ }+ })++ t.Run("true_copied", func(t *testing.T) {+ v := true+ got := boolPtrCopy(&v)+ if got == nil || *got != true {+ t.Fatalf("boolPtrCopy(true) = %v, want true", got)+ }+ // Mutating input must not affect the returned copy.+ v = false+ if *got != true {+ t.Fatal("boolPtrCopy aliased input value")+ }+ })++ t.Run("false_copied", func(t *testing.T) {+ v := false+ got := boolPtrCopy(&v)+ if got == nil || *got != false {+ t.Fatalf("boolPtrCopy(false) = %v, want false", got)+ }+ })+}++func TestBranchcov0723Am_StringPtrValue(t *testing.T) {+ t.Run("nil_returns_empty", func(t *testing.T) {+ if got := stringPtrValue(nil); got != "" {+ t.Fatalf("stringPtrValue(nil) = %q, want empty", got)+ }+ })++ t.Run("value_trimmed", func(t *testing.T) {+ v := " hello "+ if got := stringPtrValue(&v); got != "hello" {+ t.Fatalf("stringPtrValue = %q, want %q", got, "hello")+ }+ })+}++func TestBranchcov0723Am_SortedStringKeys(t *testing.T) {+ t.Run("empty_returns_nil", func(t *testing.T) {+ if got := sortedStringKeys[int](nil); got != nil {+ t.Fatalf("sortedStringKeys(nil) = %v, want nil", got)+ }+ if got := sortedStringKeys[int](map[string]int{}); got != nil {+ t.Fatalf("sortedStringKeys(empty) = %v, want nil", got)+ }+ })++ t.Run("whitespace_only_keys_filtered", func(t *testing.T) {+ got := sortedStringKeys[int](map[string]int{" ": 1, "": 2})+ if len(got) != 0 {+ t.Fatalf("sortedStringKeys(whitespace) = %v, want empty", got)+ }+ })++ t.Run("keys_sorted_and_trimmed", func(t *testing.T) {+ got := sortedStringKeys[int](map[string]int{+ " banana ": 1,+ "apple": 2,+ "cherry": 3,+ })+ want := []string{"apple", "banana", "cherry"}+ if len(got) != len(want) {+ t.Fatalf("sortedStringKeys len = %d, want %d (%v)", len(got), len(want), got)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("sortedStringKeys[%d] = %q, want %q", i, got[i], want[i])+ }+ }+ })+}++func TestBranchcov0723Am_DesiredReplicasAndCompletions(t *testing.T) {+ t.Run("statefulset_nil_replicas_zero", func(t *testing.T) {+ if got := statefulSetDesiredReplicas(appsv1.StatefulSet{}); got != 0 {+ t.Fatalf("statefulSetDesiredReplicas(nil) = %d, want 0", got)+ }+ })++ t.Run("statefulset_replicas_value", func(t *testing.T) {+ replicas := int32(5)+ ss := appsv1.StatefulSet{Spec: appsv1.StatefulSetSpec{Replicas: &replicas}}+ if got := statefulSetDesiredReplicas(ss); got != 5 {+ t.Fatalf("statefulSetDesiredReplicas = %d, want 5", got)+ }+ })++ t.Run("replicaset_nil_replicas_zero", func(t *testing.T) {+ if got := replicaSetDesiredReplicas(appsv1.ReplicaSet{}); got != 0 {+ t.Fatalf("replicaSetDesiredReplicas(nil) = %d, want 0", got)+ }+ })++ t.Run("replicaset_replicas_value", func(t *testing.T) {+ replicas := int32(7)+ rs := appsv1.ReplicaSet{Spec: appsv1.ReplicaSetSpec{Replicas: &replicas}}+ if got := replicaSetDesiredReplicas(rs); got != 7 {+ t.Fatalf("replicaSetDesiredReplicas = %d, want 7", got)+ }+ })++ t.Run("job_nil_completions_zero", func(t *testing.T) {+ if got := jobDesiredCompletions(batchv1.Job{}); got != 0 {+ t.Fatalf("jobDesiredCompletions(nil) = %d, want 0", got)+ }+ })++ t.Run("job_completions_value", func(t *testing.T) {+ c := int32(3)+ j := batchv1.Job{Spec: batchv1.JobSpec{Completions: &c}}+ if got := jobDesiredCompletions(j); got != 3 {+ t.Fatalf("jobDesiredCompletions = %d, want 3", got)+ }+ })+}++func TestBranchcov0723Am_CronJobSuspended(t *testing.T) {+ t.Run("nil_returns_false", func(t *testing.T) {+ if got := cronJobSuspended(batchv1.CronJob{}); got {+ t.Fatal("cronJobSuspended(nil) = true, want false")+ }+ })++ t.Run("explicit_false_returns_false", func(t *testing.T) {+ f := false+ if got := cronJobSuspended(batchv1.CronJob{Spec: batchv1.CronJobSpec{Suspend: &f}}); got {+ t.Fatal("cronJobSuspended(false) = true, want false")+ }+ })++ t.Run("explicit_true_returns_true", func(t *testing.T) {+ tr := true+ if got := cronJobSuspended(batchv1.CronJob{Spec: batchv1.CronJobSpec{Suspend: &tr}}); !got {+ t.Fatal("cronJobSuspended(true) = false, want true")+ }+ })+}++func TestBranchcov0723Am_IngressClassName(t *testing.T) {+ t.Run("nil_returns_empty", func(t *testing.T) {+ if got := ingressClassName(networkingv1.Ingress{}); got != "" {+ t.Fatalf("ingressClassName(nil) = %q, want empty", got)+ }+ })++ t.Run("value_trimmed", func(t *testing.T) {+ name := " nginx "+ ing := networkingv1.Ingress{Spec: networkingv1.IngressSpec{IngressClassName: &name}}+ if got := ingressClassName(ing); got != "nginx" {+ t.Fatalf("ingressClassName = %q, want %q", got, "nginx")+ }+ })+}++func TestBranchcov0723Am_IngressHosts(t *testing.T) {+ t.Run("empty_rules_returns_empty_nonnil", func(t *testing.T) {+ got := ingressHosts(networkingv1.Ingress{})+ if got == nil {+ t.Fatalf("ingressHosts(empty) = nil, want a non-nil empty slice")+ }+ if len(got) != 0 {+ t.Fatalf("ingressHosts(empty) = %v, want empty", got)+ }+ })++ t.Run("blank_hosts_filtered", func(t *testing.T) {+ ing := networkingv1.Ingress{Spec: networkingv1.IngressSpec{Rules: []networkingv1.IngressRule{+ {Host: " "},+ {Host: ""},+ }}}+ got := ingressHosts(ing)+ if len(got) != 0 {+ t.Fatalf("ingressHosts(blank) = %v, want empty", got)+ }+ })++ t.Run("hosts_trimmed_deduped_order_preserved", func(t *testing.T) {+ ing := networkingv1.Ingress{Spec: networkingv1.IngressSpec{Rules: []networkingv1.IngressRule{+ {Host: " b.example.com "},+ {Host: "a.example.com"},+ {Host: "b.example.com"}, // duplicate (after trim)+ {Host: "c.example.com"},+ }}}+ got := ingressHosts(ing)+ want := []string{"b.example.com", "a.example.com", "c.example.com"}+ if len(got) != len(want) {+ t.Fatalf("ingressHosts len = %d, want %d (%v)", len(got), len(want), got)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("ingressHosts[%d] = %q, want %q", i, got[i], want[i])+ }+ }+ })+}++func TestBranchcov0723Am_IngressAddresses(t *testing.T) {+ t.Run("empty_status_returns_empty_nonnil", func(t *testing.T) {+ got := ingressAddresses(networkingv1.Ingress{})+ if len(got) != 0 {+ t.Fatalf("ingressAddresses(empty) = %v, want empty", got)+ }+ })++ t.Run("ips_and_hostnames_deduped_trimmed", func(t *testing.T) {+ ing := networkingv1.Ingress{Status: networkingv1.IngressStatus{LoadBalancer: networkingv1.IngressLoadBalancerStatus{+ Ingress: []networkingv1.IngressLoadBalancerIngress{+ {IP: " 10.0.0.1 ", Hostname: ""},+ {IP: "10.0.0.1"}, // duplicate IP after trim+ {Hostname: " lb.example.com "},+ {IP: "10.0.0.2"},+ },+ }}}+ got := ingressAddresses(ing)+ want := []string{"10.0.0.1", "lb.example.com", "10.0.0.2"}+ if len(got) != len(want) {+ t.Fatalf("ingressAddresses len = %d, want %d (%v)", len(got), len(want), got)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("ingressAddresses[%d] = %q, want %q", i, got[i], want[i])+ }+ }+ })+}++func TestBranchcov0723Am_NetworkPolicyTypes(t *testing.T) {+ t.Run("empty_returns_nil", func(t *testing.T) {+ if got := networkPolicyTypes(networkingv1.NetworkPolicy{}); got != nil {+ t.Fatalf("networkPolicyTypes(empty) = %v, want nil", got)+ }+ })++ t.Run("types_returned_trimmed_blank_filtered", func(t *testing.T) {+ policy := networkingv1.NetworkPolicy{Spec: networkingv1.NetworkPolicySpec{+ PolicyTypes: []networkingv1.PolicyType{+ networkingv1.PolicyTypeIngress,+ networkingv1.PolicyTypeEgress,+ networkingv1.PolicyType(" "),+ },+ }}+ got := networkPolicyTypes(policy)+ want := []string{+ string(networkingv1.PolicyTypeIngress),+ string(networkingv1.PolicyTypeEgress),+ }+ if len(got) != len(want) {+ t.Fatalf("networkPolicyTypes len = %d, want %d (%v)", len(got), len(want), got)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("networkPolicyTypes[%d] = %q, want %q", i, got[i], want[i])+ }+ }+ })+}++func TestBranchcov0723Am_EndpointSliceServiceName(t *testing.T) {+ t.Run("nil_labels_returns_empty", func(t *testing.T) {+ if got := endpointSliceServiceName(discoveryv1.EndpointSlice{}); got != "" {+ t.Fatalf("endpointSliceServiceName(nil labels) = %q, want empty", got)+ }+ })++ t.Run("missing_label_returns_empty", func(t *testing.T) {+ slice := discoveryv1.EndpointSlice{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{"other": "value"}}}+ if got := endpointSliceServiceName(slice); got != "" {+ t.Fatalf("endpointSliceServiceName(missing) = %q, want empty", got)+ }+ })++ t.Run("label_value_trimmed", func(t *testing.T) {+ slice := discoveryv1.EndpointSlice{ObjectMeta: metav1.ObjectMeta{Labels: map[string]string{+ discoveryv1.LabelServiceName: " my-service ",+ }}}+ if got := endpointSliceServiceName(slice); got != "my-service" {+ t.Fatalf("endpointSliceServiceName = %q, want %q", got, "my-service")+ }+ })+}++func TestBranchcov0723Am_EndpointSlicePorts(t *testing.T) {+ t.Run("empty_returns_nil", func(t *testing.T) {+ if got := endpointSlicePorts(discoveryv1.EndpointSlice{}); got != nil {+ t.Fatalf("endpointSlicePorts(empty) = %v, want nil", got)+ }+ })++ t.Run("nil_port_and_protocol_default_to_zero_and_empty", func(t *testing.T) {+ name := "http"+ appProto := " L7 "+ slice := discoveryv1.EndpointSlice{Ports: []discoveryv1.EndpointPort{+ {Name: &name, AppProtocol: &appProto},+ }}+ got := endpointSlicePorts(slice)+ if len(got) != 1 {+ t.Fatalf("endpointSlicePorts len = %d, want 1", len(got))+ }+ if got[0].Port != 0 {+ t.Fatalf("Port = %d, want 0", got[0].Port)+ }+ if got[0].Protocol != "" {+ t.Fatalf("Protocol = %q, want empty", got[0].Protocol)+ }+ if got[0].Name != "http" {+ t.Fatalf("Name = %q, want http", got[0].Name)+ }+ if got[0].AppProtocol != "L7" {+ t.Fatalf("AppProtocol = %q, want L7", got[0].AppProtocol)+ }+ })++ t.Run("set_port_and_protocol_returned", func(t *testing.T) {+ port := int32(443)+ proto := corev1.ProtocolTCP+ name := "https"+ slice := discoveryv1.EndpointSlice{Ports: []discoveryv1.EndpointPort{+ {Port: &port, Protocol: &proto, Name: &name},+ }}+ got := endpointSlicePorts(slice)+ if len(got) != 1 {+ t.Fatalf("endpointSlicePorts len = %d, want 1", len(got))+ }+ if got[0].Port != 443 {+ t.Fatalf("Port = %d, want 443", got[0].Port)+ }+ if got[0].Protocol != string(corev1.ProtocolTCP) {+ t.Fatalf("Protocol = %q, want %q", got[0].Protocol, corev1.ProtocolTCP)+ }+ if got[0].Name != "https" {+ t.Fatalf("Name = %q, want https", got[0].Name)+ }+ })+}++func TestBranchcov0723Am_EndpointSliceReadyCount(t *testing.T) {+ t.Run("empty_endpoints_zero", func(t *testing.T) {+ if got := endpointSliceReadyCount(discoveryv1.EndpointSlice{}); got != 0 {+ t.Fatalf("endpointSliceReadyCount(empty) = %d, want 0", got)+ }+ })++ t.Run("nil_ready_counts_as_ready", func(t *testing.T) {+ slice := discoveryv1.EndpointSlice{Endpoints: []discoveryv1.Endpoint{+ {Conditions: discoveryv1.EndpointConditions{Ready: nil}},+ {Conditions: discoveryv1.EndpointConditions{Ready: nil}},+ }}+ if got := endpointSliceReadyCount(slice); got != 2 {+ t.Fatalf("endpointSliceReadyCount(nil) = %d, want 2", got)+ }+ })++ t.Run("mixed_ready_states_counted", func(t *testing.T) {+ tr := true+ fa := false+ slice := discoveryv1.EndpointSlice{Endpoints: []discoveryv1.Endpoint{+ {Conditions: discoveryv1.EndpointConditions{Ready: &tr}},+ {Conditions: discoveryv1.EndpointConditions{Ready: &fa}},+ {Conditions: discoveryv1.EndpointConditions{Ready: &tr}},+ }}+ if got := endpointSliceReadyCount(slice); got != 2 {+ t.Fatalf("endpointSliceReadyCount(mixed) = %d, want 2", got)+ }+ })+}++func TestBranchcov0723Am_ServiceAccountImagePullSecrets(t *testing.T) {+ t.Run("empty_returns_nil", func(t *testing.T) {+ if got := serviceAccountImagePullSecrets(corev1.ServiceAccount{}); got != nil {+ t.Fatalf("serviceAccountImagePullSecrets(empty) = %v, want nil", got)+ }+ })++ t.Run("secrets_trimmed_sorted_blank_filtered_no_dedup", func(t *testing.T) {+ sa := corev1.ServiceAccount{ImagePullSecrets: []corev1.LocalObjectReference{+ {Name: " regcred "},+ {Name: "regcred"}, // duplicate after trim; source does NOT dedupe+ {Name: " "}, // blank, filtered+ {Name: "other"},+ }}+ got := serviceAccountImagePullSecrets(sa)+ // Source sorts the result; duplicates are preserved.+ want := []string{"other", "regcred", "regcred"}+ if len(got) != len(want) {+ t.Fatalf("serviceAccountImagePullSecrets len = %d, want %d (%v)", len(got), len(want), got)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("serviceAccountImagePullSecrets[%d] = %q, want %q", i, got[i], want[i])+ }+ }+ })+}