github.com/1aal/kubeblocks@v0.0.0-20231107070852-e1c03e598921/pkg/cli/list/list_test.go (about)

     1  /*
     2  Copyright (C) 2022-2023 ApeCloud Co., Ltd
     3  
     4  This file is part of KubeBlocks project
     5  
     6  This program is free software: you can redistribute it and/or modify
     7  it under the terms of the GNU Affero General Public License as published by
     8  the Free Software Foundation, either version 3 of the License, or
     9  (at your option) any later version.
    10  
    11  This program is distributed in the hope that it will be useful
    12  but WITHOUT ANY WARRANTY; without even the implied warranty of
    13  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14  GNU Affero General Public License for more details.
    15  
    16  You should have received a copy of the GNU Affero General Public License
    17  along with this program.  If not, see <http://www.gnu.org/licenses/>.
    18  */
    19  
    20  package list
    21  
    22  import (
    23  	"bytes"
    24  	"net/http"
    25  
    26  	. "github.com/onsi/ginkgo/v2"
    27  	. "github.com/onsi/gomega"
    28  	"github.com/spf13/cobra"
    29  	corev1 "k8s.io/api/core/v1"
    30  	"k8s.io/apimachinery/pkg/runtime"
    31  	"k8s.io/apimachinery/pkg/runtime/schema"
    32  	"k8s.io/cli-runtime/pkg/genericiooptions"
    33  	"k8s.io/cli-runtime/pkg/resource"
    34  	"k8s.io/client-go/kubernetes/scheme"
    35  	"k8s.io/client-go/rest/fake"
    36  	cmdtesting "k8s.io/kubectl/pkg/cmd/testing"
    37  	cmdutil "k8s.io/kubectl/pkg/cmd/util"
    38  
    39  	"github.com/1aal/kubeblocks/pkg/cli/types"
    40  	"github.com/1aal/kubeblocks/pkg/cli/util"
    41  )
    42  
    43  var _ = Describe("List", func() {
    44  	var cmd *cobra.Command
    45  	var streams genericiooptions.IOStreams
    46  	buf := new(bytes.Buffer)
    47  
    48  	buildTestCmd := func(f cmdutil.Factory, streams genericiooptions.IOStreams) *cobra.Command {
    49  		o := NewListOptions(f, streams, schema.GroupVersionResource{Group: "", Resource: "pods", Version: types.K8sCoreAPIVersion})
    50  		cmd := &cobra.Command{
    51  			Use:   "ls-test",
    52  			Short: "List test.",
    53  			Run: func(cmd *cobra.Command, args []string) {
    54  				_, err := o.Run()
    55  				util.CheckErr(err)
    56  			},
    57  		}
    58  		o.AddFlags(cmd)
    59  		return cmd
    60  	}
    61  
    62  	mockClient := func(data runtime.Object) *cmdtesting.TestFactory {
    63  		tf := cmdtesting.NewTestFactory().WithNamespace("test")
    64  		defer tf.Cleanup()
    65  
    66  		codec := scheme.Codecs.LegacyCodec(scheme.Scheme.PrioritizedVersionsAllGroups()...)
    67  		tf.UnstructuredClient = &fake.RESTClient{
    68  			NegotiatedSerializer: resource.UnstructuredPlusDefaultContentConfig().NegotiatedSerializer,
    69  			Resp:                 &http.Response{StatusCode: http.StatusOK, Header: cmdtesting.DefaultHeader(), Body: cmdtesting.ObjBody(codec, data)},
    70  		}
    71  		return tf
    72  	}
    73  
    74  	BeforeEach(func() {
    75  		pods, _, _ := cmdtesting.TestData()
    76  		tf := mockClient(pods)
    77  		streams, _, buf, _ = genericiooptions.NewTestIOStreams()
    78  		cmd = buildTestCmd(tf, streams)
    79  		cmd.SetOut(buf)
    80  	})
    81  
    82  	It("run", func() {
    83  		pods, _, _ := cmdtesting.TestData()
    84  		tf := mockClient(pods)
    85  		streams, _, buf, _ := genericiooptions.NewTestIOStreams()
    86  		cmd := buildTestCmd(tf, streams)
    87  		cmd.Run(cmd, []string{})
    88  		Expect(len(buf.String()) > 0).Should(BeTrue())
    89  	})
    90  
    91  	Context("List Objects", func() {
    92  		It("Without any flags", func() {
    93  			expected := `NAME   AGE
    94  foo    <unknown>
    95  bar    <unknown>
    96  `
    97  			cmd.Run(cmd, []string{})
    98  			Expect(buf.String()).To(Equal(expected))
    99  		})
   100  
   101  		It("With -A flag", func() {
   102  			expected := `NAMESPACE   NAME   AGE
   103  test        foo    <unknown>
   104  test        bar    <unknown>
   105  `
   106  			_ = cmd.Flags().Set("all-namespaces", "true")
   107  			cmd.Run(cmd, []string{})
   108  			Expect(buf.String()).To(Equal(expected))
   109  		})
   110  
   111  		It("With -o wide flag", func() {
   112  			expected := `NAME   AGE
   113  foo    <unknown>
   114  bar    <unknown>
   115  `
   116  			_ = cmd.Flags().Set("output", "wide")
   117  			cmd.Run(cmd, []string{})
   118  			Expect(buf.String()).To(Equal(expected))
   119  		})
   120  
   121  		It("With -o yaml flag", func() {
   122  			expected := `apiVersion: v1
   123  items:
   124  - apiVersion: v1
   125    kind: Pod
   126    metadata:
   127      creationTimestamp: null
   128      name: foo
   129      namespace: test
   130      resourceVersion: "10"
   131    spec:
   132      containers: null
   133      dnsPolicy: ClusterFirst
   134      enableServiceLinks: true
   135      restartPolicy: Always
   136      securityContext: {}
   137      terminationGracePeriodSeconds: 30
   138    status: {}
   139  - apiVersion: v1
   140    kind: Pod
   141    metadata:
   142      creationTimestamp: null
   143      name: bar
   144      namespace: test
   145      resourceVersion: "11"
   146    spec:
   147      containers: null
   148      dnsPolicy: ClusterFirst
   149      enableServiceLinks: true
   150      restartPolicy: Always
   151      securityContext: {}
   152      terminationGracePeriodSeconds: 30
   153    status: {}
   154  kind: List
   155  metadata:
   156    resourceVersion: ""
   157  `
   158  			_ = cmd.Flags().Set("output", "yaml")
   159  			cmd.Run(cmd, []string{})
   160  			Expect(buf.String()).To(Equal(expected))
   161  		})
   162  
   163  		It("With -o json flag", func() {
   164  			expected := `{
   165      "apiVersion": "v1",
   166      "items": [
   167          {
   168              "apiVersion": "v1",
   169              "kind": "Pod",
   170              "metadata": {
   171                  "creationTimestamp": null,
   172                  "name": "foo",
   173                  "namespace": "test",
   174                  "resourceVersion": "10"
   175              },
   176              "spec": {
   177                  "containers": null,
   178                  "dnsPolicy": "ClusterFirst",
   179                  "enableServiceLinks": true,
   180                  "restartPolicy": "Always",
   181                  "securityContext": {},
   182                  "terminationGracePeriodSeconds": 30
   183              },
   184              "status": {}
   185          },
   186          {
   187              "apiVersion": "v1",
   188              "kind": "Pod",
   189              "metadata": {
   190                  "creationTimestamp": null,
   191                  "name": "bar",
   192                  "namespace": "test",
   193                  "resourceVersion": "11"
   194              },
   195              "spec": {
   196                  "containers": null,
   197                  "dnsPolicy": "ClusterFirst",
   198                  "enableServiceLinks": true,
   199                  "restartPolicy": "Always",
   200                  "securityContext": {},
   201                  "terminationGracePeriodSeconds": 30
   202              },
   203              "status": {}
   204          }
   205      ],
   206      "kind": "List",
   207      "metadata": {
   208          "resourceVersion": ""
   209      }
   210  }
   211  `
   212  			_ = cmd.Flags().Set("output", "json")
   213  			cmd.Run(cmd, []string{})
   214  			Expect(buf.String()).To(Equal(expected))
   215  		})
   216  
   217  		It("No resources found", func() {
   218  			tf := mockClient(&corev1.PodList{})
   219  			streams, _, buf, errbuf := genericiooptions.NewTestIOStreams()
   220  			cmd = buildTestCmd(tf, streams)
   221  			cmd.SetOut(buf)
   222  			cmd.Run(cmd, []string{})
   223  
   224  			Expect(buf.String()).To(Equal(""))
   225  			Expect(errbuf.String()).To(Equal("No pods found in test namespace.\n"))
   226  		})
   227  	})
   228  })