Skip to content

Commit 0ea0ac5

Browse files
committed
Honor GenerateName during fake client create
Closely matches the NameGenerator from APIServer
1 parent 19e72eb commit 0ea0ac5

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
@@ -171,6 +171,35 @@ var _ = Describe("Fake client", func() {
171171
Expect(obj.ObjectMeta.ResourceVersion).To(Equal("1"))
172172
})
173173

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

0 commit comments

Comments
 (0)