From 3a037ef46a00f5713b4d001804959f0ae812eadf Mon Sep 17 00:00:00 2001 From: Alvaro Aleman Date: Sat, 3 Apr 2021 10:08:53 -0400 Subject: [PATCH] :bug: Fakeclient: Do not require ListKind The fake client will currently error out of given a Kind in an UnstructuredList that doesn't end with list. This is different from what we do in the actual client, where we tolerate that: https://github.com/kubernetes-sigs/controller-runtime/blob/10ae090c1d3ac0c560dfa1a29b2517eb8d74442b/pkg/client/unstructured_client.go#L204 This change brings the fake client in line with the real client. --- pkg/client/fake/client.go | 10 ++++------ pkg/client/fake/client_test.go | 10 ++++++++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/pkg/client/fake/client.go b/pkg/client/fake/client.go index 39eb9c597e..ee190adb67 100644 --- a/pkg/client/fake/client.go +++ b/pkg/client/fake/client.go @@ -290,13 +290,11 @@ func (c *fakeClient) List(ctx context.Context, obj client.ObjectList, opts ...cl return err } - OriginalKind := gvk.Kind + originalKind := gvk.Kind - if !strings.HasSuffix(gvk.Kind, "List") { - return fmt.Errorf("non-list type %T (kind %q) passed as output", obj, gvk) + if strings.HasSuffix(gvk.Kind, "List") { + gvk.Kind = gvk.Kind[:len(gvk.Kind)-4] } - // we need the non-list GVK, so chop off the "List" from the end of the kind - gvk.Kind = gvk.Kind[:len(gvk.Kind)-4] listOpts := client.ListOptions{} listOpts.ApplyOptions(opts) @@ -311,7 +309,7 @@ func (c *fakeClient) List(ctx context.Context, obj client.ObjectList, opts ...cl if err != nil { return err } - ta.SetKind(OriginalKind) + ta.SetKind(originalKind) ta.SetAPIVersion(gvk.GroupVersion().String()) j, err := json.Marshal(o) diff --git a/pkg/client/fake/client_test.go b/pkg/client/fake/client_test.go index 1e89bb97bf..49da9ad559 100644 --- a/pkg/client/fake/client_test.go +++ b/pkg/client/fake/client_test.go @@ -129,6 +129,16 @@ var _ = Describe("Fake client", func() { Expect(list.Items).To(HaveLen(2)) }) + It("should be able to List using unstructured list when setting a non-list kind", func() { + By("Listing all deployments in a namespace") + list := &unstructured.UnstructuredList{} + list.SetAPIVersion("apps/v1") + list.SetKind("Deployment") + err := cl.List(context.Background(), list, client.InNamespace("ns1")) + Expect(err).To(BeNil()) + Expect(list.Items).To(HaveLen(2)) + }) + It("should support filtering by labels and their values", func() { By("Listing deployments with a particular label and value") list := &appsv1.DeploymentList{}