-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflag_test.go
More file actions
99 lines (88 loc) · 2.19 KB
/
flag_test.go
File metadata and controls
99 lines (88 loc) · 2.19 KB
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
package struct2pflag_test
import (
"os"
"testing"
"github.com/goark/struct2pflag"
"github.com/spf13/pflag"
)
type ts struct {
S1 string `flag:"string option(1)"`
S2 string `flag:"S2,string option(2)"`
S3 string `flag:"S3,string option(3)"`
I1 int `flag:"integer option(1)"`
I2 int `flag:"I2,integer option(2)"`
I3 int `flag:"I3,integer option(3)"`
B1 bool `flag:"boolean option(1)"`
B2 bool `flag:"B2,boolean option(2)"`
B3 bool `flag:"B3,boolean option(3)"`
}
func TestBind(t *testing.T) {
ts1 := &ts{}
flagSet := pflag.NewFlagSet("", pflag.ContinueOnError)
struct2pflag.Bind(flagSet, ts1)
err := flagSet.Parse(
[]string{
"--s1", "foo",
"--S2", "bar",
"--i1", "9",
"--I2", "8",
"--b1",
"--B2",
},
)
if err != nil {
t.Fatal(err.Error())
}
if expect := "foo"; ts1.S1 != expect {
t.Fatalf("expect %#v,but %#v", ts1.S1, expect)
}
if expect := "bar"; ts1.S2 != expect {
t.Fatalf("expect %#v,but %#v", ts1.S2, expect)
}
if expect := ""; ts1.S3 != expect {
t.Fatalf("expect %#v,but %#v", ts1.S3, expect)
}
if expect := 9; ts1.I1 != expect {
t.Fatalf("expect %#v,but %#v", ts1.I1, expect)
}
if expect := 8; ts1.I2 != expect {
t.Fatalf("expect %#v,but %#v", ts1.I2, expect)
}
if expect := 0; ts1.I3 != expect {
t.Fatalf("expect %#v,but %#v", ts1.I3, expect)
}
if expect := true; ts1.B1 != expect {
t.Fatalf("expect %#v,but %#v", ts1.B1, expect)
}
if expect := true; ts1.B2 != expect {
t.Fatalf("expect %#v,but %#v", ts1.B2, expect)
}
if expect := false; ts1.B3 != expect {
t.Fatalf("expect %#v,but %#v", ts1.B3, expect)
}
ts1 = &ts{}
flagSet = pflag.NewFlagSet("", pflag.ContinueOnError)
struct2pflag.Bind(flagSet, ts1)
cases := [][]string{
{"--S1", "should be lower case"},
{"--s2", "should be upper case"},
{"--I1", "should be lower case"},
{"--i2", "should be upper case"},
{"--B1"},
{"--b2"},
}
stderrSaved := os.Stderr
devnull, err := os.Create(os.DevNull)
if err != nil {
t.Fatal(err.Error())
}
defer func() { _ = devnull.Close() }()
for _, case1 := range cases {
os.Stderr = devnull
err := flagSet.Parse(case1)
os.Stderr = stderrSaved
if err == nil {
t.Fatalf("expect error, but succeeded for %#v", case1)
}
}
}