| 1 | /* |
| 2 | Copyright 2024 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 agent |
| 18 | |
| 19 | import ( |
| 20 | "testing" |
| 21 | ) |
| 22 | |
| 23 | type FakeServerCounter struct { |
| 24 | count int |
| 25 | } |
| 26 | |
| 27 | func (f *FakeServerCounter) Count() int { |
| 28 | return f.count |
| 29 | } |
| 30 | |
| 31 | func TestServerCount(t *testing.T) { |
| 32 | testCases := []struct { |
| 33 | name string |
| 34 | serverCountSource string |
| 35 | leaseCounter ServerCounter |
| 36 | responseCount int |
| 37 | want int |
| 38 | }{ |
| 39 | { |
| 40 | name: "higher from response", |
| 41 | serverCountSource: "max", |
| 42 | responseCount: 42, |
| 43 | leaseCounter: &FakeServerCounter{24}, |
| 44 | want: 42, |
| 45 | }, |
| 46 | { |
| 47 | name: "higher from leases", |
| 48 | serverCountSource: "max", |
| 49 | responseCount: 3, |
| 50 | leaseCounter: &FakeServerCounter{6}, |
| 51 | want: 6, |
| 52 | }, |
| 53 | { |
| 54 | name: "both zero", |
| 55 | serverCountSource: "max", |
| 56 | responseCount: 0, |
| 57 | leaseCounter: &FakeServerCounter{0}, |
| 58 | want: 1, |
| 59 | }, |
| 60 | |
| 61 | { |
| 62 | name: "response picked by default when no lease counter", |
| 63 | serverCountSource: "default", |
| 64 | responseCount: 3, |
| 65 | leaseCounter: nil, |
| 66 | want: 3, |
| 67 | }, |
| 68 | { |
| 69 | name: "lease counter always picked when present", |
| 70 | serverCountSource: "default", |
| 71 | responseCount: 6, |
| 72 | leaseCounter: &FakeServerCounter{3}, |
| 73 | want: 3, |
| 74 | }, |
| 75 | } |
| 76 | |
| 77 | for _, tc := range testCases { |
| 78 | t.Run(tc.name, func(t *testing.T) { |
| 79 | |
| 80 | cs := &ClientSet{ |
| 81 | clients: make(map[string]*Client), |
| 82 | leaseCounter: tc.leaseCounter, |
| 83 | serverCountSource: tc.serverCountSource, |
| 84 | } |
| 85 | cs.lastReceivedServerCount = tc.responseCount |
| 86 | if got := cs.ServerCount(); got != tc.want { |
| 87 | t.Errorf("cs.ServerCount() = %v, want: %v", got, tc.want) |
| 88 | } |
| 89 | }) |
| 90 | } |
| 91 | |
| 92 | } |