mirror of
https://github.com/rancher/k3k.git
synced 2026-08-18 03:46:31 +00:00
Scope k3kcli viper env binding to K3KCLI_ prefix to fix flaky test-cli
This commit is contained in:
@@ -92,6 +92,10 @@ func CobraFlagNamespace(appCtx *AppContext, flag *pflag.FlagSet) {
|
||||
}
|
||||
|
||||
func InitializeConfig(cmd *cobra.Command) {
|
||||
// Use a "K3KCLI" prefix so that only namespaced environment variables (e.g.
|
||||
// K3KCLI_VERSION) bind to flags. Without a prefix, common environment variables
|
||||
// such as VERSION, MODE or TOKEN would silently override the matching CLI flags.
|
||||
viper.SetEnvPrefix("K3KCLI")
|
||||
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
|
||||
viper.AutomaticEnv()
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package cmds
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func Test_InitializeConfig_envPrefix(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
envName string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "unprefixed env does not bind to flag",
|
||||
envName: "VERSION",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "prefixed env binds to flag",
|
||||
envName: "K3KCLI_VERSION",
|
||||
want: "1h",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
viper.Reset()
|
||||
t.Setenv(tt.envName, "1h")
|
||||
|
||||
var version string
|
||||
cmd := &cobra.Command{Use: "create"}
|
||||
cmd.Flags().StringVar(&version, "version", "", "k3s version")
|
||||
|
||||
InitializeConfig(cmd)
|
||||
|
||||
assert.Equal(t, tt.want, version)
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user