Skip to content

Commit a5101e8

Browse files
committed
Add EqualLabelSelectors utility function
This patch introduces EqualLabelSelectors function that allows to match two labelSelectors. This is useful when comparing Secrets or other k8s resources that a service operator watches. Signed-off-by: Francesco Pantano <[email protected]>
1 parent 7e1cd2e commit a5101e8

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

modules/common/labels/labels.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package labels
1919
import (
2020
"github.com/openstack-k8s-operators/lib-common/modules/common"
2121
"github.com/openstack-k8s-operators/lib-common/modules/common/util"
22+
"k8s.io/apimachinery/pkg/api/equality"
2223
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2324
)
2425

@@ -108,3 +109,10 @@ func GetLabelSelector(
108109
MatchLabels: serviceLabels,
109110
}
110111
}
112+
113+
// EqualLabelSelectors - returns true if two labelSelectors matches, false
114+
// otherwise
115+
func EqualLabelSelectors(
116+
l1, l2 metav1.LabelSelector) bool {
117+
return equality.Semantic.DeepEqual(l1, l2)
118+
}

modules/common/labels/labels_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,3 +124,20 @@ func TestGetLabels(t *testing.T) {
124124
})
125125
}
126126
}
127+
128+
// Given a map[string]string, get the corresponding labelSelectors and compare
129+
// them via the EqualLabelSelectors utility
130+
func TestEqualLabelSelectors(t *testing.T) {
131+
t.Run("Compare labelSelectors", func(t *testing.T) {
132+
g := NewWithT(t)
133+
134+
l0 := GetLabelSelector(map[string]string{})
135+
l1 := GetLabelSelector(map[string]string{"app": "foo", "version": "v1", "property": "bar"})
136+
l2 := GetLabelSelector(map[string]string{"app": "foo", "version": "v1", "property": "bar"})
137+
l3 := GetLabelSelector(map[string]string{"app": "api", "version": "v1"})
138+
139+
g.Expect(EqualLabelSelectors(l1, l0)).To(BeFalse())
140+
g.Expect(EqualLabelSelectors(l1, l2)).To(BeTrue())
141+
g.Expect(EqualLabelSelectors(l1, l3)).To(BeFalse())
142+
})
143+
}

0 commit comments

Comments
 (0)