| 1 |
/* |
| 2 |
Copyright 2016 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 validation |
| 18 |
|
| 19 |
import ( |
| 20 |
"fmt" |
| 21 |
"strings" |
| 22 |
"testing" |
| 23 |
|
| 24 |
"github.com/google/go-cmp/cmp" |
| 25 |
|
| 26 |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" |
| 27 |
"k8s.io/apimachinery/pkg/types" |
| 28 |
"k8s.io/apimachinery/pkg/util/validation/field" |
| 29 |
|
| 30 |
"k8s.io/utils/ptr" |
| 31 |
) |
| 32 |
|
| 33 |
func TestValidateLabels(t *testing.T) { |
| 34 |
successCases := []map[string]string{ |
| 35 |
{"simple": "bar"}, |
| 36 |
{"now-with-dashes": "bar"}, |
| 37 |
{"1-starts-with-num": "bar"}, |
| 38 |
{"1234": "bar"}, |
| 39 |
{"simple/simple": "bar"}, |
| 40 |
{"now-with-dashes/simple": "bar"}, |
| 41 |
{"now-with-dashes/now-with-dashes": "bar"}, |
| 42 |
{"now.with.dots/simple": "bar"}, |
| 43 |
{"now-with.dashes-and.dots/simple": "bar"}, |
| 44 |
{"1-num.2-num/3-num": "bar"}, |
| 45 |
{"1234/5678": "bar"}, |
| 46 |
{"1.2.3.4/5678": "bar"}, |
| 47 |
{"UpperCaseAreOK123": "bar"}, |
| 48 |
{"goodvalue": "123_-.BaR"}, |
| 49 |
} |
| 50 |
for i := range successCases { |
| 51 |
errs := ValidateLabels(successCases[i], field.NewPath("field")) |
| 52 |
if len(errs) != 0 { |
| 53 |
t.Errorf("case[%d] expected success, got %#v", i, errs) |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
namePartErrMsg := "name part must consist of" |
| 58 |
nameErrMsg := "a qualified name must consist of" |
| 59 |
labelErrMsg := "a valid label must be an empty string or consist of" |
| 60 |
maxLengthErrMsg := "must be no more than" |
| 61 |
|
| 62 |
labelNameErrorCases := []struct { |
| 63 |
labels map[string]string |
| 64 |
expect string |
| 65 |
}{ |
| 66 |
{map[string]string{"nospecialchars^=@": "bar"}, namePartErrMsg}, |
| 67 |
{map[string]string{"cantendwithadash-": "bar"}, namePartErrMsg}, |
| 68 |
{map[string]string{"only/one/slash": "bar"}, nameErrMsg}, |
| 69 |
{map[string]string{strings.Repeat("a", 254): "bar"}, maxLengthErrMsg}, |
| 70 |
} |
| 71 |
for i := range labelNameErrorCases { |
| 72 |
errs := ValidateLabels(labelNameErrorCases[i].labels, field.NewPath("field")) |
| 73 |
if len(errs) != 1 { |
| 74 |
t.Errorf("case[%d]: expected failure", i) |
| 75 |
} else { |
| 76 |
if !strings.Contains(errs[0].Detail, labelNameErrorCases[i].expect) { |
| 77 |
t.Errorf("case[%d]: error details do not include %q: %q", i, labelNameErrorCases[i].expect, errs[0].Detail) |
| 78 |
} |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
labelValueErrorCases := []struct { |
| 83 |
labels map[string]string |
| 84 |
expect string |
| 85 |
}{ |
| 86 |
{map[string]string{"toolongvalue": strings.Repeat("a", 64)}, maxLengthErrMsg}, |
| 87 |
{map[string]string{"backslashesinvalue": "some\\bad\\value"}, labelErrMsg}, |
| 88 |
{map[string]string{"nocommasallowed": "bad,value"}, labelErrMsg}, |
| 89 |
{map[string]string{"strangecharsinvalue": "?#$notsogood"}, labelErrMsg}, |
| 90 |
} |
| 91 |
for i := range labelValueErrorCases { |
| 92 |
errs := ValidateLabels(labelValueErrorCases[i].labels, field.NewPath("field")) |
| 93 |
if len(errs) != 1 { |
| 94 |
t.Errorf("case[%d]: expected failure", i) |
| 95 |
} else { |
| 96 |
if !strings.Contains(errs[0].Detail, labelValueErrorCases[i].expect) { |
| 97 |
t.Errorf("case[%d]: error details do not include %q: %q", i, labelValueErrorCases[i].expect, errs[0].Detail) |
| 98 |
} |
| 99 |
} |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
func TestValidDryRun(t *testing.T) { |
| 104 |
tests := [][]string{ |
| 105 |
{}, |
| 106 |
{"All"}, |
| 107 |
{"All", "All"}, |
| 108 |
} |
| 109 |
|
| 110 |
for _, test := range tests { |
| 111 |
t.Run(fmt.Sprintf("%v", test), func(t *testing.T) { |
| 112 |
if errs := ValidateDryRun(field.NewPath("dryRun"), test); len(errs) != 0 { |
| 113 |
t.Errorf("%v should be a valid dry-run value: %v", test, errs) |
| 114 |
} |
| 115 |
}) |
| 116 |
} |
| 117 |
} |
| 118 |
|
| 119 |
func TestInvalidDryRun(t *testing.T) { |
| 120 |
tests := [][]string{ |
| 121 |
{"False"}, |
| 122 |
{"All", "False"}, |
| 123 |
} |
| 124 |
|
| 125 |
for _, test := range tests { |
| 126 |
t.Run(fmt.Sprintf("%v", test), func(t *testing.T) { |
| 127 |
if len(ValidateDryRun(field.NewPath("dryRun"), test)) == 0 { |
| 128 |
t.Errorf("%v shouldn't be a valid dry-run value", test) |
| 129 |
} |
| 130 |
}) |
| 131 |
} |
| 132 |
|
| 133 |
} |
| 134 |
|
| 135 |
func boolPtr(b bool) *bool { |
| 136 |
return &b |
| 137 |
} |
| 138 |
|
| 139 |
func TestValidateDeleteOptionsWithIgnoreStoreReadError(t *testing.T) { |
| 140 |
fieldPath := field.NewPath("ignoreStoreReadErrorWithClusterBreakingPotential") |
| 141 |
tests := []struct { |
| 142 |
name string |
| 143 |
opts metav1.DeleteOptions |
| 144 |
expectedErrors field.ErrorList |
| 145 |
}{ |
| 146 |
{ |
| 147 |
name: "option is nil", |
| 148 |
opts: metav1.DeleteOptions{ |
| 149 |
IgnoreStoreReadErrorWithClusterBreakingPotential: nil, |
| 150 |
DryRun: []string{"All"}, |
| 151 |
}, |
| 152 |
expectedErrors: field.ErrorList{}, |
| 153 |
}, |
| 154 |
{ |
| 155 |
name: "option is false, PropagationPolicy is set", |
| 156 |
opts: metav1.DeleteOptions{ |
| 157 |
IgnoreStoreReadErrorWithClusterBreakingPotential: ptr.To[bool](false), |
| 158 |
DryRun: []string{"All"}, |
| 159 |
PropagationPolicy: ptr.To[metav1.DeletionPropagation](metav1.DeletePropagationBackground), |
| 160 |
GracePeriodSeconds: ptr.To[int64](0), |
| 161 |
Preconditions: &metav1.Preconditions{}, |
| 162 |
}, |
| 163 |
expectedErrors: field.ErrorList{}, |
| 164 |
}, |
| 165 |
{ |
| 166 |
name: "option is false, OrphanDependents is set", |
| 167 |
opts: metav1.DeleteOptions{ |
| 168 |
IgnoreStoreReadErrorWithClusterBreakingPotential: ptr.To[bool](false), |
| 169 |
DryRun: []string{"All"}, |
| 170 |
//nolint:staticcheck // until it's being removed |
| 171 |
OrphanDependents: ptr.To[bool](true), |
| 172 |
GracePeriodSeconds: ptr.To[int64](0), |
| 173 |
Preconditions: &metav1.Preconditions{}, |
| 174 |
}, |
| 175 |
expectedErrors: field.ErrorList{}, |
| 176 |
}, |
| 177 |
{ |
| 178 |
name: "option is true, PropagationPolicy is set", |
| 179 |
opts: metav1.DeleteOptions{ |
| 180 |
IgnoreStoreReadErrorWithClusterBreakingPotential: ptr.To[bool](true), |
| 181 |
DryRun: []string{"All"}, |
| 182 |
PropagationPolicy: ptr.To[metav1.DeletionPropagation](metav1.DeletePropagationBackground), |
| 183 |
GracePeriodSeconds: ptr.To[int64](0), |
| 184 |
Preconditions: &metav1.Preconditions{}, |
| 185 |
}, |
| 186 |
expectedErrors: field.ErrorList{ |
| 187 |
field.Invalid(fieldPath, true, "cannot be set together with .dryRun"), |
| 188 |
field.Invalid(fieldPath, true, "cannot be set together with .propagationPolicy"), |
| 189 |
field.Invalid(fieldPath, true, "cannot be set together with .gracePeriodSeconds"), |
| 190 |
field.Invalid(fieldPath, true, "cannot be set together with .preconditions"), |
| 191 |
}, |
| 192 |
}, |
| 193 |
{ |
| 194 |
name: "option is true, OrphanDependents is set", |
| 195 |
opts: metav1.DeleteOptions{ |
| 196 |
IgnoreStoreReadErrorWithClusterBreakingPotential: ptr.To[bool](true), |
| 197 |
DryRun: []string{"All"}, |
| 198 |
//nolint:staticcheck // until it's being removed |
| 199 |
OrphanDependents: ptr.To[bool](true), |
| 200 |
GracePeriodSeconds: ptr.To[int64](0), |
| 201 |
Preconditions: &metav1.Preconditions{}, |
| 202 |
}, |
| 203 |
expectedErrors: field.ErrorList{ |
| 204 |
field.Invalid(fieldPath, true, "cannot be set together with .dryRun"), |
| 205 |
field.Invalid(fieldPath, true, "cannot be set together with .orphanDependents"), |
| 206 |
field.Invalid(fieldPath, true, "cannot be set together with .gracePeriodSeconds"), |
| 207 |
field.Invalid(fieldPath, true, "cannot be set together with .preconditions"), |
| 208 |
}, |
| 209 |
}, |
| 210 |
{ |
| 211 |
name: "option is true, no other option is set", |
| 212 |
opts: metav1.DeleteOptions{ |
| 213 |
IgnoreStoreReadErrorWithClusterBreakingPotential: ptr.To[bool](false), |
| 214 |
}, |
| 215 |
expectedErrors: field.ErrorList{}, |
| 216 |
}, |
| 217 |
} |
| 218 |
|
| 219 |
for _, test := range tests { |
| 220 |
t.Run(test.name, func(t *testing.T) { |
| 221 |
errGot := ValidateDeleteOptions(&test.opts) |
| 222 |
if !cmp.Equal(test.expectedErrors, errGot) { |
| 223 |
t.Errorf("expected error(s) to match, diff: %s", cmp.Diff(test.expectedErrors, errGot)) |
| 224 |
} |
| 225 |
}) |
| 226 |
} |
| 227 |
} |
| 228 |
|
| 229 |
func TestValidPatchOptions(t *testing.T) { |
| 230 |
tests := []struct { |
| 231 |
opts metav1.PatchOptions |
| 232 |
patchType types.PatchType |
| 233 |
}{{ |
| 234 |
opts: metav1.PatchOptions{ |
| 235 |
Force: boolPtr(true), |
| 236 |
FieldManager: "kubectl", |
| 237 |
}, |
| 238 |
patchType: types.ApplyYAMLPatchType, |
| 239 |
}, { |
| 240 |
opts: metav1.PatchOptions{ |
| 241 |
FieldManager: "kubectl", |
| 242 |
}, |
| 243 |
patchType: types.ApplyYAMLPatchType, |
| 244 |
}, { |
| 245 |
opts: metav1.PatchOptions{ |
| 246 |
Force: boolPtr(true), |
| 247 |
FieldManager: "kubectl", |
| 248 |
}, |
| 249 |
patchType: types.ApplyCBORPatchType, |
| 250 |
}, { |
| 251 |
opts: metav1.PatchOptions{ |
| 252 |
FieldManager: "kubectl", |
| 253 |
}, |
| 254 |
patchType: types.ApplyCBORPatchType, |
| 255 |
}, { |
| 256 |
opts: metav1.PatchOptions{}, |
| 257 |
patchType: types.MergePatchType, |
| 258 |
}, { |
| 259 |
opts: metav1.PatchOptions{ |
| 260 |
FieldManager: "patcher", |
| 261 |
}, |
| 262 |
patchType: types.MergePatchType, |
| 263 |
}} |
| 264 |
|
| 265 |
for _, test := range tests { |
| 266 |
t.Run(fmt.Sprintf("%v", test.opts), func(t *testing.T) { |
| 267 |
errs := ValidatePatchOptions(&test.opts, test.patchType) |
| 268 |
if len(errs) != 0 { |
| 269 |
t.Fatalf("Expected no failures, got: %v", errs) |
| 270 |
} |
| 271 |
}) |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
func TestInvalidPatchOptions(t *testing.T) { |
| 276 |
tests := []struct { |
| 277 |
opts metav1.PatchOptions |
| 278 |
patchType types.PatchType |
| 279 |
}{ |
| 280 |
// missing manager |
| 281 |
{ |
| 282 |
opts: metav1.PatchOptions{}, |
| 283 |
patchType: types.ApplyYAMLPatchType, |
| 284 |
}, |
| 285 |
// missing manager |
| 286 |
{ |
| 287 |
opts: metav1.PatchOptions{}, |
| 288 |
patchType: types.ApplyCBORPatchType, |
| 289 |
}, |
| 290 |
// force on non-apply |
| 291 |
{ |
| 292 |
opts: metav1.PatchOptions{ |
| 293 |
Force: boolPtr(true), |
| 294 |
}, |
| 295 |
patchType: types.MergePatchType, |
| 296 |
}, |
| 297 |
// manager and force on non-apply |
| 298 |
{ |
| 299 |
opts: metav1.PatchOptions{ |
| 300 |
FieldManager: "kubectl", |
| 301 |
Force: boolPtr(false), |
| 302 |
}, |
| 303 |
patchType: types.MergePatchType, |
| 304 |
}, |
| 305 |
} |
| 306 |
|
| 307 |
for _, test := range tests { |
| 308 |
t.Run(fmt.Sprintf("%v", test.opts), func(t *testing.T) { |
| 309 |
errs := ValidatePatchOptions(&test.opts, test.patchType) |
| 310 |
if len(errs) == 0 { |
| 311 |
t.Fatal("Expected failures, got none.") |
| 312 |
} |
| 313 |
}) |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
func TestValidateFieldManagerValid(t *testing.T) { |
| 318 |
tests := []string{ |
| 319 |
"filedManager", |
| 320 |
"你好", // Hello |
| 321 |
"🍔", |
| 322 |
} |
| 323 |
|
| 324 |
for _, test := range tests { |
| 325 |
t.Run(test, func(t *testing.T) { |
| 326 |
errs := ValidateFieldManager(test, field.NewPath("fieldManager")) |
| 327 |
if len(errs) != 0 { |
| 328 |
t.Errorf("Validation failed: %v", errs) |
| 329 |
} |
| 330 |
}) |
| 331 |
} |
| 332 |
} |
| 333 |
|
| 334 |
func TestValidateFieldManagerInvalid(t *testing.T) { |
| 335 |
tests := []string{ |
| 336 |
"field\nmanager", // Contains invalid character \n |
| 337 |
"fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", // Has 129 chars |
| 338 |
} |
| 339 |
|
| 340 |
for _, test := range tests { |
| 341 |
t.Run(test, func(t *testing.T) { |
| 342 |
errs := ValidateFieldManager(test, field.NewPath("fieldManager")) |
| 343 |
if len(errs) == 0 { |
| 344 |
t.Errorf("Validation should have failed") |
| 345 |
} |
| 346 |
}) |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
func TestValidateManagedFieldsInvalid(t *testing.T) { |
| 351 |
tests := []metav1.ManagedFieldsEntry{{ |
| 352 |
Operation: metav1.ManagedFieldsOperationUpdate, |
| 353 |
FieldsType: "RandomVersion", |
| 354 |
APIVersion: "v1", |
| 355 |
}, { |
| 356 |
Operation: "RandomOperation", |
| 357 |
FieldsType: "FieldsV1", |
| 358 |
APIVersion: "v1", |
| 359 |
}, { |
| 360 |
// Operation is missing |
| 361 |
FieldsType: "FieldsV1", |
| 362 |
APIVersion: "v1", |
| 363 |
}, { |
| 364 |
Operation: metav1.ManagedFieldsOperationUpdate, |
| 365 |
FieldsType: "FieldsV1", |
| 366 |
// Invalid fieldManager |
| 367 |
Manager: "field\nmanager", |
| 368 |
APIVersion: "v1", |
| 369 |
}, { |
| 370 |
Operation: metav1.ManagedFieldsOperationApply, |
| 371 |
FieldsType: "FieldsV1", |
| 372 |
APIVersion: "v1", |
| 373 |
Subresource: "TooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLongTooLong", |
| 374 |
}} |
| 375 |
|
| 376 |
for _, test := range tests { |
| 377 |
t.Run(fmt.Sprintf("%#v", test), func(t *testing.T) { |
| 378 |
errs := ValidateManagedFields([]metav1.ManagedFieldsEntry{test}, field.NewPath("managedFields")) |
| 379 |
if len(errs) == 0 { |
| 380 |
t.Errorf("Validation should have failed") |
| 381 |
} |
| 382 |
}) |
| 383 |
} |
| 384 |
} |
| 385 |
|
| 386 |
func TestValidateMangedFieldsValid(t *testing.T) { |
| 387 |
tests := []metav1.ManagedFieldsEntry{{ |
| 388 |
Operation: metav1.ManagedFieldsOperationUpdate, |
| 389 |
APIVersion: "v1", |
| 390 |
// FieldsType is missing |
| 391 |
}, { |
| 392 |
Operation: metav1.ManagedFieldsOperationUpdate, |
| 393 |
FieldsType: "FieldsV1", |
| 394 |
APIVersion: "v1", |
| 395 |
}, { |
| 396 |
Operation: metav1.ManagedFieldsOperationApply, |
| 397 |
FieldsType: "FieldsV1", |
| 398 |
APIVersion: "v1", |
| 399 |
Subresource: "scale", |
| 400 |
}, { |
| 401 |
Operation: metav1.ManagedFieldsOperationApply, |
| 402 |
FieldsType: "FieldsV1", |
| 403 |
APIVersion: "v1", |
| 404 |
Manager: "🍔", |
| 405 |
}} |
| 406 |
|
| 407 |
for _, test := range tests { |
| 408 |
t.Run(fmt.Sprintf("%#v", test), func(t *testing.T) { |
| 409 |
err := ValidateManagedFields([]metav1.ManagedFieldsEntry{test}, field.NewPath("managedFields")) |
| 410 |
if err != nil { |
| 411 |
t.Errorf("Validation failed: %v", err) |
| 412 |
} |
| 413 |
}) |
| 414 |
} |
| 415 |
} |
| 416 |
|
| 417 |
func TestValidateConditions(t *testing.T) { |
| 418 |
tests := []struct { |
| 419 |
name string |
| 420 |
conditions []metav1.Condition |
| 421 |
validateErrs func(t *testing.T, errs field.ErrorList) |
| 422 |
}{{ |
| 423 |
name: "bunch-of-invalid-fields", |
| 424 |
conditions: []metav1.Condition{{ |
| 425 |
Type: ":invalid", |
| 426 |
Status: "unknown", |
| 427 |
ObservedGeneration: -1, |
| 428 |
LastTransitionTime: metav1.Time{}, |
| 429 |
Reason: "invalid;val", |
| 430 |
Message: "", |
| 431 |
}}, |
| 432 |
validateErrs: func(t *testing.T, errs field.ErrorList) { |
| 433 |
needle := `status.conditions[0].type: Invalid value: ":invalid": name part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName', or 'my.name', or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]')` |
| 434 |
if !hasError(errs, needle) { |
| 435 |
t.Errorf("missing %q in\n%v", needle, errorsAsString(errs)) |
| 436 |
} |
| 437 |
needle = `status.conditions[0].status: Unsupported value: "unknown": supported values: "False", "True", "Unknown"` |
| 438 |
if !hasError(errs, needle) { |
| 439 |
t.Errorf("missing %q in\n%v", needle, errorsAsString(errs)) |
| 440 |
} |
| 441 |
needle = `status.conditions[0].observedGeneration: Invalid value: -1: must be greater than or equal to zero` |
| 442 |
if !hasError(errs, needle) { |
| 443 |
t.Errorf("missing %q in\n%v", needle, errorsAsString(errs)) |
| 444 |
} |
| 445 |
needle = `status.conditions[0].lastTransitionTime: Required value: must be set` |
| 446 |
if !hasError(errs, needle) { |
| 447 |
t.Errorf("missing %q in\n%v", needle, errorsAsString(errs)) |
| 448 |
} |
| 449 |
needle = `status.conditions[0].reason: Invalid value: "invalid;val": a condition reason must start with alphabetic character, optionally followed by a string of alphanumeric characters or '_,:', and must end with an alphanumeric character or '_' (e.g. 'my_name', or 'MY_NAME', or 'MyName', or 'ReasonA,ReasonB', or 'ReasonA:ReasonB', regex used for validation is '[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?')` |
| 450 |
if !hasError(errs, needle) { |
| 451 |
t.Errorf("missing %q in\n%v", needle, errorsAsString(errs)) |
| 452 |
} |
| 453 |
}, |
| 454 |
}, { |
| 455 |
name: "duplicates", |
| 456 |
conditions: []metav1.Condition{{ |
| 457 |
Type: "First", |
| 458 |
}, { |
| 459 |
Type: "Second", |
| 460 |
}, { |
| 461 |
Type: "First", |
| 462 |
}}, |
| 463 |
validateErrs: func(t *testing.T, errs field.ErrorList) { |
| 464 |
needle := `status.conditions[2].type: Duplicate value: "First"` |
| 465 |
if !hasError(errs, needle) { |
| 466 |
t.Errorf("missing %q in\n%v", needle, errorsAsString(errs)) |
| 467 |
} |
| 468 |
}, |
| 469 |
}, { |
| 470 |
name: "colon-allowed-in-reason", |
| 471 |
conditions: []metav1.Condition{{ |
| 472 |
Type: "First", |
| 473 |
Reason: "valid:val", |
| 474 |
}}, |
| 475 |
validateErrs: func(t *testing.T, errs field.ErrorList) { |
| 476 |
needle := `status.conditions[0].reason` |
| 477 |
if hasPrefixError(errs, needle) { |
| 478 |
t.Errorf("has %q in\n%v", needle, errorsAsString(errs)) |
| 479 |
} |
| 480 |
}, |
| 481 |
}, { |
| 482 |
name: "comma-allowed-in-reason", |
| 483 |
conditions: []metav1.Condition{{ |
| 484 |
Type: "First", |
| 485 |
Reason: "valid,val", |
| 486 |
}}, |
| 487 |
validateErrs: func(t *testing.T, errs field.ErrorList) { |
| 488 |
needle := `status.conditions[0].reason` |
| 489 |
if hasPrefixError(errs, needle) { |
| 490 |
t.Errorf("has %q in\n%v", needle, errorsAsString(errs)) |
| 491 |
} |
| 492 |
}, |
| 493 |
}, { |
| 494 |
name: "reason-does-not-end-in-delimiter", |
| 495 |
conditions: []metav1.Condition{{ |
| 496 |
Type: "First", |
| 497 |
Reason: "valid,val:", |
| 498 |
}}, |
| 499 |
validateErrs: func(t *testing.T, errs field.ErrorList) { |
| 500 |
needle := `status.conditions[0].reason: Invalid value: "valid,val:": a condition reason must start with alphabetic character, optionally followed by a string of alphanumeric characters or '_,:', and must end with an alphanumeric character or '_' (e.g. 'my_name', or 'MY_NAME', or 'MyName', or 'ReasonA,ReasonB', or 'ReasonA:ReasonB', regex used for validation is '[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?')` |
| 501 |
if !hasError(errs, needle) { |
| 502 |
t.Errorf("missing %q in\n%v", needle, errorsAsString(errs)) |
| 503 |
} |
| 504 |
}, |
| 505 |
}} |
| 506 |
|
| 507 |
for _, test := range tests { |
| 508 |
t.Run(test.name, func(t *testing.T) { |
| 509 |
errs := ValidateConditions(test.conditions, field.NewPath("status").Child("conditions")) |
| 510 |
test.validateErrs(t, errs) |
| 511 |
}) |
| 512 |
} |
| 513 |
} |
| 514 |
|
| 515 |
func TestLabelSelectorMatchExpression(t *testing.T) { |
| 516 |
testCases := []struct { |
| 517 |
name string |
| 518 |
labelSelector *metav1.LabelSelector |
| 519 |
wantErrorNumber int |
| 520 |
validateErrs func(t *testing.T, errs field.ErrorList) |
| 521 |
}{{ |
| 522 |
name: "Valid LabelSelector", |
| 523 |
labelSelector: &metav1.LabelSelector{ |
| 524 |
MatchExpressions: []metav1.LabelSelectorRequirement{{ |
| 525 |
Key: "key", |
| 526 |
Operator: metav1.LabelSelectorOpIn, |
| 527 |
Values: []string{"value"}, |
| 528 |
}}, |
| 529 |
}, |
| 530 |
wantErrorNumber: 0, |
| 531 |
validateErrs: nil, |
| 532 |
}, { |
| 533 |
name: "MatchExpression's key name isn't valid", |
| 534 |
labelSelector: &metav1.LabelSelector{ |
| 535 |
MatchExpressions: []metav1.LabelSelectorRequirement{{ |
| 536 |
Key: "-key", |
| 537 |
Operator: metav1.LabelSelectorOpIn, |
| 538 |
Values: []string{"value"}, |
| 539 |
}}, |
| 540 |
}, |
| 541 |
wantErrorNumber: 1, |
| 542 |
validateErrs: func(t *testing.T, errs field.ErrorList) { |
| 543 |
errMessage := "name part must consist of alphanumeric characters" |
| 544 |
if !partStringInErrorMessage(errs, errMessage) { |
| 545 |
t.Errorf("missing %q in\n%v", errMessage, errorsAsString(errs)) |
| 546 |
} |
| 547 |
}, |
| 548 |
}, { |
| 549 |
name: "MatchExpression's operator isn't valid", |
| 550 |
labelSelector: &metav1.LabelSelector{ |
| 551 |
MatchExpressions: []metav1.LabelSelectorRequirement{{ |
| 552 |
Key: "key", |
| 553 |
Operator: "abc", |
| 554 |
Values: []string{"value"}, |
| 555 |
}}, |
| 556 |
}, |
| 557 |
wantErrorNumber: 1, |
| 558 |
validateErrs: func(t *testing.T, errs field.ErrorList) { |
| 559 |
errMessage := "not a valid selector operator" |
| 560 |
if !partStringInErrorMessage(errs, errMessage) { |
| 561 |
t.Errorf("missing %q in\n%v", errMessage, errorsAsString(errs)) |
| 562 |
} |
| 563 |
}, |
| 564 |
}, { |
| 565 |
name: "MatchExpression's value name isn't valid", |
| 566 |
labelSelector: &metav1.LabelSelector{ |
| 567 |
MatchExpressions: []metav1.LabelSelectorRequirement{{ |
| 568 |
Key: "key", |
| 569 |
Operator: metav1.LabelSelectorOpIn, |
| 570 |
Values: []string{"-value"}, |
| 571 |
}}, |
| 572 |
}, |
| 573 |
wantErrorNumber: 1, |
| 574 |
validateErrs: func(t *testing.T, errs field.ErrorList) { |
| 575 |
errMessage := "a valid label must be an empty string or consist of" |
| 576 |
if !partStringInErrorMessage(errs, errMessage) { |
| 577 |
t.Errorf("missing %q in\n%v", errMessage, errorsAsString(errs)) |
| 578 |
} |
| 579 |
}, |
| 580 |
}} |
| 581 |
for index, testCase := range testCases { |
| 582 |
t.Run(testCase.name, func(t *testing.T) { |
| 583 |
allErrs := ValidateLabelSelector(testCase.labelSelector, LabelSelectorValidationOptions{AllowInvalidLabelValueInSelector: false}, field.NewPath("labelSelector")) |
| 584 |
if len(allErrs) != testCase.wantErrorNumber { |
| 585 |
t.Errorf("case[%d]: expected failure", index) |
| 586 |
} |
| 587 |
if len(allErrs) >= 1 && testCase.validateErrs != nil { |
| 588 |
testCase.validateErrs(t, allErrs) |
| 589 |
} |
| 590 |
}) |
| 591 |
} |
| 592 |
} |
| 593 |
|
| 594 |
func hasError(errs field.ErrorList, needle string) bool { |
| 595 |
for _, curr := range errs { |
| 596 |
if curr.Error() == needle { |
| 597 |
return true |
| 598 |
} |
| 599 |
} |
| 600 |
return false |
| 601 |
} |
| 602 |
|
| 603 |
func hasPrefixError(errs field.ErrorList, prefix string) bool { |
| 604 |
for _, curr := range errs { |
| 605 |
if strings.HasPrefix(curr.Error(), prefix) { |
| 606 |
return true |
| 607 |
} |
| 608 |
} |
| 609 |
return false |
| 610 |
} |
| 611 |
|
| 612 |
func partStringInErrorMessage(errs field.ErrorList, prefix string) bool { |
| 613 |
for _, curr := range errs { |
| 614 |
if strings.Contains(curr.Error(), prefix) { |
| 615 |
return true |
| 616 |
} |
| 617 |
} |
| 618 |
return false |
| 619 |
} |
| 620 |
|
| 621 |
func errorsAsString(errs field.ErrorList) string { |
| 622 |
messages := []string{} |
| 623 |
for _, curr := range errs { |
| 624 |
messages = append(messages, curr.Error()) |
| 625 |
} |
| 626 |
return strings.Join(messages, "\n") |
| 627 |
} |