...
1
16
17 package config
18
19 import (
20 "bytes"
21 utiltesting "k8s.io/client-go/util/testing"
22 "os"
23 "strings"
24 "testing"
25
26 "k8s.io/client-go/tools/clientcmd"
27 clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
28 )
29
30 type currentContextTest struct {
31 startingConfig clientcmdapi.Config
32 expectedError string
33 }
34
35 func newFederalContextConfig() clientcmdapi.Config {
36 return clientcmdapi.Config{
37 CurrentContext: "federal-context",
38 }
39 }
40
41 func TestCurrentContextWithSetContext(t *testing.T) {
42 test := currentContextTest{
43 startingConfig: newFederalContextConfig(),
44 expectedError: "",
45 }
46
47 test.run(t)
48 }
49
50 func TestCurrentContextWithUnsetContext(t *testing.T) {
51 test := currentContextTest{
52 startingConfig: *clientcmdapi.NewConfig(),
53 expectedError: "current-context is not set",
54 }
55
56 test.run(t)
57 }
58
59 func (test currentContextTest) run(t *testing.T) {
60 fakeKubeFile, err := os.CreateTemp(os.TempDir(), "")
61 if err != nil {
62 t.Fatalf("unexpected error: %v", err)
63 }
64 defer utiltesting.CloseAndRemove(t, fakeKubeFile)
65 err = clientcmd.WriteToFile(test.startingConfig, fakeKubeFile.Name())
66 if err != nil {
67 t.Fatalf("unexpected error: %v", err)
68 }
69
70 pathOptions := clientcmd.NewDefaultPathOptions()
71 pathOptions.GlobalFile = fakeKubeFile.Name()
72 pathOptions.EnvVar = ""
73 options := CurrentContextOptions{
74 ConfigAccess: pathOptions,
75 }
76
77 buf := bytes.NewBuffer([]byte{})
78 err = RunCurrentContext(buf, &options)
79 if len(test.expectedError) != 0 {
80 if err == nil {
81 t.Errorf("Did not get %v", test.expectedError)
82 } else {
83 if !strings.Contains(err.Error(), test.expectedError) {
84 t.Errorf("Expected %v, but got %v", test.expectedError, err)
85 }
86 }
87 return
88 }
89
90 if err != nil {
91 t.Errorf("Unexpected error: %v", err)
92 }
93 }
94
View as plain text