...

Source file src/k8s.io/kubectl/pkg/cmd/config/get_clusters_test.go

Documentation: k8s.io/kubectl/pkg/cmd/config

     1  /*
     2  Copyright 2014 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package config
    18  
    19  import (
    20  	"bytes"
    21  	"os"
    22  	"testing"
    23  
    24  	utiltesting "k8s.io/client-go/util/testing"
    25  
    26  	"k8s.io/client-go/tools/clientcmd"
    27  	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
    28  )
    29  
    30  type getClustersTest struct {
    31  	config   clientcmdapi.Config
    32  	expected string
    33  }
    34  
    35  func TestGetClusters(t *testing.T) {
    36  	conf := clientcmdapi.Config{
    37  		Clusters: map[string]*clientcmdapi.Cluster{
    38  			"minikube": {Server: "https://192.168.0.99"},
    39  		},
    40  	}
    41  	test := getClustersTest{
    42  		config: conf,
    43  		expected: `NAME
    44  minikube
    45  `,
    46  	}
    47  
    48  	test.run(t)
    49  }
    50  
    51  func TestGetClustersEmpty(t *testing.T) {
    52  	test := getClustersTest{
    53  		config:   clientcmdapi.Config{},
    54  		expected: "NAME\n",
    55  	}
    56  
    57  	test.run(t)
    58  }
    59  
    60  func (test getClustersTest) run(t *testing.T) {
    61  	fakeKubeFile, err := os.CreateTemp(os.TempDir(), "")
    62  	if err != nil {
    63  		t.Fatalf("unexpected error: %v", err)
    64  	}
    65  	defer utiltesting.CloseAndRemove(t, fakeKubeFile)
    66  	err = clientcmd.WriteToFile(test.config, fakeKubeFile.Name())
    67  	if err != nil {
    68  		t.Fatalf("unexpected error: %v", err)
    69  	}
    70  
    71  	pathOptions := clientcmd.NewDefaultPathOptions()
    72  	pathOptions.GlobalFile = fakeKubeFile.Name()
    73  	pathOptions.EnvVar = ""
    74  	buf := bytes.NewBuffer([]byte{})
    75  	cmd := NewCmdConfigGetClusters(buf, pathOptions)
    76  	if err := cmd.Execute(); err != nil {
    77  		t.Fatalf("unexpected error executing command: %v", err)
    78  	}
    79  	if len(test.expected) != 0 {
    80  		if buf.String() != test.expected {
    81  			t.Errorf("expected %v, but got %v", test.expected, buf.String())
    82  		}
    83  		return
    84  	}
    85  }
    86  

View as plain text