Debian Codegraph @

gentype/fake.go

raw
1 /*
2 Copyright 2024 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 gentype
18
19 import (
20 "context"
21 json "encoding/json"
22 "fmt"
23
24 "k8s.io/apimachinery/pkg/api/meta"
25 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
26 labels "k8s.io/apimachinery/pkg/labels"
27 "k8s.io/apimachinery/pkg/runtime"
28 "k8s.io/apimachinery/pkg/runtime/schema"
29 types "k8s.io/apimachinery/pkg/types"
30 watch "k8s.io/apimachinery/pkg/watch"
31 testing "k8s.io/client-go/testing"
32 )
33
34 // FakeClient represents a fake client
35 type FakeClient[T objectWithMeta] struct {
36 *testing.Fake
37 ns string
38 resource schema.GroupVersionResource
39 kind schema.GroupVersionKind
40 newObject func() T
41 }
42
43 // FakeClientWithList represents a fake client with support for lists.
44 type FakeClientWithList[T objectWithMeta, L runtime.Object] struct {
45 *FakeClient[T]
46 alsoFakeLister[T, L]
47 }
48
49 // FakeClientWithApply represents a fake client with support for apply declarative configurations.
50 type FakeClientWithApply[T objectWithMeta, C namedObject] struct {
51 *FakeClient[T]
52 alsoFakeApplier[T, C]
53 }
54
55 // FakeClientWithListAndApply represents a fake client with support for lists and apply declarative configurations.
56 type FakeClientWithListAndApply[T objectWithMeta, L runtime.Object, C namedObject] struct {
57 *FakeClient[T]
58 alsoFakeLister[T, L]
59 alsoFakeApplier[T, C]
60 }
61
62 // Helper types for composition
63 type alsoFakeLister[T objectWithMeta, L runtime.Object] struct {
64 client *FakeClient[T]
65 newList func() L
66 copyListMeta func(L, L)
67 getItems func(L) []T
68 setItems func(L, []T)
69 }
70
71 type alsoFakeApplier[T objectWithMeta, C namedObject] struct {
72 client *FakeClient[T]
73 }
74
75 // NewFakeClient constructs a fake client, namespaced or not, with no support for lists or apply.
76 // Non-namespaced clients are constructed by passing an empty namespace ("").
77 func NewFakeClient[T objectWithMeta](
78 fake *testing.Fake, namespace string, resource schema.GroupVersionResource, kind schema.GroupVersionKind, emptyObjectCreator func() T,
79 ) *FakeClient[T] {
80 return &FakeClient[T]{fake, namespace, resource, kind, emptyObjectCreator}
81 }
82
83 // NewFakeClientWithList constructs a namespaced client with support for lists.
84 func NewFakeClientWithList[T objectWithMeta, L runtime.Object](
85 fake *testing.Fake, namespace string, resource schema.GroupVersionResource, kind schema.GroupVersionKind, emptyObjectCreator func() T,
86 emptyListCreator func() L, listMetaCopier func(L, L), itemGetter func(L) []T, itemSetter func(L, []T),
87 ) *FakeClientWithList[T, L] {
88 fakeClient := NewFakeClient[T](fake, namespace, resource, kind, emptyObjectCreator)
89 return &FakeClientWithList[T, L]{
90 fakeClient,
91 alsoFakeLister[T, L]{fakeClient, emptyListCreator, listMetaCopier, itemGetter, itemSetter},
92 }
93 }
94
95 // NewFakeClientWithApply constructs a namespaced client with support for apply declarative configurations.
96 func NewFakeClientWithApply[T objectWithMeta, C namedObject](
97 fake *testing.Fake, namespace string, resource schema.GroupVersionResource, kind schema.GroupVersionKind, emptyObjectCreator func() T,
98 ) *FakeClientWithApply[T, C] {
99 fakeClient := NewFakeClient[T](fake, namespace, resource, kind, emptyObjectCreator)
100 return &FakeClientWithApply[T, C]{
101 fakeClient,
102 alsoFakeApplier[T, C]{fakeClient},
103 }
104 }
105
106 // NewFakeClientWithListAndApply constructs a client with support for lists and applying declarative configurations.
107 func NewFakeClientWithListAndApply[T objectWithMeta, L runtime.Object, C namedObject](
108 fake *testing.Fake, namespace string, resource schema.GroupVersionResource, kind schema.GroupVersionKind, emptyObjectCreator func() T,
109 emptyListCreator func() L, listMetaCopier func(L, L), itemGetter func(L) []T, itemSetter func(L, []T),
110 ) *FakeClientWithListAndApply[T, L, C] {
111 fakeClient := NewFakeClient[T](fake, namespace, resource, kind, emptyObjectCreator)
112 return &FakeClientWithListAndApply[T, L, C]{
113 fakeClient,
114 alsoFakeLister[T, L]{fakeClient, emptyListCreator, listMetaCopier, itemGetter, itemSetter},
115 alsoFakeApplier[T, C]{fakeClient},
116 }
117 }
118
119 // Get takes name of a resource, and returns the corresponding object, and an error if there is any.
120 func (c *FakeClient[T]) Get(ctx context.Context, name string, options metav1.GetOptions) (T, error) {
121 emptyResult := c.newObject()
122
123 obj, err := c.Fake.
124 Invokes(testing.NewGetActionWithOptions(c.resource, c.ns, name, options), emptyResult)
125 if obj == nil {
126 return emptyResult, err
127 }
128 return obj.(T), err
129 }
130
131 func ToPointerSlice[T any](src []T) []*T {
132 if src == nil {
133 return nil
134 }
135 result := make([]*T, len(src))
136 for i := range src {
137 result[i] = &src[i]
138 }
139 return result
140 }
141
142 func FromPointerSlice[T any](src []*T) []T {
143 if src == nil {
144 return nil
145 }
146 result := make([]T, len(src))
147 for i := range src {
148 result[i] = *src[i]
149 }
150 return result
151 }
152
153 // List takes label and field selectors, and returns the list of resources that match those selectors.
154 func (l *alsoFakeLister[T, L]) List(ctx context.Context, opts metav1.ListOptions) (result L, err error) {
155 emptyResult := l.newList()
156 obj, err := l.client.Fake.
157 Invokes(testing.NewListActionWithOptions(l.client.resource, l.client.kind, l.client.ns, opts), emptyResult)
158 if obj == nil {
159 return emptyResult, err
160 }
161
162 label, _, _ := testing.ExtractFromListOptions(opts)
163 if label == nil {
164 // Everything matches
165 return obj.(L), nil
166 }
167 list := l.newList()
168 l.copyListMeta(list, obj.(L))
169 var items []T
170 for _, item := range l.getItems(obj.(L)) {
171 itemMeta, err := meta.Accessor(item)
172 if err != nil {
173 // No ObjectMeta, nothing can match
174 continue
175 }
176 if label.Matches(labels.Set(itemMeta.GetLabels())) {
177 items = append(items, item)
178 }
179 }
180 l.setItems(list, items)
181 return list, err
182 }
183
184 // Watch returns a watch.Interface that watches the requested resources.
185 func (c *FakeClient[T]) Watch(ctx context.Context, opts metav1.ListOptions) (watch.Interface, error) {
186 opts.Watch = true
187 return c.Fake.
188 InvokesWatch(testing.NewWatchActionWithOptions(c.resource, c.ns, opts))
189 }
190
191 // Create takes the representation of a resource and creates it. Returns the server's representation of the resource, and an error, if there is any.
192 func (c *FakeClient[T]) Create(ctx context.Context, resource T, opts metav1.CreateOptions) (result T, err error) {
193 emptyResult := c.newObject()
194 obj, err := c.Fake.
195 Invokes(testing.NewCreateActionWithOptions(c.resource, c.ns, resource, opts), emptyResult)
196 if obj == nil {
197 return emptyResult, err
198 }
199 return obj.(T), err
200 }
201
202 // Update takes the representation of a resource and updates it. Returns the server's representation of the resource, and an error, if there is any.
203 func (c *FakeClient[T]) Update(ctx context.Context, resource T, opts metav1.UpdateOptions) (result T, err error) {
204 emptyResult := c.newObject()
205 obj, err := c.Fake.
206 Invokes(testing.NewUpdateActionWithOptions(c.resource, c.ns, resource, opts), emptyResult)
207 if obj == nil {
208 return emptyResult, err
209 }
210 return obj.(T), err
211 }
212
213 // UpdateStatus updates the resource's status and returns the updated resource.
214 func (c *FakeClient[T]) UpdateStatus(ctx context.Context, resource T, opts metav1.UpdateOptions) (result T, err error) {
215 emptyResult := c.newObject()
216 obj, err := c.Fake.
217 Invokes(testing.NewUpdateSubresourceActionWithOptions(c.resource, "status", c.ns, resource, opts), emptyResult)
218
219 if obj == nil {
220 return emptyResult, err
221 }
222 return obj.(T), err
223 }
224
225 // Delete deletes the resource matching the given name. Returns an error if one occurs.
226 func (c *FakeClient[T]) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error {
227 _, err := c.Fake.
228 Invokes(testing.NewDeleteActionWithOptions(c.resource, c.ns, name, opts), c.newObject())
229 return err
230 }
231
232 // DeleteCollection deletes a collection of objects.
233 func (l *alsoFakeLister[T, L]) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error {
234 _, err := l.client.Fake.
235 Invokes(testing.NewDeleteCollectionActionWithOptions(l.client.resource, l.client.ns, opts, listOpts), l.newList())
236 return err
237 }
238
239 // Patch applies the patch and returns the patched resource.
240 func (c *FakeClient[T]) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts metav1.PatchOptions, subresources ...string) (result T, err error) {
241 emptyResult := c.newObject()
242 obj, err := c.Fake.
243 Invokes(testing.NewPatchSubresourceActionWithOptions(c.resource, c.ns, name, pt, data, opts, subresources...), emptyResult)
244 if obj == nil {
245 return emptyResult, err
246 }
247 return obj.(T), err
248 }
249
250 // Apply takes the given apply declarative configuration, applies it and returns the applied resource.
251 func (a *alsoFakeApplier[T, C]) Apply(ctx context.Context, configuration C, opts metav1.ApplyOptions) (result T, err error) {
252 if configuration == *new(C) {
253 return *new(T), fmt.Errorf("configuration provided to Apply must not be nil")
254 }
255 data, err := json.Marshal(configuration)
256 if err != nil {
257 return *new(T), err
258 }
259 name := configuration.GetName()
260 if name == nil {
261 return *new(T), fmt.Errorf("configuration.Name must be provided to Apply")
262 }
263 emptyResult := a.client.newObject()
264 obj, err := a.client.Fake.
265 Invokes(testing.NewPatchSubresourceActionWithOptions(a.client.resource, a.client.ns, *name, types.ApplyPatchType, data, opts.ToPatchOptions()), emptyResult)
266 if obj == nil {
267 return emptyResult, err
268 }
269 return obj.(T), err
270 }
271
272 // ApplyStatus applies the given apply declarative configuration to the resource's status and returns the updated resource.
273 func (a *alsoFakeApplier[T, C]) ApplyStatus(ctx context.Context, configuration C, opts metav1.ApplyOptions) (result T, err error) {
274 if configuration == *new(C) {
275 return *new(T), fmt.Errorf("configuration provided to Apply must not be nil")
276 }
277 data, err := json.Marshal(configuration)
278 if err != nil {
279 return *new(T), err
280 }
281 name := configuration.GetName()
282 if name == nil {
283 return *new(T), fmt.Errorf("configuration.Name must be provided to Apply")
284 }
285 emptyResult := a.client.newObject()
286 obj, err := a.client.Fake.
287 Invokes(testing.NewPatchSubresourceActionWithOptions(a.client.resource, a.client.ns, *name, types.ApplyPatchType, data, opts.ToPatchOptions(), "status"), emptyResult)
288
289 if obj == nil {
290 return emptyResult, err
291 }
292 return obj.(T), err
293 }
294
295 func (c *FakeClient[T]) Namespace() string {
296 return c.ns
297 }
298
299 func (c *FakeClient[T]) Kind() schema.GroupVersionKind {
300 return c.kind
301 }
302
303 func (c *FakeClient[T]) Resource() schema.GroupVersionResource {
304 return c.resource
305 }