istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/kube/kclient/clienttest/crd.go (about) 1 // Copyright Istio Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package clienttest 16 17 import ( 18 "fmt" 19 20 v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" 21 kerrors "k8s.io/apimachinery/pkg/api/errors" 22 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 23 "k8s.io/apimachinery/pkg/runtime/schema" 24 metadatafake "k8s.io/client-go/metadata/fake" 25 26 "istio.io/istio/pkg/config/schema/gvr" 27 "istio.io/istio/pkg/kube" 28 "istio.io/istio/pkg/test" 29 ) 30 31 func MakeCRD(t test.Failer, c kube.Client, g schema.GroupVersionResource) { 32 t.Helper() 33 MakeCRDWithAnnotations(t, c, g, nil) 34 } 35 36 func MakeCRDWithAnnotations(t test.Failer, c kube.Client, g schema.GroupVersionResource, annotations map[string]string) { 37 t.Helper() 38 crd := &v1.CustomResourceDefinition{ 39 ObjectMeta: metav1.ObjectMeta{ 40 Name: fmt.Sprintf("%s.%s", g.Resource, g.Group), 41 Annotations: annotations, 42 }, 43 } 44 // Metadata client fake is not kept in sync, so if using a fake client update that as well 45 fmc, ok := c.Metadata().(*metadatafake.FakeMetadataClient) 46 if !ok { 47 return 48 } 49 fmg := fmc.Resource(gvr.CustomResourceDefinition) 50 fmd, ok := fmg.(metadatafake.MetadataClient) 51 if !ok { 52 return 53 } 54 obj := &metav1.PartialObjectMetadata{ 55 TypeMeta: crd.TypeMeta, 56 ObjectMeta: crd.ObjectMeta, 57 } 58 if _, err := fmd.CreateFake(obj, metav1.CreateOptions{}); err != nil { 59 if kerrors.IsAlreadyExists(err) { 60 _, err = fmd.UpdateFake(obj, metav1.UpdateOptions{}) 61 if err != nil { 62 t.Fatal(err) 63 } 64 } else { 65 t.Fatal(err) 66 } 67 } 68 }