From 809ce573e4dd025be7dd41d50fcffa6361713a59 Mon Sep 17 00:00:00 2001 From: Matt Moore Date: Mon, 28 Oct 2019 10:41:42 -0700 Subject: [PATCH] Add FilterByName for cluster-scoped resources. (#816) This is a precursor to reconciling named webhook configurations, and largely a copy of `FilterByNameAndNamespace`. --- controller/controller.go | 11 ++++++ controller/controller_test.go | 63 +++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/controller/controller.go b/controller/controller.go index 38fafda80..19b87e6d4 100644 --- a/controller/controller.go +++ b/controller/controller.go @@ -98,6 +98,17 @@ func Filter(gvk schema.GroupVersionKind) func(obj interface{}) bool { } } +// FilterWithName makes it simple to create FilterFunc's for use with +// cache.FilteringResourceEventHandler that filter based on a name. +func FilterWithName(name string) func(obj interface{}) bool { + return func(obj interface{}) bool { + if object, ok := obj.(metav1.Object); ok { + return name == object.GetName() + } + return false + } +} + // FilterWithNameAndNamespace makes it simple to create FilterFunc's for use with // cache.FilteringResourceEventHandler that filter based on a namespace and a name. func FilterWithNameAndNamespace(namespace, name string) func(obj interface{}) bool { diff --git a/controller/controller_test.go b/controller/controller_test.go index e96e39abc..5f4713900 100644 --- a/controller/controller_test.go +++ b/controller/controller_test.go @@ -135,6 +135,69 @@ func TestFilterWithNameAndNamespace(t *testing.T) { } } +func TestFilterWithName(t *testing.T) { + filter := FilterWithName("test-name") + + tests := []struct { + name string + input interface{} + want bool + }{{ + name: "not a metav1.Object", + input: "foo", + want: false, + }, { + name: "nil", + input: nil, + want: false, + }, { + name: "name matches, namespace does not", + input: &Resource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-name", + Namespace: "wrong-namespace", + }, + }, + want: true, // Unlike FilterWithNameAndNamespace this passes + }, { + name: "namespace matches, name does not", + input: &Resource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "wrong-name", + Namespace: "test-namespace", + }, + }, + want: false, + }, { + name: "neither matches", + input: &Resource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "wrong-name", + Namespace: "wrong-namespace", + }, + }, + want: false, + }, { + name: "matches", + input: &Resource{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-name", + Namespace: "test-namespace", + }, + }, + want: true, + }} + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got := filter(test.input) + if test.want != got { + t.Errorf("FilterWithNameAndNamespace() = %v, wanted %v", got, test.want) + } + }) + } +} + func TestFilter(t *testing.T) { filter := Filter(gvk)