diff --git a/modules/common/labels/labels.go b/modules/common/labels/labels.go index 88840465..1030f8a1 100644 --- a/modules/common/labels/labels.go +++ b/modules/common/labels/labels.go @@ -19,6 +19,7 @@ package labels import ( "github.com/openstack-k8s-operators/lib-common/modules/common" "github.com/openstack-k8s-operators/lib-common/modules/common/util" + "k8s.io/apimachinery/pkg/api/equality" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -108,3 +109,10 @@ func GetLabelSelector( MatchLabels: serviceLabels, } } + +// EqualLabelSelectors - returns true if two labelSelectors matches, false +// otherwise +func EqualLabelSelectors( + l1, l2 metav1.LabelSelector) bool { + return equality.Semantic.DeepEqual(l1, l2) +} diff --git a/modules/common/labels/labels_test.go b/modules/common/labels/labels_test.go index 1dcd6e5a..3893475f 100644 --- a/modules/common/labels/labels_test.go +++ b/modules/common/labels/labels_test.go @@ -124,3 +124,20 @@ func TestGetLabels(t *testing.T) { }) } } + +// Given a map[string]string, get the corresponding labelSelectors and compare +// them via the EqualLabelSelectors utility +func TestEqualLabelSelectors(t *testing.T) { + t.Run("Compare labelSelectors", func(t *testing.T) { + g := NewWithT(t) + + l0 := GetLabelSelector(map[string]string{}) + l1 := GetLabelSelector(map[string]string{"app": "foo", "version": "v1", "property": "bar"}) + l2 := l1 + l3 := GetLabelSelector(map[string]string{"app": "api", "version": "v1"}) + + g.Expect(EqualLabelSelectors(l1, l0)).To(BeFalse()) + g.Expect(EqualLabelSelectors(l1, l2)).To(BeTrue()) + g.Expect(EqualLabelSelectors(l1, l3)).To(BeFalse()) + }) +}