Skip to content

Commit 53ca4a0

Browse files
add fake client wrapper for setting resource version
1 parent bfb2a3b commit 53ca4a0

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

test/helpers/client.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
Copyright 2020 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 helpers
18+
19+
import (
20+
"fmt"
21+
22+
"k8s.io/apimachinery/pkg/api/meta"
23+
"k8s.io/apimachinery/pkg/runtime"
24+
"sigs.k8s.io/controller-runtime/pkg/client"
25+
"sigs.k8s.io/controller-runtime/pkg/client/fake"
26+
)
27+
28+
// NewFakeClientWithScheme creates a new fake client with the given scheme
29+
// for testing.
30+
// You can choose to initialize it with a slice of runtime.Object; all the objects with be given
31+
// a fake ResourceVersion="1" so it will be possible to use optimistic lock when patching conditions.
32+
func NewFakeClientWithScheme(clientScheme *runtime.Scheme, initObjs ...runtime.Object) client.Client {
33+
for _, obj := range initObjs {
34+
accessor, err := meta.Accessor(obj)
35+
if err != nil {
36+
panic(fmt.Errorf("failed to get accessor for object: %v", err))
37+
}
38+
39+
if accessor.GetResourceVersion() == "" {
40+
accessor.SetResourceVersion("1")
41+
}
42+
}
43+
return fake.NewFakeClientWithScheme(clientScheme, initObjs...)
44+
}

0 commit comments

Comments
 (0)