fix: Update unit test to catch actual nil Labels case and fix functionality to handle nil Labels

Kubernetes-commit: 8d4108bf9355b086e7f8996e84723ca389db887a
This commit is contained in:
DerekFrank 2025-08-15 14:28:18 -07:00 committed by Kubernetes Publisher
parent bccbbb3816
commit 706156ceaf
2 changed files with 27 additions and 17 deletions

View File

@ -77,6 +77,9 @@ func (ll *LeaseLock) Update(ctx context.Context, ler LeaderElectionRecord) error
ll.lease.Spec = LeaderElectionRecordToLeaseSpec(&ler)
if ll.Labels != nil {
if ll.lease.Labels == nil {
ll.lease.Labels = map[string]string{}
}
// Only overwrite the labels that are specifically set
for k, v := range ll.Labels {
ll.lease.Labels[k] = v

View File

@ -266,7 +266,28 @@ func TestLeaseConversion(t *testing.T) {
}
}
func TestUpdateWithNilLabels(t *testing.T) {
func TestUpdateWithNilLabelsOnLease(t *testing.T) {
setup()
// Create initial lease
if err := leaseLock.Create(context.Background(), testRecord); err != nil {
t.Fatalf("Failed to create lease: %v", err)
}
// Get the lease to initialize leaseLock.lease
if _, _, err := leaseLock.Get(context.Background()); err != nil {
t.Fatalf("Failed to get lease: %v", err)
}
leaseLock.Labels = map[string]string{"custom-key": "custom-val"}
// Update should succeed even with nil Labels on the lease itself
if err := leaseLock.Update(context.Background(), testRecord); err != nil {
t.Errorf("Update failed with nil Labels: %v", err)
}
}
func TestUpdateWithNilLabelsOnLeaseLock(t *testing.T) {
setup()
// Create initial lease
@ -280,21 +301,7 @@ func TestUpdateWithNilLabels(t *testing.T) {
leaseLock.lease.Labels = map[string]string{"custom-key": "custom-val"}
// Update labels
lease, err := leaseLock.Client.Leases(testNamespace).Update(context.Background(), leaseLock.lease, metav1.UpdateOptions{})
if err != nil {
t.Fatalf("Failed to update lease labels: %v", err)
}
val, exists := lease.Labels["custom-key"]
if !exists {
t.Error("Label was overidden on the lease")
}
if val != "custom-val" {
t.Errorf("Label value mismatch, got %q want %q", val, "custom-val")
}
// Update should succeed even with nil Labels
// Update should succeed even with nil Labels on the leaselock
if err := leaseLock.Update(context.Background(), testRecord); err != nil {
t.Errorf("Update failed with nil Labels: %v", err)
}
@ -364,4 +371,4 @@ func TestLabelUpdate(t *testing.T) {
if val != "custom-val-2" {
t.Errorf("Label value mismatch, got %q want %q", val, "custom-val-2")
}
}
}