diff --git a/internal/store/builder.go b/internal/store/builder.go index f7941794e..3b253295c 100644 --- a/internal/store/builder.go +++ b/internal/store/builder.go @@ -20,7 +20,7 @@ import ( "context" "fmt" "reflect" - "sort" + "slices" "strconv" "strings" "time" @@ -113,12 +113,10 @@ func (b *Builder) WithEnabledResources(r []string) error { } } - var sortedResources []string - sortedResources = append(sortedResources, r...) + b.enabledResources = append(b.enabledResources, r...) + slices.Sort(b.enabledResources) + b.enabledResources = slices.Compact(b.enabledResources) - sort.Strings(sortedResources) - - b.enabledResources = append(b.enabledResources, sortedResources...) return nil } diff --git a/internal/store/builder_test.go b/internal/store/builder_test.go index 3bb5dea3a..d9ea5813e 100644 --- a/internal/store/builder_test.go +++ b/internal/store/builder_test.go @@ -18,6 +18,7 @@ package store import ( "reflect" + "slices" "testing" "k8s.io/kube-state-metrics/v2/pkg/options" @@ -196,3 +197,64 @@ func TestWithAllowAnnotations(t *testing.T) { } } } + +func TestWithEnabledResources(t *testing.T) { + + tests := []struct { + Desc string + EnabledResources []string + Wanted []string + err expectedError + }{ + { + Desc: "sorts enabled resources", + EnabledResources: []string{"pods", "cronjobs", "deployments"}, + Wanted: []string{ + "cronjobs", + "deployments", + "pods", + }, + }, + { + Desc: "de-duplicates enabled resources", + EnabledResources: []string{"pods", "cronjobs", "deployments", "pods"}, + Wanted: []string{ + "cronjobs", + "deployments", + "pods", + }, + }, + { + Desc: "error if not exist", + EnabledResources: []string{"pods", "cronjobs", "deployments", "foo"}, + Wanted: []string{}, + err: expectedError{ + expectedResourceError: true, + }, + }, + } + for _, test := range tests { + b := NewBuilder() + + // Set the enabled resources. + err := b.WithEnabledResources(test.EnabledResources) + if test.err.expectedResourceError { + if err == nil { + t.Log("Did not expect error while setting resources (--resources).") + t.Fatalf("Test error for Desc: %s. Got Error: %v", test.Desc, err) + } else { + return + } + } + if err != nil { + t.Log("...") + t.Fatal("...", test.Desc, err) + } + + // Evaluate. + if !slices.Equal(b.enabledResources, test.Wanted) { + t.Log("Expected enabled resources to be equal.") + t.Errorf("Test error for Desc: %s\n Want: \n%+v\n Got: \n%#+v", test.Desc, test.Wanted, b.enabledResources) + } + } +}