Skip to content

Commit 4c789c1

Browse files
authored
Merge pull request #815 from tvs/fake-client-generate-name
🐛 Use GenerateName during fake client's Create method
2 parents 525a922 + 0ea0ac5 commit 4c789c1

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

pkg/client/fake/client.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import (
2727
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2828
"k8s.io/apimachinery/pkg/runtime"
2929
"k8s.io/apimachinery/pkg/runtime/schema"
30+
utilrand "k8s.io/apimachinery/pkg/util/rand"
3031
"k8s.io/client-go/kubernetes/scheme"
3132
"k8s.io/client-go/testing"
3233

@@ -46,6 +47,12 @@ type fakeClient struct {
4647

4748
var _ client.Client = &fakeClient{}
4849

50+
const (
51+
maxNameLength = 63
52+
randomLength = 5
53+
maxGeneratedNameLength = maxNameLength - randomLength
54+
)
55+
4956
// NewFakeClient creates a new fake client for testing.
5057
// You can choose to initialize it with a slice of runtime.Object.
5158
// Deprecated: use NewFakeClientWithScheme. You should always be
@@ -202,6 +209,15 @@ func (c *fakeClient) Create(ctx context.Context, obj runtime.Object, opts ...cli
202209
if err != nil {
203210
return err
204211
}
212+
213+
if accessor.GetName() == "" && accessor.GetGenerateName() != "" {
214+
base := accessor.GetGenerateName()
215+
if len(base) > maxGeneratedNameLength {
216+
base = base[:maxGeneratedNameLength]
217+
}
218+
accessor.SetName(fmt.Sprintf("%s%s", base, utilrand.String(randomLength)))
219+
}
220+
205221
return c.tracker.Create(gvr, obj, accessor.GetNamespace())
206222
}
207223

pkg/client/fake/client_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,35 @@ var _ = Describe("Fake client", func() {
172172
Expect(obj.ObjectMeta.ResourceVersion).To(Equal("1"))
173173
})
174174

175+
It("should be able to Create with GenerateName", func() {
176+
By("Creating a new configmap")
177+
newcm := &corev1.ConfigMap{
178+
TypeMeta: metav1.TypeMeta{
179+
APIVersion: "v1",
180+
Kind: "ConfigMap",
181+
},
182+
ObjectMeta: metav1.ObjectMeta{
183+
GenerateName: "new-test-cm",
184+
Namespace: "ns2",
185+
Labels: map[string]string{
186+
"test-label": "label-value",
187+
},
188+
},
189+
}
190+
err := cl.Create(nil, newcm)
191+
Expect(err).To(BeNil())
192+
193+
By("Listing configmaps with a particular label")
194+
list := &corev1.ConfigMapList{}
195+
err = cl.List(nil, list, client.InNamespace("ns2"),
196+
client.MatchingLabels(map[string]string{
197+
"test-label": "label-value",
198+
}))
199+
Expect(err).To(BeNil())
200+
Expect(list.Items).To(HaveLen(1))
201+
Expect(list.Items[0].Name).NotTo(BeEmpty())
202+
})
203+
175204
It("should be able to Update", func() {
176205
By("Updating a new configmap")
177206
newcm := &corev1.ConfigMap{

0 commit comments

Comments
 (0)