Skip to content

Commit

Permalink
Merge pull request #815 from tvs/fake-client-generate-name
Browse files Browse the repository at this point in the history
🐛 Use GenerateName during fake client's Create method
  • Loading branch information
k8s-ci-robot authored Feb 24, 2020
2 parents 525a922 + 0ea0ac5 commit 4c789c1
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pkg/client/fake/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
utilrand "k8s.io/apimachinery/pkg/util/rand"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/testing"

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

var _ client.Client = &fakeClient{}

const (
maxNameLength = 63
randomLength = 5
maxGeneratedNameLength = maxNameLength - randomLength
)

// NewFakeClient creates a new fake client for testing.
// You can choose to initialize it with a slice of runtime.Object.
// Deprecated: use NewFakeClientWithScheme. You should always be
Expand Down Expand Up @@ -202,6 +209,15 @@ func (c *fakeClient) Create(ctx context.Context, obj runtime.Object, opts ...cli
if err != nil {
return err
}

if accessor.GetName() == "" && accessor.GetGenerateName() != "" {
base := accessor.GetGenerateName()
if len(base) > maxGeneratedNameLength {
base = base[:maxGeneratedNameLength]
}
accessor.SetName(fmt.Sprintf("%s%s", base, utilrand.String(randomLength)))
}

return c.tracker.Create(gvr, obj, accessor.GetNamespace())
}

Expand Down
29 changes: 29 additions & 0 deletions pkg/client/fake/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,35 @@ var _ = Describe("Fake client", func() {
Expect(obj.ObjectMeta.ResourceVersion).To(Equal("1"))
})

It("should be able to Create with GenerateName", func() {
By("Creating a new configmap")
newcm := &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "ConfigMap",
},
ObjectMeta: metav1.ObjectMeta{
GenerateName: "new-test-cm",
Namespace: "ns2",
Labels: map[string]string{
"test-label": "label-value",
},
},
}
err := cl.Create(nil, newcm)
Expect(err).To(BeNil())

By("Listing configmaps with a particular label")
list := &corev1.ConfigMapList{}
err = cl.List(nil, list, client.InNamespace("ns2"),
client.MatchingLabels(map[string]string{
"test-label": "label-value",
}))
Expect(err).To(BeNil())
Expect(list.Items).To(HaveLen(1))
Expect(list.Items[0].Name).NotTo(BeEmpty())
})

It("should be able to Update", func() {
By("Updating a new configmap")
newcm := &corev1.ConfigMap{
Expand Down

0 comments on commit 4c789c1

Please sign in to comment.