github.com/olli-ai/jx/v2@v2.0.400-0.20210921045218-14731b4dd448/pkg/cmd/opts/common_test.go (about) 1 // +build unit 2 3 package opts 4 5 import ( 6 "fmt" 7 "io/ioutil" 8 "os" 9 "path" 10 "testing" 11 12 "github.com/jenkins-x/jx-logging/pkg/log" 13 "github.com/spf13/cobra" 14 "github.com/spf13/viper" 15 "github.com/stretchr/testify/assert" 16 "github.com/stretchr/testify/require" 17 18 clientmocks "github.com/olli-ai/jx/v2/pkg/cmd/clients/mocks" 19 v1 "k8s.io/api/core/v1" 20 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 21 kubemocks "k8s.io/client-go/kubernetes/fake" 22 23 . "github.com/petergtz/pegomock" 24 ) 25 26 const ( 27 testCommandName = "foo" 28 testFlagName = "snafu" 29 ) 30 31 var ( 32 cmdUnderTest *cobra.Command 33 commonOptsUnderTest CommonOptions 34 ) 35 36 type TestFlags struct { 37 Snafu bool `mapstructure:"snafu"` 38 ChildFlags ChildFlags `mapstructure:"children"` 39 } 40 41 type ChildFlags struct { 42 Child string `mapstructure:"child"` 43 } 44 45 func Test_FlagExplicitlySet_returns_true_if_flag_explicitly_set_to_false(t *testing.T) { 46 setupTestCommand() 47 48 err := cmdUnderTest.Flags().Parse([]string{testCommandName, fmt.Sprintf("--%s", testFlagName), "false"}) 49 assert.NoError(t, err) 50 explicit := commonOptsUnderTest.IsFlagExplicitlySet(testFlagName) 51 assert.True(t, explicit, "the flag should be explicitly set") 52 } 53 54 func Test_FlagExplicitlySet_returns_true_if_flag_explicitly_set_to_true(t *testing.T) { 55 setupTestCommand() 56 57 err := cmdUnderTest.Flags().Parse([]string{testCommandName, fmt.Sprintf("--%s", testFlagName), "true"}) 58 assert.NoError(t, err) 59 explicit := commonOptsUnderTest.IsFlagExplicitlySet(testFlagName) 60 assert.True(t, explicit, "the flag should be explicitly set") 61 } 62 63 func Test_FlagExplicitlySet_returns_false_if_flag_is_not_set(t *testing.T) { 64 setupTestCommand() 65 66 explicit := commonOptsUnderTest.IsFlagExplicitlySet(testFlagName) 67 assert.False(t, explicit, "the flag should not be explicitly set") 68 } 69 70 func Test_FlagExplicitlySet_returns_false_if_flag_is_unknown(t *testing.T) { 71 setupTestCommand() 72 73 explicit := commonOptsUnderTest.IsFlagExplicitlySet("fubar") 74 assert.False(t, explicit, "the flag should be unknown") 75 } 76 77 func Test_NotifyProgress(t *testing.T) { 78 setupTestCommand() 79 80 commonOptsUnderTest.NotifyProgressf(LogInfo, "hello %s", "world\n") 81 82 actual := "" 83 expectedText := "hello again\n" 84 85 commonOptsUnderTest.NotifyCallback = func(level LogLevel, text string) { 86 actual = text 87 } 88 89 commonOptsUnderTest.NotifyProgressf(LogInfo, expectedText) 90 91 assert.Equal(t, expectedText, actual, "callback receives the log message") 92 } 93 94 func Test_JXNamespace(t *testing.T) { 95 setupTestCommand() 96 97 // mock factory 98 factory := clientmocks.NewMockFactory() 99 100 // namespace fixture 101 namespace := &v1.Namespace{ 102 ObjectMeta: metav1.ObjectMeta{ 103 Name: "jx-testing", 104 Namespace: "jx-testing", 105 }, 106 } 107 108 // mock Kubernetes interface 109 kubernetesInterface := kubemocks.NewSimpleClientset(namespace) 110 // Override CreateKubeClient to return mock Kubernetes interface 111 When(factory.CreateKubeClient()).ThenReturn(kubernetesInterface, "jx-testing", nil) 112 113 commonOptsUnderTest.SetFactory(factory) 114 115 kubeClient, ns, err := commonOptsUnderTest.KubeClientAndNamespace() 116 assert.NoError(t, err, "Failed to create kube client") 117 118 if err == nil { 119 resource, err := kubeClient.CoreV1().Namespaces().Get(ns, metav1.GetOptions{}) 120 assert.NoError(t, err, "Failed to query namespace") 121 if err == nil { 122 log.Logger().Warnf("Found namespace %#v", resource) 123 } 124 assert.Equal(t, namespace.Namespace, ns) 125 } 126 } 127 128 func Test_GetConfiguration(t *testing.T) { 129 setupTestCommand() 130 131 fileContent := fmt.Sprintf("%s: %t\n", testFlagName, true) 132 configFile, removeTmp := setupTestConfig(t, fileContent) 133 134 defer removeTmp(configFile) 135 136 commonOptsUnderTest = CommonOptions{} 137 commonOptsUnderTest.ConfigFile = configFile 138 139 testFlags := TestFlags{} 140 err := commonOptsUnderTest.GetConfiguration(&testFlags) 141 assert.NoError(t, err, "Failed to GetConfiguration") 142 143 assert.Equal(t, true, testFlags.Snafu) 144 } 145 146 func Test_configExists_child(t *testing.T) { 147 setupTestCommand() 148 149 valuesYaml := fmt.Sprintf("children:\n child: foo") 150 configFile, removeTmp := setupTestConfig(t, valuesYaml) 151 152 defer removeTmp(configFile) 153 154 assert.True(t, configExists("children", "child")) 155 } 156 157 func Test_configExists_no_path(t *testing.T) { 158 setupTestCommand() 159 160 valuesYaml := fmt.Sprintf("snafu: true") 161 configFile, removeTmp := setupTestConfig(t, valuesYaml) 162 163 defer removeTmp(configFile) 164 165 assert.True(t, configExists("", "snafu")) 166 } 167 168 func Test_configNotExists(t *testing.T) { 169 setupTestCommand() 170 171 valuesYaml := fmt.Sprintf("children:\n child: foo") 172 configFile, removeTmp := setupTestConfig(t, valuesYaml) 173 174 defer removeTmp(configFile) 175 176 assert.False(t, configExists("children", "son")) 177 } 178 179 func Test_IsJXBoot(t *testing.T) { 180 orig, found := os.LookupEnv(jxInterpretPipelineEnvKey) 181 defer func() { 182 if found { 183 _ = os.Setenv(jxInterpretPipelineEnvKey, orig) 184 } 185 }() 186 187 o := CommonOptions{} 188 189 err := os.Setenv(jxInterpretPipelineEnvKey, "") 190 assert.NoError(t, err) 191 assert.False(t, o.IsJXBoot(), "we should not be in boot mode") 192 193 err = os.Setenv(jxInterpretPipelineEnvKey, "false") 194 assert.NoError(t, err) 195 assert.False(t, o.IsJXBoot(), "we should not be in boot mode") 196 197 err = os.Setenv(jxInterpretPipelineEnvKey, "true") 198 assert.NoError(t, err) 199 assert.True(t, o.IsJXBoot(), "we should be in boot mode") 200 } 201 202 func setupTestConfig(t *testing.T, config string) (string, func(string)) { 203 setupTestCommand() 204 205 tmpDir, err := ioutil.TempDir("", "") 206 require.Nil(t, err, "Failed creating tmp dir") 207 configFile := path.Join(tmpDir, "config.yaml") 208 err = ioutil.WriteFile(configFile, []byte(config), 0600) 209 require.Nil(t, err, "Failed writing config yaml file") 210 211 commonOptsUnderTest.ConfigFile = configFile 212 213 testFlags := TestFlags{} 214 err = commonOptsUnderTest.GetConfiguration(&testFlags) 215 assert.NoError(t, err, "Failed to GetConfiguration") 216 217 removeAllFunc := func(configFile string) { 218 _ = os.RemoveAll(configFile) 219 } 220 return configFile, removeAllFunc 221 } 222 223 func setupTestCommand() { 224 var flag bool 225 cmdUnderTest = &cobra.Command{ 226 Use: testCommandName, 227 Short: "", 228 Run: func(cmd *cobra.Command, args []string) { 229 // noop 230 }, 231 } 232 cmdUnderTest.Flags().BoolVar(&flag, testFlagName, false, "") 233 _ = viper.BindPFlag(testFlagName, cmdUnderTest.Flags().Lookup(testFlagName)) 234 235 commonOptsUnderTest = CommonOptions{} 236 commonOptsUnderTest.Cmd = cmdUnderTest 237 }