|
| 1 | +// Copyright Axis Communications AB. |
| 2 | +// |
| 3 | +// For a full list of individual contributors, please see the commit history. |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +// you may not use this file except in compliance with the License. |
| 7 | +// You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, software |
| 12 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +// See the License for the specific language governing permissions and |
| 15 | +// limitations under the License. |
| 16 | + |
| 17 | +package v1alpha2 |
| 18 | + |
| 19 | +import ( |
| 20 | + "context" |
| 21 | + "encoding/json" |
| 22 | + "errors" |
| 23 | + |
| 24 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 25 | +) |
| 26 | + |
| 27 | +// fakeReader implements the client.Reader interface |
| 28 | +type fakeReader struct { |
| 29 | + getResponse client.Object |
| 30 | + listResponse client.ObjectList |
| 31 | +} |
| 32 | + |
| 33 | +// FakeReader returns a fake client implementing the client.Reader interface. |
| 34 | +// |
| 35 | +// Any of the two inputs can be nil, but it is best to at least provide one of them. |
| 36 | +// If an input is nil, the corresponding method will return an error. |
| 37 | +// The inputs are the resources you expect a webhook to fetch either using .Get or |
| 38 | +// .List. |
| 39 | +func FakeReader(get client.Object, list client.ObjectList) client.Reader { |
| 40 | + return &fakeReader{get, list} |
| 41 | +} |
| 42 | + |
| 43 | +// Get fakes the get response of a controller-runtime client. |
| 44 | +func (f *fakeReader) Get(ctx context.Context, key client.ObjectKey, obj client.Object, opts ...client.GetOption) error { |
| 45 | + if f.getResponse == nil { |
| 46 | + return errors.New("this is an error in the Get method") |
| 47 | + } |
| 48 | + b, err := json.Marshal(f.getResponse) |
| 49 | + if err != nil { |
| 50 | + return err |
| 51 | + } |
| 52 | + return json.Unmarshal(b, obj) |
| 53 | +} |
| 54 | + |
| 55 | +// List fakes the list response of a controller-runtime client. |
| 56 | +func (f *fakeReader) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { |
| 57 | + if f.listResponse == nil { |
| 58 | + return errors.New("this is an error in the List method") |
| 59 | + } |
| 60 | + b, err := json.Marshal(f.listResponse) |
| 61 | + if err != nil { |
| 62 | + return err |
| 63 | + } |
| 64 | + return json.Unmarshal(b, list) |
| 65 | +} |
0 commit comments