Skip to content

Commit

Permalink
Merge pull request #2502 from bartlettc22/cr-duplication-fix
Browse files Browse the repository at this point in the history
fix: de-duplication of custom resource metrics
  • Loading branch information
k8s-ci-robot authored Oct 15, 2024
2 parents 0013d73 + bd6beed commit 77a99a5
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 6 deletions.
10 changes: 4 additions & 6 deletions internal/store/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
"context"
"fmt"
"reflect"
"sort"
"slices"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -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
}

Expand Down
62 changes: 62 additions & 0 deletions internal/store/builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package store

import (
"reflect"
"slices"
"testing"

"k8s.io/kube-state-metrics/v2/pkg/options"
Expand Down Expand Up @@ -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)
}
}
}

0 comments on commit 77a99a5

Please sign in to comment.