knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/configmap/manual_watcher_test.go (about) 1 /* 2 Copyright 2018 The Knative Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package configmap 18 19 import ( 20 "sync" 21 "testing" 22 23 corev1 "k8s.io/api/core/v1" 24 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 ) 26 27 type counter struct { 28 name string 29 mu sync.RWMutex 30 cfg []*corev1.ConfigMap 31 wg *sync.WaitGroup 32 } 33 34 func (c *counter) callback(cm *corev1.ConfigMap) { 35 c.mu.Lock() 36 defer c.mu.Unlock() 37 c.cfg = append(c.cfg, cm) 38 if c.wg != nil { 39 c.wg.Done() 40 } 41 } 42 43 func (c *counter) count() int { 44 c.mu.RLock() 45 defer c.mu.RUnlock() 46 return len(c.cfg) 47 } 48 49 func TestManualStartNOOP(t *testing.T) { 50 watcher := ManualWatcher{ 51 Namespace: "default", 52 } 53 if err := watcher.Start(nil); err != nil { 54 t.Error("Unexpected error watcher.Start() =", err) 55 } 56 } 57 58 func TestCallbackInvoked(t *testing.T) { 59 watcher := ManualWatcher{ 60 Namespace: "default", 61 } 62 63 // Verify empty works as designed. 64 watcher.OnChange(&corev1.ConfigMap{ 65 ObjectMeta: metav1.ObjectMeta{ 66 Namespace: "default", 67 Name: "foo", 68 }, 69 }) 70 observer := counter{} 71 72 watcher.Watch("foo", observer.callback) 73 watcher.OnChange(&corev1.ConfigMap{ 74 ObjectMeta: metav1.ObjectMeta{ 75 Namespace: "default", 76 Name: "foo", 77 }, 78 }) 79 80 if observer.count() == 0 { 81 t.Error("Expected callback to be invoked - got invocations", observer.count()) 82 } 83 } 84 85 func TestDifferentNamespace(t *testing.T) { 86 watcher := ManualWatcher{ 87 Namespace: "default", 88 } 89 90 observer := counter{} 91 92 watcher.Watch("foo", observer.callback) 93 watcher.OnChange(&corev1.ConfigMap{ 94 ObjectMeta: metav1.ObjectMeta{ 95 Namespace: "not-default", 96 Name: "foo", 97 }, 98 }) 99 100 if observer.count() != 0 { 101 t.Error("Expected callback to be not be invoked - got invocations", observer.count()) 102 } 103 } 104 105 func TestDifferentConfigName(t *testing.T) { 106 watcher := ManualWatcher{ 107 Namespace: "default", 108 } 109 110 observer := counter{} 111 112 watcher.OnChange(&corev1.ConfigMap{ 113 ObjectMeta: metav1.ObjectMeta{ 114 Namespace: "default", 115 Name: "foo", 116 }, 117 }) 118 119 watcher.Watch("bar", observer.callback) 120 121 if observer.count() != 0 { 122 t.Error("Expected callback to be not be invoked - got invocations", observer.count()) 123 } 124 }