(t *testing.T)
| 66 | } |
| 67 | |
| 68 | func TestSetupConfig(t *testing.T) { |
| 69 | // we pre-create two config files we can refer to in the rest of |
| 70 | // the test cases. |
| 71 | cval1 := "fubble" |
| 72 | conf1 := tempDir() |
| 73 | err := WriteConfigVals(conf1, map[string]string{"boo": cval1}) |
| 74 | require.Nil(t, err) |
| 75 | |
| 76 | cases := []struct { |
| 77 | args []string |
| 78 | env map[string]string |
| 79 | expected string |
| 80 | expectedTwo string |
| 81 | }{ |
| 82 | {nil, nil, "", ""}, |
| 83 | // setting on the command line |
| 84 | {[]string{"--boo", "haha"}, nil, "haha", ""}, |
| 85 | {[]string{"--two-words", "rocks"}, nil, "", "rocks"}, |
| 86 | {[]string{"--home", conf1}, nil, cval1, ""}, |
| 87 | // test both variants of the prefix |
| 88 | {nil, map[string]string{"RD_BOO": "bang"}, "bang", ""}, |
| 89 | {nil, map[string]string{"RD_TWO_WORDS": "fly"}, "", "fly"}, |
| 90 | {nil, map[string]string{"RDTWO_WORDS": "fly"}, "", "fly"}, |
| 91 | {nil, map[string]string{"RD_HOME": conf1}, cval1, ""}, |
| 92 | {nil, map[string]string{"RDHOME": conf1}, cval1, ""}, |
| 93 | } |
| 94 | |
| 95 | for idx, tc := range cases { |
| 96 | i := strconv.Itoa(idx) |
| 97 | // test command that store value of foobar in local variable |
| 98 | var foo, two string |
| 99 | boo := &cobra.Command{ |
| 100 | Use: "reader", |
| 101 | RunE: func(cmd *cobra.Command, args []string) error { |
| 102 | foo = viper.GetString("boo") |
| 103 | two = viper.GetString("two-words") |
| 104 | return nil |
| 105 | }, |
| 106 | } |
| 107 | boo.Flags().String("boo", "", "Some test value from config") |
| 108 | boo.Flags().String("two-words", "", "Check out env handling -") |
| 109 | cmd := PrepareBaseCmd(boo, "RD", "/qwerty/asdfgh") // some missing dir... |
| 110 | cmd.Exit = func(int) {} |
| 111 | |
| 112 | viper.Reset() |
| 113 | args := append([]string{cmd.Use}, tc.args...) |
| 114 | err := RunWithArgs(cmd, args, tc.env) |
| 115 | require.Nil(t, err, i) |
| 116 | assert.Equal(t, tc.expected, foo, i) |
| 117 | assert.Equal(t, tc.expectedTwo, two, i) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | type DemoConfig struct { |
| 122 | Name string `mapstructure:"name"` |
nothing calls this directly
no test coverage detected