-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathenvflag_test.go
100 lines (80 loc) · 2.36 KB
/
envflag_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
package envflag
import (
"flag"
"os"
"testing"
)
func setupFlag(options flagOption) *Envflag {
os.Clearenv()
cli := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
options(cli)
return &Envflag{
Cli: cli,
}
}
// declare one flag, assigns value via cli, expects empty unsetFlags
func TestOneSetFlag(t *testing.T) {
var testVal string
ef := setupFlag(func(fs *flag.FlagSet) {
fs.StringVar(&testVal, "test-flag", "default-value", "this is test flag")
})
ef.parseWithEnv([]string{"--test-flag=dummy"})
if want, got := 0, len(ef.unsetFlags()); want != got {
t.Errorf("expects only %v unset flag, got %v intead.", want, got)
}
}
// declare two flags, only set 1 via cli, expects 1 unsetflag
func TestTwoFlagsOneUnset(t *testing.T) {
var (
testIntOne int
testIntTwo int
)
ef := setupFlag(func(fs *flag.FlagSet) {
fs.IntVar(&testIntOne, "test-int-one", 1, "this is test int one")
fs.IntVar(&testIntTwo, "test-int-two", 1, "this is test int two")
})
ef.parseWithEnv([]string{"--test-int-one=100"})
if want, got := 1, len(ef.unsetFlags()); want != got {
t.Errorf("expects only %v unset flag, got %v.", want, got)
}
}
// default < env < cli
func TestPrecendence(t *testing.T) {
var (
testVal string
envVal = "envValue"
cliVal = "cliValue"
defaultVal = "defaultValue"
// testIntTwo int
)
// cli
ef := setupFlag(func(fs *flag.FlagSet) {
fs.StringVar(&testVal, "test-flag", defaultVal, "this is test flag")
})
os.Setenv("TEST_FLAG", envVal)
ef.parseWithEnv([]string{
"--test-flag=" + cliVal,
})
if want, got := cliVal, testVal; want != got {
t.Errorf("expects flag-value be overridden by (cli)%v, got %v.", want, got)
}
// env
ef = setupFlag(func(fs *flag.FlagSet) {
fs.StringVar(&testVal, "test-flag", defaultVal, "this is test flag")
})
os.Setenv("TEST_FLAG", envVal)
ef.parseWithEnv([]string{}) // empty cli
if want, got := envVal, testVal; want != got {
t.Errorf("expects flag-value be overridden by (env)%v, got %v.", want, got)
}
// default
ef = setupFlag(func(fs *flag.FlagSet) {
fs.StringVar(&testVal, "test-flag", defaultVal, "this is test flag")
})
ef.parseWithEnv([]string{}) // empty cli
if want, got := defaultVal, testVal; want != got {
t.Errorf("expects flag-value be overridden by (env)%v, got %v.", want, got)
}
}
// flagOption for testing purposes -- visibility
type flagOption func(*flag.FlagSet)