...

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

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

     1  /*
     2  Copyright 2017 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  	"fmt"
    22  	"os"
    23  	"strings"
    24  	"testing"
    25  
    26  	utiltesting "k8s.io/client-go/util/testing"
    27  
    28  	"k8s.io/client-go/tools/clientcmd"
    29  	clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
    30  )
    31  
    32  const (
    33  	currentContext            = "current-context"
    34  	newContext                = "new-context"
    35  	nonexistentCurrentContext = "nonexistent-current-context"
    36  	existentNewContext        = "existent-new-context"
    37  )
    38  
    39  var (
    40  	contextData = clientcmdapi.NewContext()
    41  )
    42  
    43  type renameContextTest struct {
    44  	description    string
    45  	initialConfig  clientcmdapi.Config // initial config
    46  	expectedConfig clientcmdapi.Config // expected config
    47  	args           []string            // kubectl rename-context args
    48  	expectedOut    string              // expected out message
    49  	expectedErr    string              // expected error message
    50  }
    51  
    52  func TestRenameContext(t *testing.T) {
    53  	initialConfig := clientcmdapi.Config{
    54  		CurrentContext: currentContext,
    55  		Contexts:       map[string]*clientcmdapi.Context{currentContext: contextData}}
    56  
    57  	expectedConfig := clientcmdapi.Config{
    58  		CurrentContext: newContext,
    59  		Contexts:       map[string]*clientcmdapi.Context{newContext: contextData}}
    60  
    61  	test := renameContextTest{
    62  		description:    "Testing for kubectl config rename-context whose context to be renamed is the CurrentContext",
    63  		initialConfig:  initialConfig,
    64  		expectedConfig: expectedConfig,
    65  		args:           []string{currentContext, newContext},
    66  		expectedOut:    fmt.Sprintf("Context %q renamed to %q.\n", currentContext, newContext),
    67  		expectedErr:    "",
    68  	}
    69  	test.run(t)
    70  }
    71  
    72  func TestRenameNonexistentContext(t *testing.T) {
    73  	initialConfig := clientcmdapi.Config{
    74  		CurrentContext: currentContext,
    75  		Contexts:       map[string]*clientcmdapi.Context{currentContext: contextData}}
    76  
    77  	test := renameContextTest{
    78  		description:    "Testing for kubectl config rename-context whose context to be renamed no exists",
    79  		initialConfig:  initialConfig,
    80  		expectedConfig: initialConfig,
    81  		args:           []string{nonexistentCurrentContext, newContext},
    82  		expectedOut:    "",
    83  		expectedErr:    fmt.Sprintf("cannot rename the context %q, it's not in", nonexistentCurrentContext),
    84  	}
    85  	test.run(t)
    86  }
    87  
    88  func TestRenameToAlreadyExistingContext(t *testing.T) {
    89  	initialConfig := clientcmdapi.Config{
    90  		CurrentContext: currentContext,
    91  		Contexts: map[string]*clientcmdapi.Context{
    92  			currentContext:     contextData,
    93  			existentNewContext: contextData}}
    94  
    95  	test := renameContextTest{
    96  		description:    "Testing for kubectl config rename-context whose the new name is already in another context.",
    97  		initialConfig:  initialConfig,
    98  		expectedConfig: initialConfig,
    99  		args:           []string{currentContext, existentNewContext},
   100  		expectedOut:    "",
   101  		expectedErr:    fmt.Sprintf("cannot rename the context %q, the context %q already exists", currentContext, existentNewContext),
   102  	}
   103  	test.run(t)
   104  }
   105  
   106  func (test renameContextTest) run(t *testing.T) {
   107  	fakeKubeFile, _ := os.CreateTemp(os.TempDir(), "")
   108  	defer utiltesting.CloseAndRemove(t, fakeKubeFile)
   109  	err := clientcmd.WriteToFile(test.initialConfig, fakeKubeFile.Name())
   110  	if err != nil {
   111  		t.Fatalf("unexpected error: %v", err)
   112  	}
   113  
   114  	pathOptions := clientcmd.NewDefaultPathOptions()
   115  	pathOptions.GlobalFile = fakeKubeFile.Name()
   116  	pathOptions.EnvVar = ""
   117  	options := RenameContextOptions{
   118  		configAccess: pathOptions,
   119  		contextName:  test.args[0],
   120  		newName:      test.args[1],
   121  	}
   122  	buf := bytes.NewBuffer([]byte{})
   123  	cmd := NewCmdConfigRenameContext(buf, options.configAccess)
   124  
   125  	options.Complete(cmd, test.args, buf)
   126  	options.Validate()
   127  	err = options.RunRenameContext(buf)
   128  
   129  	if len(test.expectedErr) != 0 {
   130  		if err == nil {
   131  			t.Errorf("Did not get %v", test.expectedErr)
   132  		} else {
   133  			if !strings.Contains(err.Error(), test.expectedErr) {
   134  				t.Errorf("Expected error %v, but got %v", test.expectedErr, err)
   135  			}
   136  		}
   137  		return
   138  	}
   139  
   140  	config, err := clientcmd.LoadFromFile(fakeKubeFile.Name())
   141  	if err != nil {
   142  		t.Fatalf("unexpected error loading kubeconfig file: %v", err)
   143  	}
   144  
   145  	_, oldExists := config.Contexts[currentContext]
   146  	_, newExists := config.Contexts[newContext]
   147  
   148  	if (!newExists) || (oldExists) || (config.CurrentContext != newContext) {
   149  		t.Errorf("Failed in: %q\n expected %v\n but got %v", test.description, test.expectedConfig, *config)
   150  	}
   151  
   152  	if len(test.expectedOut) != 0 {
   153  		if buf.String() != test.expectedOut {
   154  			t.Errorf("Failed in:%q\n expected out %v\n but got %v", test.description, test.expectedOut, buf.String())
   155  		}
   156  	}
   157  }
   158  

View as plain text