k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/plugin/pkg/admission/eventratelimit/cache_test.go (about) 1 /* 2 Copyright 2017 The Kubernetes 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 eventratelimit 18 19 import ( 20 "testing" 21 22 "k8s.io/client-go/util/flowcontrol" 23 "k8s.io/utils/lru" 24 ) 25 26 func TestSingleCache(t *testing.T) { 27 rateLimiter := flowcontrol.NewTokenBucketRateLimiter(1., 1) 28 cache := singleCache{ 29 rateLimiter: rateLimiter, 30 } 31 cases := []interface{}{nil, "key1", "key2"} 32 for _, tc := range cases { 33 actual := cache.get(tc) 34 if e, a := rateLimiter, actual; e != a { 35 t.Errorf("unexpected entry in cache for key %v: expected %v, got %v", tc, e, a) 36 } 37 } 38 } 39 40 func TestLRUCache(t *testing.T) { 41 rateLimiters := []flowcontrol.RateLimiter{ 42 flowcontrol.NewTokenBucketRateLimiter(1., 1), 43 flowcontrol.NewTokenBucketRateLimiter(2., 2), 44 flowcontrol.NewTokenBucketRateLimiter(3., 3), 45 flowcontrol.NewTokenBucketRateLimiter(4., 4), 46 } 47 nextRateLimiter := 0 48 rateLimiterFactory := func() flowcontrol.RateLimiter { 49 rateLimiter := rateLimiters[nextRateLimiter] 50 nextRateLimiter++ 51 return rateLimiter 52 } 53 underlyingCache := lru.New(2) 54 cache := lruCache{ 55 rateLimiterFactory: rateLimiterFactory, 56 cache: underlyingCache, 57 } 58 cases := []struct { 59 name string 60 key int 61 expected flowcontrol.RateLimiter 62 }{ 63 { 64 name: "first added", 65 key: 0, 66 expected: rateLimiters[0], 67 }, 68 { 69 name: "first obtained", 70 key: 0, 71 expected: rateLimiters[0], 72 }, 73 { 74 name: "second added", 75 key: 1, 76 expected: rateLimiters[1], 77 }, 78 { 79 name: "second obtained", 80 key: 1, 81 expected: rateLimiters[1], 82 }, 83 { 84 name: "first obtained second time", 85 key: 0, 86 expected: rateLimiters[0], 87 }, 88 { 89 name: "third added", 90 key: 2, 91 expected: rateLimiters[2], 92 }, 93 { 94 name: "third obtained", 95 key: 2, 96 expected: rateLimiters[2], 97 }, 98 { 99 name: "first obtained third time", 100 key: 0, 101 expected: rateLimiters[0], 102 }, 103 { 104 name: "second re-added after eviction", 105 key: 1, 106 expected: rateLimiters[3], 107 }, 108 } 109 for _, tc := range cases { 110 actual := cache.get(tc.key) 111 if e, a := tc.expected, actual; e != a { 112 t.Errorf("%v: unexpected entry in cache for key %v: expected %v, got %v", tc.name, tc.key, e, a) 113 } 114 } 115 }