github.com/uhthomas/helm@v3.0.0-beta.3+incompatible/pkg/cli/environment_test.go (about) 1 /* 2 Copyright The Helm 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 cli 18 19 import ( 20 "os" 21 "strings" 22 "testing" 23 24 "github.com/spf13/pflag" 25 ) 26 27 func TestEnvSettings(t *testing.T) { 28 tests := []struct { 29 name string 30 31 // input 32 args string 33 envars map[string]string 34 35 // expected values 36 ns, kcontext string 37 debug bool 38 }{ 39 { 40 name: "defaults", 41 ns: "", 42 }, 43 { 44 name: "with flags set", 45 args: "--debug --namespace=myns", 46 ns: "myns", 47 debug: true, 48 }, 49 { 50 name: "with envvars set", 51 envars: map[string]string{"HELM_DEBUG": "1", "HELM_NAMESPACE": "yourns"}, 52 ns: "yourns", 53 debug: true, 54 }, 55 { 56 name: "with flags and envvars set", 57 args: "--debug --namespace=myns", 58 envars: map[string]string{"HELM_DEBUG": "1", "HELM_NAMESPACE": "yourns"}, 59 ns: "myns", 60 debug: true, 61 }, 62 } 63 64 for _, tt := range tests { 65 t.Run(tt.name, func(t *testing.T) { 66 defer resetEnv()() 67 68 for k, v := range tt.envars { 69 os.Setenv(k, v) 70 } 71 72 flags := pflag.NewFlagSet("testing", pflag.ContinueOnError) 73 74 settings := &EnvSettings{} 75 settings.AddFlags(flags) 76 flags.Parse(strings.Split(tt.args, " ")) 77 78 settings.Init(flags) 79 80 if settings.Debug != tt.debug { 81 t.Errorf("expected debug %t, got %t", tt.debug, settings.Debug) 82 } 83 if settings.Namespace != tt.ns { 84 t.Errorf("expected namespace %q, got %q", tt.ns, settings.Namespace) 85 } 86 if settings.KubeContext != tt.kcontext { 87 t.Errorf("expected kube-context %q, got %q", tt.kcontext, settings.KubeContext) 88 } 89 }) 90 } 91 } 92 93 func resetEnv() func() { 94 origEnv := os.Environ() 95 96 // ensure any local envvars do not hose us 97 for _, e := range envMap { 98 os.Unsetenv(e) 99 } 100 101 return func() { 102 for _, pair := range origEnv { 103 kv := strings.SplitN(pair, "=", 2) 104 os.Setenv(kv[0], kv[1]) 105 } 106 } 107 }