-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
options_test.go
117 lines (113 loc) · 2.42 KB
/
options_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"os"
"strings"
"testing"
)
func TestOptionsPrecedence(t *testing.T) {
testCases := []struct {
desc string
env []string
args []string
expected Options
}{
{
desc: "just --verbose arg",
args: []string{"--verbose"},
expected: Options{
NoOpen: false,
Verbose: true,
},
},
{
desc: "just -v arg",
args: []string{"-v"},
expected: Options{
NoOpen: false,
Verbose: true,
},
},
{
desc: "just --no-open arg",
args: []string{"--no-open"},
expected: Options{
NoOpen: true,
Verbose: false,
},
},
{
desc: "multiple args",
args: []string{"-v", "--no-open"},
expected: Options{
NoOpen: true,
Verbose: true,
},
},
{
desc: "env arg bool true format",
env: []string{EnvKeyVerbose + "=true"},
expected: Options{
Verbose: true,
},
},
{
desc: "env arg bool TRUE format",
env: []string{EnvKeyVerbose + "=TRUE"},
expected: Options{
Verbose: true,
},
},
{
desc: "env arg bool 1 format",
env: []string{EnvKeyVerbose + "=1"},
expected: Options{
Verbose: true,
},
},
{
desc: "env arg bool yes format",
env: []string{EnvKeyVerbose + "=yes"},
expected: Options{
Verbose: true,
},
},
{
desc: "flags beat env if disagree",
env: []string{EnvKeyVerbose + "=yes"},
args: []string{"--verbose=false"},
expected: Options{
Verbose: false,
},
},
}
originalEnv := os.Environ()
for _, tC := range testCases {
tC := tC // pin to avoid scope issues (see scopelint)
t.Run(tC.desc, func(t *testing.T) {
resetEnviron(tC.env)
actualOpts, _ := ParseFlags(NewOptionsFromEnv(), tC.args)
if actualOpts != tC.expected {
t.Error("opts not as expected")
}
})
}
resetEnviron(originalEnv)
}
// resetEnviron cleasrs and then sets the environment to match a []string of
// key=value pairs, which happens to be exactly what os.Environ() from the
// standard library provides us, but with no built in way set back using the
// same thing... even though you can do the same in Cmd.
//
// Used to restore os.Environ after messing with it in a test, or to set it to
// exact values all at once.
func resetEnviron(envPairs []string) {
os.Clearenv()
for _, envPair := range envPairs {
kv := strings.Split(envPair, "=")
k, v := kv[0], kv[1]
err := os.Setenv(k, v)
if err != nil {
panic("could not set env var in resetEnviron helper")
}
}
}