k8s.io/kubernetes@v1.29.3/pkg/api/testing/conversion.go (about) 1 /* 2 Copyright 2015 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 testing 18 19 import ( 20 "testing" 21 22 "k8s.io/apimachinery/pkg/fields" 23 "k8s.io/apimachinery/pkg/runtime/schema" 24 "k8s.io/kubernetes/pkg/api/legacyscheme" 25 ) 26 27 // TestSelectableFieldLabelConversionsOfKind verifies that given resource have field 28 // label conversion defined for each its selectable field. 29 // fields contains selectable fields of the resource. 30 // labelMap maps deprecated labels to their canonical names. 31 func TestSelectableFieldLabelConversionsOfKind(t *testing.T, apiVersion string, kind string, fields fields.Set, labelMap map[string]string) { 32 badFieldLabels := []string{ 33 "name", 34 ".name", 35 "bad", 36 "metadata", 37 "foo.bar", 38 } 39 40 value := "value" 41 42 gv, err := schema.ParseGroupVersion(apiVersion) 43 if err != nil { 44 t.Errorf("kind=%s: got unexpected error: %v", kind, err) 45 return 46 } 47 gvk := gv.WithKind(kind) 48 49 if len(fields) == 0 { 50 t.Logf("no selectable fields for kind %q, skipping", kind) 51 } 52 for label := range fields { 53 if label == "name" { 54 t.Logf("FIXME: \"name\" is deprecated by \"metadata.name\", it should be removed from selectable fields of kind=%s", kind) 55 continue 56 } 57 newLabel, newValue, err := legacyscheme.Scheme.ConvertFieldLabel(gvk, label, value) 58 if err != nil { 59 t.Errorf("kind=%s label=%s: got unexpected error: %v", kind, label, err) 60 } else { 61 expectedLabel := label 62 if l, exists := labelMap[label]; exists { 63 expectedLabel = l 64 } 65 if newLabel != expectedLabel { 66 t.Errorf("kind=%s label=%s: got unexpected label name (%q != %q)", kind, label, newLabel, expectedLabel) 67 } 68 if newValue != value { 69 t.Errorf("kind=%s label=%s: got unexpected new value (%q != %q)", kind, label, newValue, value) 70 } 71 } 72 } 73 74 for _, label := range badFieldLabels { 75 _, _, err := legacyscheme.Scheme.ConvertFieldLabel(gvk, label, "value") 76 if err == nil { 77 t.Errorf("kind=%s label=%s: got unexpected non-error", kind, label) 78 } 79 } 80 }