diff --git a/cmd/switch.go b/cmd/switch.go index f4fb862a..bb0d6b94 100644 --- a/cmd/switch.go +++ b/cmd/switch.go @@ -64,7 +64,7 @@ func (sc *SwitchCommand) runSwitch(command *cobra.Command, args []string) error func handleQuickSwitch(config *clientcmdapi.Config, name string) (*clientcmdapi.Config, error) { if _, ok := config.Contexts[name]; !ok { - return nil, errors.New("cannot find context named 「" + name + "」") + return config, errors.New("cannot find context named 「" + name + "」") } config.CurrentContext = name return config, nil @@ -83,7 +83,7 @@ func handleOperation(config *clientcmdapi.Config) (*clientcmdapi.Config, error) // exit option kubeItems, err := ExitOption(kubeItems) if err != nil { - return nil, err + return config, err } num := SelectUI(kubeItems, "Select Kube Context") kubeName := kubeItems[num].Name @@ -91,7 +91,6 @@ func handleOperation(config *clientcmdapi.Config) (*clientcmdapi.Config, error) return config, nil } -//TODO need add test //TODO need update docs func switchExample() string { diff --git a/cmd/switch_test.go b/cmd/switch_test.go new file mode 100644 index 00000000..59bea107 --- /dev/null +++ b/cmd/switch_test.go @@ -0,0 +1,57 @@ +package cmd + +import ( + "reflect" + "testing" + + clientcmdapi "k8s.io/client-go/tools/clientcmd/api" +) + +var ( + switchConfig = clientcmdapi.Config{ + AuthInfos: map[string]*clientcmdapi.AuthInfo{ + "black-user": {Token: "black-token"}}, + Clusters: map[string]*clientcmdapi.Cluster{ + "pig-cluster": {Server: "http://pig.org:8080"}}, + Contexts: map[string]*clientcmdapi.Context{ + "root-context": {AuthInfo: "black-user", Cluster: "pig-cluster", Namespace: "saw-ns"}}, + } + currentContextSwitchConfig = clientcmdapi.Config{ + AuthInfos: map[string]*clientcmdapi.AuthInfo{ + "black-user": {Token: "black-token"}}, + Clusters: map[string]*clientcmdapi.Cluster{ + "pig-cluster": {Server: "http://pig.org:8080"}}, + Contexts: map[string]*clientcmdapi.Context{ + "root-context": {AuthInfo: "black-user", Cluster: "pig-cluster", Namespace: "saw-ns"}}, + CurrentContext: "root-context", + } +) + +func Test_handleQuickSwitch(t *testing.T) { + type args struct { + config *clientcmdapi.Config + name string + } + tests := []struct { + name string + args args + want *clientcmdapi.Config + wantErr bool + }{ + // TODO: Add test cases. + {"exist-context", args{&switchConfig, "root-context"}, ¤tContextSwitchConfig, false}, + {"no-exist-context", args{&switchConfig, "test"}, ¤tContextSwitchConfig, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := handleQuickSwitch(tt.args.config, tt.args.name) + if (err != nil) != tt.wantErr { + t.Errorf("handleQuickSwitch() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("handleQuickSwitch() got = %v, want %v", got, tt.want) + } + }) + } +}