| 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 |
package util //nolint:revive |
| 17 |
|
| 18 |
import ( |
| 19 |
"testing" |
| 20 |
"time" |
| 21 |
|
| 22 |
clocktesting "k8s.io/utils/clock/testing" |
| 23 |
|
| 24 |
proxytesting "sigs.k8s.io/apiserver-network-proxy/pkg/testing" |
| 25 |
) |
| 26 |
|
| 27 |
func TestIsLeaseValid(t *testing.T) { |
| 28 |
testCases := []struct { |
| 29 |
name string |
| 30 |
template proxytesting.LeaseTemplate |
| 31 |
want bool |
| 32 |
}{ |
| 33 |
{ |
| 34 |
name: "freshly acquired lease is valid", |
| 35 |
template: proxytesting.LeaseTemplate{ |
| 36 |
DurationSecs: 1000, |
| 37 |
TimeSinceAcquire: time.Second, |
| 38 |
}, |
| 39 |
want: true, |
| 40 |
}, { |
| 41 |
name: "freshly renewed lease is valid", |
| 42 |
template: proxytesting.LeaseTemplate{ |
| 43 |
DurationSecs: 1000, |
| 44 |
TimeSinceAcquire: 10000 * time.Second, |
| 45 |
TimeSinceRenew: time.Second, |
| 46 |
}, |
| 47 |
want: true, |
| 48 |
}, { |
| 49 |
name: "lease with neither acquisition nor renewal time is invalid", |
| 50 |
template: proxytesting.LeaseTemplate{ |
| 51 |
DurationSecs: 1000, |
| 52 |
}, |
| 53 |
want: false, |
| 54 |
}, { |
| 55 |
name: "expired lease (only acquired) is invalid", |
| 56 |
template: proxytesting.LeaseTemplate{ |
| 57 |
DurationSecs: 1000, |
| 58 |
TimeSinceAcquire: 10000 * time.Second, |
| 59 |
}, |
| 60 |
want: false, |
| 61 |
}, { |
| 62 |
name: "expired lease (acquired and renewed) is invalid", |
| 63 |
template: proxytesting.LeaseTemplate{ |
| 64 |
DurationSecs: 1000, |
| 65 |
TimeSinceAcquire: 10000 * time.Second, |
| 66 |
TimeSinceRenew: 9000 * time.Second, |
| 67 |
}, |
| 68 |
want: false, |
| 69 |
}, |
| 70 |
} |
| 71 |
|
| 72 |
for _, tc := range testCases { |
| 73 |
t.Run(tc.name, func(t *testing.T) { |
| 74 |
now := time.Now() |
| 75 |
pc := clocktesting.NewFakePassiveClock(now) |
| 76 |
|
| 77 |
lease := proxytesting.NewLeaseFromTemplate(pc, tc.template) |
| 78 |
|
| 79 |
pc.SetTime(now.Add(time.Millisecond)) |
| 80 |
|
| 81 |
got := IsLeaseValid(pc, *lease) |
| 82 |
if got != tc.want { |
| 83 |
t.Errorf("incorrect lease validity (got: %v, want: %v)", got, tc.want) |
| 84 |
} |
| 85 |
}) |
| 86 |
} |
| 87 |
} |