knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/reconciler/leader_test.go (about) 1 /* 2 Copyright 2020 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 reconciler 18 19 import ( 20 "testing" 21 22 "github.com/google/go-cmp/cmp" 23 "k8s.io/apimachinery/pkg/types" 24 ) 25 26 func TestLeaderAwareFuncs(t *testing.T) { 27 laf := LeaderAwareFuncs{} 28 wantBkt := UniversalBucket() 29 wantKey := types.NamespacedName{ 30 Namespace: "foo", 31 Name: "bar", 32 } 33 called := false 34 wantFunc := func(gotBkt Bucket, gotKey types.NamespacedName) { 35 called = true 36 if !cmp.Equal(gotKey, wantKey) { 37 t.Error("key (-want, +got) =", cmp.Diff(wantKey, gotKey)) 38 } 39 if !cmp.Equal(gotBkt, wantBkt) { 40 t.Error("bucket (-want, +got) =", cmp.Diff(wantBkt, gotBkt)) 41 } 42 } 43 44 laf.PromoteFunc = func(bkt Bucket, gotFunc func(Bucket, types.NamespacedName)) error { 45 if gotFunc == nil { 46 t.Error("PromoteFunc should not be called with nil gotFunc") 47 return nil 48 } 49 50 gotFunc(bkt, wantKey) 51 if !called { 52 t.Error("gotFunc didn't call wantFunc!") 53 } 54 55 // IsLeaderFor takes the bucket's lock, so make sure that the callback 56 // we provide is not called while the lock is still held by calling a 57 // function that we know takes the lock. 58 if !laf.IsLeaderFor(wantKey) { 59 t.Error("IsLeaderFor() = false, wanted true") 60 } 61 return nil 62 } 63 laf.DemoteFunc = func(bkt Bucket) { 64 // Check that we're not called while the lock is held, 65 // and that we are no longer leader. 66 if laf.IsLeaderFor(wantKey) { 67 t.Error("IsLeaderFor() = true, wanted false") 68 } 69 } 70 71 // We don't start as leader. 72 if laf.IsLeaderFor(wantKey) { 73 t.Error("IsLeaderFor() = true, wanted false") 74 } 75 76 // After Promote we are leader. 77 laf.Promote(wantBkt, wantFunc) 78 if !laf.IsLeaderFor(wantKey) { 79 t.Error("IsLeaderFor() = false, wanted true") 80 } 81 82 // After Demote we are not leader. 83 laf.Demote(wantBkt) 84 if laf.IsLeaderFor(wantKey) { 85 t.Error("IsLeaderFor() = true, wanted false") 86 } 87 88 // We should elide calls with a nil enq 89 laf.Promote(wantBkt, nil) 90 }