github.com/oam-dev/kubevela@v1.9.11/pkg/oam/mock/client.go (about) 1 /* 2 Copyright 2023 The KubeVela 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 mock 18 19 import ( 20 "strings" 21 22 "k8s.io/apimachinery/pkg/api/meta" 23 "k8s.io/apimachinery/pkg/runtime/schema" 24 "sigs.k8s.io/controller-runtime/pkg/client" 25 "sigs.k8s.io/controller-runtime/pkg/client/fake" 26 ) 27 28 // NewClient new client with given mappings 29 func NewClient(c client.Client, mappings map[schema.GroupVersionResource][]schema.GroupVersionKind) client.Client { 30 if c == nil { 31 c = fake.NewClientBuilder().Build() 32 } 33 return &Client{Client: c, mappings: mappings} 34 } 35 36 // Client fake client 37 type Client struct { 38 client.Client 39 mappings map[schema.GroupVersionResource][]schema.GroupVersionKind 40 } 41 42 // RESTMapper override default mapper 43 func (in *Client) RESTMapper() meta.RESTMapper { 44 mapper := in.Client.RESTMapper() 45 if mapper == nil { 46 mapper = fake.NewClientBuilder().Build().RESTMapper() 47 } 48 return &RESTMapper{RESTMapper: mapper, mappings: in.mappings} 49 } 50 51 // RESTMapper test mapper 52 type RESTMapper struct { 53 meta.RESTMapper 54 mappings map[schema.GroupVersionResource][]schema.GroupVersionKind 55 } 56 57 // KindsFor get kinds 58 func (in *RESTMapper) KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error) { 59 if gvks, found := in.mappings[resource]; found { 60 return gvks, nil 61 } 62 return in.RESTMapper.KindsFor(resource) 63 } 64 65 // RESTMapping get mapping 66 func (in *RESTMapper) RESTMapping(gk schema.GroupKind, versions ...string) (*meta.RESTMapping, error) { 67 version := "v1" 68 if len(versions) > 0 { 69 version = versions[0] 70 } 71 return &meta.RESTMapping{ 72 Resource: schema.GroupVersionResource{Group: gk.Group, Version: versions[0], Resource: strings.ToLower(gk.Kind) + "s"}, 73 GroupVersionKind: gk.WithVersion(version), 74 Scope: scope(meta.RESTScopeNameNamespace), 75 }, nil 76 } 77 78 type scope meta.RESTScopeName 79 80 func (in scope) Name() meta.RESTScopeName { 81 return meta.RESTScopeName(in) 82 }