| 1 |
/* |
| 2 |
Copyright 2025 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 rest |
| 18 |
|
| 19 |
import ( |
| 20 |
"bytes" |
| 21 |
"context" |
| 22 |
"fmt" |
| 23 |
"reflect" |
| 24 |
"regexp" |
| 25 |
"strings" |
| 26 |
"testing" |
| 27 |
|
| 28 |
v1 "k8s.io/api/core/v1" |
| 29 |
"k8s.io/apimachinery/pkg/api/operation" |
| 30 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 31 |
"k8s.io/apimachinery/pkg/conversion" |
| 32 |
"k8s.io/apimachinery/pkg/runtime" |
| 33 |
"k8s.io/apimachinery/pkg/runtime/schema" |
| 34 |
"k8s.io/apimachinery/pkg/util/sets" |
| 35 |
"k8s.io/apimachinery/pkg/util/validation/field" |
| 36 |
genericapirequest "k8s.io/apiserver/pkg/endpoints/request" |
| 37 |
"k8s.io/klog/v2" |
| 38 |
) |
| 39 |
|
| 40 |
func TestValidateDeclaratively(t *testing.T) { |
| 41 |
valid := &Pod{ |
| 42 |
TypeMeta: metav1.TypeMeta{ |
| 43 |
APIVersion: "v1", |
| 44 |
Kind: "Pod", |
| 45 |
}, |
| 46 |
ObjectMeta: metav1.ObjectMeta{ |
| 47 |
Name: "test", |
| 48 |
}, |
| 49 |
} |
| 50 |
|
| 51 |
invalidRestartPolicy := &Pod{ |
| 52 |
TypeMeta: metav1.TypeMeta{ |
| 53 |
APIVersion: "v1", |
| 54 |
Kind: "Pod", |
| 55 |
}, |
| 56 |
ObjectMeta: metav1.ObjectMeta{ |
| 57 |
Name: "test", |
| 58 |
}, |
| 59 |
RestartPolicy: "INVALID", |
| 60 |
} |
| 61 |
|
| 62 |
invalidRestartPolicyErr := field.Invalid(field.NewPath("spec", "restartPolicy"), "", "Invalid value").WithOrigin("invalid-test") |
| 63 |
mutatedRestartPolicyErr := field.Invalid(field.NewPath("spec", "restartPolicy"), "", "Immutable field").WithOrigin("immutable-test") |
| 64 |
invalidStatusErr := field.Invalid(field.NewPath("status", "conditions"), "", "Invalid condition").WithOrigin("invalid-condition") |
| 65 |
invalidIfOptionErr := field.Invalid(field.NewPath("spec", "restartPolicy"), "", "Invalid when option is set").WithOrigin("invalid-when-option-set") |
| 66 |
invalidSubresourceErr := field.InternalError(nil, fmt.Errorf("unexpected error parsing subresource path: %w", fmt.Errorf("invalid subresource path: %s", "invalid/status"))) |
| 67 |
|
| 68 |
testCases := []struct { |
| 69 |
name string |
| 70 |
object runtime.Object |
| 71 |
oldObject runtime.Object |
| 72 |
subresource string |
| 73 |
options sets.Set[string] |
| 74 |
expected field.ErrorList |
| 75 |
}{ |
| 76 |
{ |
| 77 |
name: "create", |
| 78 |
object: invalidRestartPolicy, |
| 79 |
expected: field.ErrorList{invalidRestartPolicyErr}, |
| 80 |
}, |
| 81 |
{ |
| 82 |
name: "update", |
| 83 |
object: invalidRestartPolicy, |
| 84 |
oldObject: valid, |
| 85 |
expected: field.ErrorList{invalidRestartPolicyErr, mutatedRestartPolicyErr}, |
| 86 |
}, |
| 87 |
{ |
| 88 |
name: "update subresource with declarative validation", |
| 89 |
subresource: "status", |
| 90 |
object: valid, |
| 91 |
oldObject: valid, |
| 92 |
expected: field.ErrorList{invalidStatusErr}, |
| 93 |
}, |
| 94 |
{ |
| 95 |
name: "update subresource without declarative validation", |
| 96 |
subresource: "scale", |
| 97 |
object: valid, |
| 98 |
oldObject: valid, |
| 99 |
expected: field.ErrorList{}, // Expect no errors if there is no registered validation |
| 100 |
}, |
| 101 |
{ |
| 102 |
name: "invalid subresource", |
| 103 |
subresource: "/invalid/status", |
| 104 |
object: valid, |
| 105 |
oldObject: valid, |
| 106 |
expected: field.ErrorList{invalidSubresourceErr}, |
| 107 |
}, |
| 108 |
{ |
| 109 |
name: "update with option", |
| 110 |
options: sets.New("option1"), |
| 111 |
object: valid, |
| 112 |
expected: field.ErrorList{invalidIfOptionErr}, |
| 113 |
}, |
| 114 |
} |
| 115 |
|
| 116 |
ctx := context.Background() |
| 117 |
|
| 118 |
internalGV := schema.GroupVersion{Group: "", Version: runtime.APIVersionInternal} |
| 119 |
v1GV := schema.GroupVersion{Group: "", Version: "v1"} |
| 120 |
|
| 121 |
scheme := runtime.NewScheme() |
| 122 |
scheme.AddKnownTypes(internalGV, &Pod{}) |
| 123 |
scheme.AddKnownTypes(v1GV, &v1.Pod{}) |
| 124 |
|
| 125 |
scheme.AddValidationFunc(&v1.Pod{}, func(ctx context.Context, op operation.Operation, object, oldObject interface{}, subresources ...string) field.ErrorList { |
| 126 |
results := field.ErrorList{} |
| 127 |
if op.Options.Has("option1") { |
| 128 |
results = append(results, invalidIfOptionErr) |
| 129 |
} |
| 130 |
if len(subresources) == 1 && subresources[0] == "status" { |
| 131 |
results = append(results, invalidStatusErr) |
| 132 |
} |
| 133 |
if op.Type == operation.Update && object.(*v1.Pod).Spec.RestartPolicy != oldObject.(*v1.Pod).Spec.RestartPolicy { |
| 134 |
results = append(results, mutatedRestartPolicyErr) |
| 135 |
} |
| 136 |
if object.(*v1.Pod).Spec.RestartPolicy == "INVALID" { |
| 137 |
results = append(results, invalidRestartPolicyErr) |
| 138 |
} |
| 139 |
return results |
| 140 |
}) |
| 141 |
err := scheme.AddConversionFunc(&Pod{}, &v1.Pod{}, func(a, b interface{}, scope conversion.Scope) error { |
| 142 |
if in, ok := a.(*Pod); ok { |
| 143 |
if out, ok := b.(*v1.Pod); ok { |
| 144 |
out.APIVersion = in.APIVersion |
| 145 |
out.Kind = in.Kind |
| 146 |
out.Spec.RestartPolicy = v1.RestartPolicy(in.RestartPolicy) |
| 147 |
} |
| 148 |
} |
| 149 |
return nil |
| 150 |
}) |
| 151 |
if err != nil { |
| 152 |
t.Fatal(err) |
| 153 |
} |
| 154 |
|
| 155 |
for _, tc := range testCases { |
| 156 |
ctx = genericapirequest.WithRequestInfo(ctx, &genericapirequest.RequestInfo{ |
| 157 |
APIGroup: "", |
| 158 |
APIVersion: "v1", |
| 159 |
Subresource: tc.subresource, |
| 160 |
}) |
| 161 |
t.Run(tc.name, func(t *testing.T) { |
| 162 |
var results field.ErrorList |
| 163 |
if tc.oldObject == nil { |
| 164 |
results = ValidateDeclaratively(ctx, tc.options, scheme, tc.object) |
| 165 |
} else { |
| 166 |
results = ValidateUpdateDeclaratively(ctx, tc.options, scheme, tc.object, tc.oldObject) |
| 167 |
} |
| 168 |
matcher := field.ErrorMatcher{}.ByType().ByField().ByOrigin() |
| 169 |
matcher.Test(t, tc.expected, results) |
| 170 |
}) |
| 171 |
} |
| 172 |
} |
| 173 |
|
| 174 |
// Fake internal pod type, since core.Pod cannot be imported by this package |
| 175 |
type Pod struct { |
| 176 |
metav1.TypeMeta `json:",inline"` |
| 177 |
metav1.ObjectMeta `json:"metadata,omitempty"` |
| 178 |
RestartPolicy string `json:"restartPolicy"` |
| 179 |
} |
| 180 |
|
| 181 |
func (Pod) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } |
| 182 |
|
| 183 |
func (p Pod) DeepCopyObject() runtime.Object { |
| 184 |
return &Pod{ |
| 185 |
TypeMeta: metav1.TypeMeta{ |
| 186 |
APIVersion: p.APIVersion, |
| 187 |
Kind: p.Kind, |
| 188 |
}, |
| 189 |
ObjectMeta: metav1.ObjectMeta{ |
| 190 |
Name: p.Name, |
| 191 |
Namespace: p.Namespace, |
| 192 |
}, |
| 193 |
RestartPolicy: p.RestartPolicy, |
| 194 |
} |
| 195 |
} |
| 196 |
|
| 197 |
// TestGatherDeclarativeValidationMismatches tests all mismatch |
| 198 |
// scenarios across imperative and declarative errors for |
| 199 |
// the gatherDeclarativeValidationMismatches function |
| 200 |
func TestGatherDeclarativeValidationMismatches(t *testing.T) { |
| 201 |
replicasPath := field.NewPath("spec").Child("replicas") |
| 202 |
minReadySecondsPath := field.NewPath("spec").Child("minReadySeconds") |
| 203 |
selectorPath := field.NewPath("spec").Child("selector") |
| 204 |
|
| 205 |
errA := field.Invalid(replicasPath, nil, "regular error A") |
| 206 |
errB := field.Invalid(minReadySecondsPath, -1, "covered error B").WithOrigin("minimum") |
| 207 |
coveredErrB := field.Invalid(minReadySecondsPath, -1, "covered error B").WithOrigin("minimum") |
| 208 |
errBWithDiffDetail := field.Invalid(minReadySecondsPath, -1, "covered error B - different detail").WithOrigin("minimum") |
| 209 |
coveredErrB.CoveredByDeclarative = true |
| 210 |
errC := field.Invalid(replicasPath, nil, "covered error C").WithOrigin("minimum") |
| 211 |
coveredErrC := field.Invalid(replicasPath, nil, "covered error C").WithOrigin("minimum") |
| 212 |
coveredErrC.CoveredByDeclarative = true |
| 213 |
errCWithDiffOrigin := field.Invalid(replicasPath, nil, "covered error C").WithOrigin("maximum") |
| 214 |
errD := field.Invalid(selectorPath, nil, "regular error D") |
| 215 |
|
| 216 |
testCases := []struct { |
| 217 |
name string |
| 218 |
imperativeErrors field.ErrorList |
| 219 |
declarativeErrors field.ErrorList |
| 220 |
takeover bool |
| 221 |
expectMismatches bool |
| 222 |
expectDetailsContaining []string |
| 223 |
}{ |
| 224 |
{ |
| 225 |
name: "Declarative and imperative return 0 errors - no mismatch", |
| 226 |
imperativeErrors: field.ErrorList{}, |
| 227 |
declarativeErrors: field.ErrorList{}, |
| 228 |
takeover: false, |
| 229 |
expectMismatches: false, |
| 230 |
expectDetailsContaining: []string{}, |
| 231 |
}, |
| 232 |
{ |
| 233 |
name: "Declarative returns multiple errors with different origins, errors match - no mismatch", |
| 234 |
imperativeErrors: field.ErrorList{ |
| 235 |
errA, |
| 236 |
coveredErrB, |
| 237 |
coveredErrC, |
| 238 |
errD, |
| 239 |
}, |
| 240 |
declarativeErrors: field.ErrorList{ |
| 241 |
errB, |
| 242 |
errC, |
| 243 |
}, |
| 244 |
takeover: false, |
| 245 |
expectMismatches: false, |
| 246 |
expectDetailsContaining: []string{}, |
| 247 |
}, |
| 248 |
{ |
| 249 |
name: "Declarative returns multiple errors with different origins, errors don't match - mismatch case", |
| 250 |
imperativeErrors: field.ErrorList{ |
| 251 |
errA, |
| 252 |
coveredErrB, |
| 253 |
coveredErrC, |
| 254 |
}, |
| 255 |
declarativeErrors: field.ErrorList{ |
| 256 |
errB, |
| 257 |
errCWithDiffOrigin, |
| 258 |
}, |
| 259 |
takeover: true, |
| 260 |
expectMismatches: true, |
| 261 |
expectDetailsContaining: []string{ |
| 262 |
"Unexpected difference between hand written validation and declarative validation error results", |
| 263 |
"unmatched error(s) found", |
| 264 |
"extra error(s) found", |
| 265 |
"replicas", |
| 266 |
"Consider disabling the DeclarativeValidationTakeover feature gate to keep data persisted in etcd consistent with prior versions of Kubernetes", |
| 267 |
}, |
| 268 |
}, |
| 269 |
{ |
| 270 |
name: "Declarative and imperative return exactly 1 error, errors match - no mismatch", |
| 271 |
imperativeErrors: field.ErrorList{ |
| 272 |
coveredErrB, |
| 273 |
}, |
| 274 |
declarativeErrors: field.ErrorList{ |
| 275 |
errB, |
| 276 |
}, |
| 277 |
takeover: false, |
| 278 |
expectMismatches: false, |
| 279 |
expectDetailsContaining: []string{}, |
| 280 |
}, |
| 281 |
{ |
| 282 |
name: "Declarative and imperative exactly 1 error, errors don't match - mismatch", |
| 283 |
imperativeErrors: field.ErrorList{ |
| 284 |
coveredErrB, |
| 285 |
}, |
| 286 |
declarativeErrors: field.ErrorList{ |
| 287 |
errC, |
| 288 |
}, |
| 289 |
takeover: false, |
| 290 |
expectMismatches: true, |
| 291 |
expectDetailsContaining: []string{ |
| 292 |
"Unexpected difference between hand written validation and declarative validation error results", |
| 293 |
"unmatched error(s) found", |
| 294 |
"minReadySeconds", |
| 295 |
"extra error(s) found", |
| 296 |
"replicas", |
| 297 |
"This difference should not affect system operation since hand written validation is authoritative", |
| 298 |
}, |
| 299 |
}, |
| 300 |
{ |
| 301 |
name: "Declarative returns 0 errors, imperative returns 1 covered error - mismatch", |
| 302 |
imperativeErrors: field.ErrorList{ |
| 303 |
coveredErrB, |
| 304 |
}, |
| 305 |
declarativeErrors: field.ErrorList{}, |
| 306 |
takeover: true, |
| 307 |
expectMismatches: true, |
| 308 |
expectDetailsContaining: []string{ |
| 309 |
"Unexpected difference between hand written validation and declarative validation error results", |
| 310 |
"unmatched error(s) found", |
| 311 |
"minReadySeconds", |
| 312 |
"Consider disabling the DeclarativeValidationTakeover feature gate to keep data persisted in etcd consistent with prior versions of Kubernetes", |
| 313 |
}, |
| 314 |
}, |
| 315 |
{ |
| 316 |
name: "Declarative returns 0 errors, imperative returns 1 uncovered error - no mismatch", |
| 317 |
imperativeErrors: field.ErrorList{ |
| 318 |
errB, |
| 319 |
}, |
| 320 |
declarativeErrors: field.ErrorList{}, |
| 321 |
takeover: false, |
| 322 |
expectMismatches: false, |
| 323 |
expectDetailsContaining: []string{}, |
| 324 |
}, |
| 325 |
{ |
| 326 |
name: "Declarative returns 1 error, imperative returns 0 error - mismatch", |
| 327 |
imperativeErrors: field.ErrorList{}, |
| 328 |
declarativeErrors: field.ErrorList{ |
| 329 |
errB, |
| 330 |
}, |
| 331 |
takeover: false, |
| 332 |
expectMismatches: true, |
| 333 |
expectDetailsContaining: []string{ |
| 334 |
"Unexpected difference between hand written validation and declarative validation error results", |
| 335 |
"extra error(s) found", |
| 336 |
"minReadySeconds", |
| 337 |
"This difference should not affect system operation since hand written validation is authoritative", |
| 338 |
}, |
| 339 |
}, |
| 340 |
{ |
| 341 |
name: "Declarative returns 1 error, imperative returns 3 matching errors - no mismatch", |
| 342 |
imperativeErrors: field.ErrorList{ |
| 343 |
coveredErrB, |
| 344 |
}, |
| 345 |
declarativeErrors: field.ErrorList{ |
| 346 |
errB, |
| 347 |
errB, |
| 348 |
errBWithDiffDetail, |
| 349 |
}, |
| 350 |
takeover: false, |
| 351 |
expectMismatches: false, |
| 352 |
expectDetailsContaining: []string{}, |
| 353 |
}, |
| 354 |
} |
| 355 |
|
| 356 |
for _, tc := range testCases { |
| 357 |
t.Run(tc.name, func(t *testing.T) { |
| 358 |
details := gatherDeclarativeValidationMismatches(tc.imperativeErrors, tc.declarativeErrors, tc.takeover) |
| 359 |
// Check if mismatches were found if expected |
| 360 |
if tc.expectMismatches && len(details) == 0 { |
| 361 |
t.Errorf("Expected mismatches but got none") |
| 362 |
} |
| 363 |
// Check if details contain expected text |
| 364 |
detailsStr := strings.Join(details, " ") |
| 365 |
for _, expectedContent := range tc.expectDetailsContaining { |
| 366 |
if !strings.Contains(detailsStr, expectedContent) { |
| 367 |
t.Errorf("Expected details to contain: %q, but they didn't.\nDetails were:\n%s", |
| 368 |
expectedContent, strings.Join(details, "\n")) |
| 369 |
} |
| 370 |
} |
| 371 |
// If we don't expect any details, make sure none provided |
| 372 |
if len(tc.expectDetailsContaining) == 0 && len(details) > 0 { |
| 373 |
t.Errorf("Expected no details, but got %d details: %v", len(details), details) |
| 374 |
} |
| 375 |
}) |
| 376 |
} |
| 377 |
} |
| 378 |
|
| 379 |
// TestCompareDeclarativeErrorsAndEmitMismatches tests expected |
| 380 |
// logging of mismatch information given match & mismatch error conditions. |
| 381 |
func TestCompareDeclarativeErrorsAndEmitMismatches(t *testing.T) { |
| 382 |
replicasPath := field.NewPath("spec").Child("replicas") |
| 383 |
minReadySecondsPath := field.NewPath("spec").Child("minReadySeconds") |
| 384 |
|
| 385 |
errA := field.Invalid(replicasPath, nil, "regular error A") |
| 386 |
errB := field.Invalid(minReadySecondsPath, -1, "covered error B").WithOrigin("minimum") |
| 387 |
coveredErrB := field.Invalid(minReadySecondsPath, -1, "covered error B").WithOrigin("minimum") |
| 388 |
coveredErrB.CoveredByDeclarative = true |
| 389 |
|
| 390 |
testCases := []struct { |
| 391 |
name string |
| 392 |
imperativeErrs field.ErrorList |
| 393 |
declarativeErrs field.ErrorList |
| 394 |
takeover bool |
| 395 |
expectLogs bool |
| 396 |
expectedRegex string |
| 397 |
}{ |
| 398 |
{ |
| 399 |
name: "mismatched errors, log info", |
| 400 |
imperativeErrs: field.ErrorList{coveredErrB}, |
| 401 |
declarativeErrs: field.ErrorList{errA}, |
| 402 |
takeover: true, |
| 403 |
expectLogs: true, |
| 404 |
// logs have a prefix of the form - E0309 21:05:33.865030 1926106 validate.go:199] |
| 405 |
expectedRegex: "E.*Unexpected difference between hand written validation and declarative validation error results.*Consider disabling the DeclarativeValidationTakeover feature gate to keep data persisted in etcd consistent with prior versions of Kubernetes", |
| 406 |
}, |
| 407 |
{ |
| 408 |
name: "matching errors, don't log info", |
| 409 |
imperativeErrs: field.ErrorList{coveredErrB}, |
| 410 |
declarativeErrs: field.ErrorList{errB}, |
| 411 |
takeover: true, |
| 412 |
expectLogs: false, |
| 413 |
expectedRegex: "", |
| 414 |
}, |
| 415 |
} |
| 416 |
|
| 417 |
for _, tc := range testCases { |
| 418 |
t.Run(tc.name, func(t *testing.T) { |
| 419 |
var buf bytes.Buffer |
| 420 |
klog.SetOutput(&buf) |
| 421 |
klog.LogToStderr(false) |
| 422 |
defer klog.LogToStderr(true) |
| 423 |
ctx := context.Background() |
| 424 |
|
| 425 |
CompareDeclarativeErrorsAndEmitMismatches(ctx, tc.imperativeErrs, tc.declarativeErrs, tc.takeover) |
| 426 |
|
| 427 |
klog.Flush() |
| 428 |
logOutput := buf.String() |
| 429 |
|
| 430 |
if tc.expectLogs { |
| 431 |
matched, err := regexp.MatchString(tc.expectedRegex, logOutput) |
| 432 |
if err != nil { |
| 433 |
t.Fatalf("Bad regex: %v", err) |
| 434 |
} |
| 435 |
if !matched { |
| 436 |
t.Errorf("Expected log output to match %q, but got:\n%s", tc.expectedRegex, logOutput) |
| 437 |
} |
| 438 |
} else if len(logOutput) > 0 { |
| 439 |
t.Errorf("Expected no mismatch logs, but found: %s", logOutput) |
| 440 |
} |
| 441 |
}) |
| 442 |
} |
| 443 |
} |
| 444 |
|
| 445 |
func TestWithRecover(t *testing.T) { |
| 446 |
ctx := context.Background() |
| 447 |
scheme := runtime.NewScheme() |
| 448 |
options := sets.New[string]() |
| 449 |
obj := &runtime.Unknown{} |
| 450 |
|
| 451 |
testCases := []struct { |
| 452 |
name string |
| 453 |
validateFn func(context.Context, sets.Set[string], *runtime.Scheme, runtime.Object) field.ErrorList |
| 454 |
takeoverEnabled bool |
| 455 |
wantErrs field.ErrorList |
| 456 |
expectLogRegex string |
| 457 |
}{ |
| 458 |
{ |
| 459 |
name: "no panic", |
| 460 |
validateFn: func(context.Context, sets.Set[string], *runtime.Scheme, runtime.Object) field.ErrorList { |
| 461 |
return field.ErrorList{ |
| 462 |
field.Invalid(field.NewPath("field"), "value", "reason"), |
| 463 |
} |
| 464 |
}, |
| 465 |
takeoverEnabled: false, |
| 466 |
wantErrs: field.ErrorList{ |
| 467 |
field.Invalid(field.NewPath("field"), "value", "reason"), |
| 468 |
}, |
| 469 |
expectLogRegex: "", |
| 470 |
}, |
| 471 |
{ |
| 472 |
name: "panic with takeover disabled", |
| 473 |
validateFn: func(context.Context, sets.Set[string], *runtime.Scheme, runtime.Object) field.ErrorList { |
| 474 |
panic("test panic") |
| 475 |
}, |
| 476 |
takeoverEnabled: false, |
| 477 |
wantErrs: nil, |
| 478 |
// logs have a prefix of the form - E0309 21:05:33.865030 1926106 validate.go:199] |
| 479 |
expectLogRegex: "E.*panic during declarative validation: test panic", |
| 480 |
}, |
| 481 |
{ |
| 482 |
name: "panic with takeover enabled", |
| 483 |
validateFn: func(context.Context, sets.Set[string], *runtime.Scheme, runtime.Object) field.ErrorList { |
| 484 |
panic("test panic") |
| 485 |
}, |
| 486 |
takeoverEnabled: true, |
| 487 |
wantErrs: field.ErrorList{ |
| 488 |
field.InternalError(nil, fmt.Errorf("panic during declarative validation: test panic")), |
| 489 |
}, |
| 490 |
expectLogRegex: "", |
| 491 |
}, |
| 492 |
{ |
| 493 |
name: "nil return, no panic", |
| 494 |
validateFn: func(context.Context, sets.Set[string], *runtime.Scheme, runtime.Object) field.ErrorList { |
| 495 |
return nil |
| 496 |
}, |
| 497 |
takeoverEnabled: false, |
| 498 |
wantErrs: nil, |
| 499 |
expectLogRegex: "", |
| 500 |
}, |
| 501 |
} |
| 502 |
|
| 503 |
for _, tc := range testCases { |
| 504 |
t.Run(tc.name, func(t *testing.T) { |
| 505 |
var buf bytes.Buffer |
| 506 |
klog.SetOutput(&buf) |
| 507 |
klog.LogToStderr(false) |
| 508 |
defer klog.LogToStderr(true) |
| 509 |
|
| 510 |
// Pass the takeover flag to panicSafeValidateFunc instead of relying on the feature gate |
| 511 |
wrapped := panicSafeValidateFunc(tc.validateFn, tc.takeoverEnabled) |
| 512 |
gotErrs := wrapped(ctx, options, scheme, obj) |
| 513 |
|
| 514 |
klog.Flush() |
| 515 |
logOutput := buf.String() |
| 516 |
|
| 517 |
// Compare gotErrs vs. tc.wantErrs |
| 518 |
if !equalErrorLists(gotErrs, tc.wantErrs) { |
| 519 |
t.Errorf("panicSafeValidateFunc() gotErrs = %#v, want %#v", gotErrs, tc.wantErrs) |
| 520 |
} |
| 521 |
|
| 522 |
// Check logs if needed |
| 523 |
if tc.expectLogRegex != "" { |
| 524 |
matched, err := regexp.MatchString(tc.expectLogRegex, logOutput) |
| 525 |
if err != nil { |
| 526 |
t.Fatalf("Bad regex: %v", err) |
| 527 |
} |
| 528 |
if !matched { |
| 529 |
t.Errorf("Expected log output %q, but got:\n%s", tc.expectLogRegex, logOutput) |
| 530 |
} |
| 531 |
} else if strings.Contains(logOutput, "panic during declarative validation") { |
| 532 |
t.Errorf("Unexpected panic log found: %s", logOutput) |
| 533 |
} |
| 534 |
}) |
| 535 |
} |
| 536 |
} |
| 537 |
|
| 538 |
func TestWithRecoverUpdate(t *testing.T) { |
| 539 |
ctx := context.Background() |
| 540 |
scheme := runtime.NewScheme() |
| 541 |
options := sets.New[string]() |
| 542 |
obj := &runtime.Unknown{} |
| 543 |
oldObj := &runtime.Unknown{} |
| 544 |
|
| 545 |
testCases := []struct { |
| 546 |
name string |
| 547 |
validateFn func(context.Context, sets.Set[string], *runtime.Scheme, runtime.Object, runtime.Object) field.ErrorList |
| 548 |
takeoverEnabled bool |
| 549 |
wantErrs field.ErrorList |
| 550 |
expectLogRegex string |
| 551 |
}{ |
| 552 |
{ |
| 553 |
name: "no panic", |
| 554 |
validateFn: func(context.Context, sets.Set[string], *runtime.Scheme, runtime.Object, runtime.Object) field.ErrorList { |
| 555 |
return field.ErrorList{ |
| 556 |
field.Invalid(field.NewPath("field"), "value", "reason"), |
| 557 |
} |
| 558 |
}, |
| 559 |
takeoverEnabled: false, |
| 560 |
wantErrs: field.ErrorList{ |
| 561 |
field.Invalid(field.NewPath("field"), "value", "reason"), |
| 562 |
}, |
| 563 |
expectLogRegex: "", |
| 564 |
}, |
| 565 |
{ |
| 566 |
name: "panic with takeover disabled", |
| 567 |
validateFn: func(context.Context, sets.Set[string], *runtime.Scheme, runtime.Object, runtime.Object) field.ErrorList { |
| 568 |
panic("test update panic") |
| 569 |
}, |
| 570 |
takeoverEnabled: false, |
| 571 |
wantErrs: nil, |
| 572 |
// logs have a prefix of the form - E0309 21:05:33.865030 1926106 validate.go:199] |
| 573 |
expectLogRegex: "E.*panic during declarative validation: test update panic", |
| 574 |
}, |
| 575 |
{ |
| 576 |
name: "panic with takeover enabled", |
| 577 |
validateFn: func(context.Context, sets.Set[string], *runtime.Scheme, runtime.Object, runtime.Object) field.ErrorList { |
| 578 |
panic("test update panic") |
| 579 |
}, |
| 580 |
takeoverEnabled: true, |
| 581 |
wantErrs: field.ErrorList{ |
| 582 |
field.InternalError(nil, fmt.Errorf("panic during declarative validation: test update panic")), |
| 583 |
}, |
| 584 |
expectLogRegex: "", |
| 585 |
}, |
| 586 |
{ |
| 587 |
name: "nil return, no panic", |
| 588 |
validateFn: func(context.Context, sets.Set[string], *runtime.Scheme, runtime.Object, runtime.Object) field.ErrorList { |
| 589 |
return nil |
| 590 |
}, |
| 591 |
takeoverEnabled: false, |
| 592 |
wantErrs: nil, |
| 593 |
expectLogRegex: "", |
| 594 |
}, |
| 595 |
} |
| 596 |
|
| 597 |
for _, tc := range testCases { |
| 598 |
t.Run(tc.name, func(t *testing.T) { |
| 599 |
var buf bytes.Buffer |
| 600 |
klog.SetOutput(&buf) |
| 601 |
klog.LogToStderr(false) |
| 602 |
defer klog.LogToStderr(true) |
| 603 |
|
| 604 |
// Pass the takeover flag to panicSafeValidateUpdateFunc instead of relying on the feature gate |
| 605 |
wrapped := panicSafeValidateUpdateFunc(tc.validateFn, tc.takeoverEnabled) |
| 606 |
gotErrs := wrapped(ctx, options, scheme, obj, oldObj) |
| 607 |
|
| 608 |
klog.Flush() |
| 609 |
logOutput := buf.String() |
| 610 |
|
| 611 |
// Compare gotErrs with wantErrs |
| 612 |
if !equalErrorLists(gotErrs, tc.wantErrs) { |
| 613 |
t.Errorf("panicSafeValidateUpdateFunc() gotErrs = %#v, want %#v", gotErrs, tc.wantErrs) |
| 614 |
} |
| 615 |
|
| 616 |
// Verify log output |
| 617 |
if tc.expectLogRegex != "" { |
| 618 |
matched, err := regexp.MatchString(tc.expectLogRegex, logOutput) |
| 619 |
if err != nil { |
| 620 |
t.Fatalf("Bad regex: %v", err) |
| 621 |
} |
| 622 |
if !matched { |
| 623 |
t.Errorf("Expected log pattern %q, but got:\n%s", tc.expectLogRegex, logOutput) |
| 624 |
} |
| 625 |
} else if strings.Contains(logOutput, "panic during declarative validation") { |
| 626 |
t.Errorf("Unexpected panic log found: %s", logOutput) |
| 627 |
} |
| 628 |
}) |
| 629 |
} |
| 630 |
} |
| 631 |
|
| 632 |
func TestValidateDeclarativelyWithRecovery(t *testing.T) { |
| 633 |
ctx := context.Background() |
| 634 |
scheme := runtime.NewScheme() |
| 635 |
options := sets.New[string]() |
| 636 |
obj := &runtime.Unknown{} |
| 637 |
|
| 638 |
// Simple test for the ValidateDeclarativelyWithRecovery function |
| 639 |
t.Run("with takeover disabled", func(t *testing.T) { |
| 640 |
errs := ValidateDeclarativelyWithRecovery(ctx, options, scheme, obj, false) |
| 641 |
if errs == nil { |
| 642 |
// This is expected to error since the request info is missing |
| 643 |
t.Errorf("Expected errors but got nil") |
| 644 |
} |
| 645 |
}) |
| 646 |
|
| 647 |
t.Run("with takeover enabled", func(t *testing.T) { |
| 648 |
errs := ValidateDeclarativelyWithRecovery(ctx, options, scheme, obj, true) |
| 649 |
if errs == nil { |
| 650 |
// This is expected to error since the request info is missing |
| 651 |
t.Errorf("Expected errors but got nil") |
| 652 |
} |
| 653 |
}) |
| 654 |
} |
| 655 |
|
| 656 |
func TestValidateUpdateDeclarativelyWithRecovery(t *testing.T) { |
| 657 |
ctx := context.Background() |
| 658 |
scheme := runtime.NewScheme() |
| 659 |
options := sets.New[string]() |
| 660 |
obj := &runtime.Unknown{} |
| 661 |
oldObj := &runtime.Unknown{} |
| 662 |
|
| 663 |
// Simple test for the ValidateUpdateDeclarativelyWithRecovery function |
| 664 |
t.Run("with takeover disabled", func(t *testing.T) { |
| 665 |
errs := ValidateUpdateDeclarativelyWithRecovery(ctx, options, scheme, obj, oldObj, false) |
| 666 |
if errs == nil { |
| 667 |
// This is expected to error since the request info is missing |
| 668 |
t.Errorf("Expected errors but got nil") |
| 669 |
} |
| 670 |
}) |
| 671 |
|
| 672 |
t.Run("with takeover enabled", func(t *testing.T) { |
| 673 |
errs := ValidateUpdateDeclarativelyWithRecovery(ctx, options, scheme, obj, oldObj, true) |
| 674 |
if errs == nil { |
| 675 |
// This is expected to error since the request info is missing |
| 676 |
t.Errorf("Expected errors but got nil") |
| 677 |
} |
| 678 |
}) |
| 679 |
} |
| 680 |
|
| 681 |
func equalErrorLists(a, b field.ErrorList) bool { |
| 682 |
// If both are nil, consider them equal |
| 683 |
if a == nil && b == nil { |
| 684 |
return true |
| 685 |
} |
| 686 |
// If one is nil and the other not, they're different |
| 687 |
if (a == nil && b != nil) || (a != nil && b == nil) { |
| 688 |
return false |
| 689 |
} |
| 690 |
// Both non-nil: do a normal DeepEqual |
| 691 |
return reflect.DeepEqual(a, b) |
| 692 |
} |