From d2ef8a18089c643be55aa81fa5241826c5a2dd81 Mon Sep 17 00:00:00 2001 From: yongruilin Date: Tue, 29 Oct 2024 14:13:35 -0700 Subject: [PATCH] feat(metrics): Add util func to reset label allow lists Adds a utility function `ResetLabelValueAllowLists` to reset the allow lists for label values. This facilitates testing by allowing tests to clear the global state between runs and avoid unintended side effects. --- .../src/k8s.io/component-base/metrics/opts.go | 8 ++++++++ .../k8s.io/component-base/metrics/opts_test.go | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/staging/src/k8s.io/component-base/metrics/opts.go b/staging/src/k8s.io/component-base/metrics/opts.go index 9f39c444348..43015169e72 100644 --- a/staging/src/k8s.io/component-base/metrics/opts.go +++ b/staging/src/k8s.io/component-base/metrics/opts.go @@ -37,6 +37,14 @@ var ( allowListLock sync.RWMutex ) +// ResetLabelValueAllowLists resets the allow lists for label values. +// NOTE: This should only be used in test. +func ResetLabelValueAllowLists() { + allowListLock.Lock() + defer allowListLock.Unlock() + labelValueAllowLists = map[string]*MetricLabelAllowList{} +} + // KubeOpts is superset struct for prometheus.Opts. The prometheus Opts structure // is purposefully not embedded here because that would change struct initialization // in the manner which people are currently accustomed. diff --git a/staging/src/k8s.io/component-base/metrics/opts_test.go b/staging/src/k8s.io/component-base/metrics/opts_test.go index b2e0fb0295c..7094f18761b 100644 --- a/staging/src/k8s.io/component-base/metrics/opts_test.go +++ b/staging/src/k8s.io/component-base/metrics/opts_test.go @@ -208,3 +208,21 @@ metric2,label2: v3`, }) } } + +func TestResetLabelValueAllowLists(t *testing.T) { + labelValueAllowLists = map[string]*MetricLabelAllowList{ + "metric1": { + labelToAllowList: map[string]sets.Set[string]{ + "label1": sets.New[string]("v1", "v2"), + }, + }, + "metric2": { + labelToAllowList: map[string]sets.Set[string]{ + "label2": sets.New[string]("v3"), + }, + }, + } + + ResetLabelValueAllowLists() + assert.Empty(t, labelValueAllowLists) +}