From 825dc470ccc6e1dc1bd69e10ce2d9404a364f441 Mon Sep 17 00:00:00 2001 From: Eric Tune Date: Fri, 12 Feb 2016 14:38:22 -0800 Subject: [PATCH] Add a validation helper function. I will use this in a subsequent PR as part of #12298 --- pkg/api/validation/validation.go | 14 ++++++++++ pkg/api/validation/validation_test.go | 37 +++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/pkg/api/validation/validation.go b/pkg/api/validation/validation.go index a2ecf16211e..21b93722a51 100644 --- a/pkg/api/validation/validation.go +++ b/pkg/api/validation/validation.go @@ -84,6 +84,20 @@ func ValidateLabels(labels map[string]string, fldPath *field.Path) field.ErrorLi return allErrs } +// ValidateHasLabel requires that api.ObjectMeta has a Label with key and expectedValue +func ValidateHasLabel(meta api.ObjectMeta, fldPath *field.Path, key, expectedValue string) field.ErrorList { + allErrs := field.ErrorList{} + actualValue, found := meta.Labels[key] + if !found { + allErrs = append(allErrs, field.Required(fldPath.Child("labels"), key+"="+expectedValue)) + return allErrs + } + if actualValue != expectedValue { + allErrs = append(allErrs, field.Invalid(fldPath.Child("labels"), meta.Labels, "expected "+key+"="+expectedValue)) + } + return allErrs +} + // ValidateAnnotations validates that a set of annotations are correctly defined. func ValidateAnnotations(annotations map[string]string, fldPath *field.Path) field.ErrorList { allErrs := field.ErrorList{} diff --git a/pkg/api/validation/validation_test.go b/pkg/api/validation/validation_test.go index 0a60104f344..38fc6bfb01c 100644 --- a/pkg/api/validation/validation_test.go +++ b/pkg/api/validation/validation_test.go @@ -5009,3 +5009,40 @@ func TestValidateConfigMapUpdate(t *testing.T) { } } } + +func TestValidateHasLabel(t *testing.T) { + successCase := api.ObjectMeta{ + Name: "123", + Namespace: "ns", + Labels: map[string]string{ + "other": "blah", + "foo": "bar", + }, + } + if errs := ValidateHasLabel(successCase, field.NewPath("field"), "foo", "bar"); len(errs) != 0 { + t.Errorf("expected success: %v", errs) + } + + missingCase := api.ObjectMeta{ + Name: "123", + Namespace: "ns", + Labels: map[string]string{ + "other": "blah", + }, + } + if errs := ValidateHasLabel(missingCase, field.NewPath("field"), "foo", "bar"); len(errs) == 0 { + t.Errorf("expected failure") + } + + wrongValueCase := api.ObjectMeta{ + Name: "123", + Namespace: "ns", + Labels: map[string]string{ + "other": "blah", + "foo": "notbar", + }, + } + if errs := ValidateHasLabel(wrongValueCase, field.NewPath("field"), "foo", "bar"); len(errs) == 0 { + t.Errorf("expected failure") + } +}