-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflagset_test.go
341 lines (283 loc) · 9.07 KB
/
flagset_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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
package flagstruct
import (
"bytes"
"flag"
"fmt"
"os"
"strconv"
"strings"
"testing"
"time"
)
type customVal int
func (i *customVal) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 64)
*i = customVal(v)
return err
}
func (i *customVal) Get() interface{} { return int(*i) }
func (i *customVal) String() string { return fmt.Sprintf("%v", *i) }
func TestStruct(t *testing.T) {
conf := struct {
TestBool bool `flag:"test_bool" usage:"bool value"`
TestInt int `flag:"test_int" usage:"int value"`
TestInt64 int64 `flag:"test_int64" usage:"int64 value"`
TestUint uint `flag:"test_uint" usage:"uint value"`
TestUint64 uint64 `flag:"test_uint64" usage:"uint64 value"`
_ struct{}
TestString string `flag:"test_string" usage:"string value"`
TestFloat64 float64 `flag:"test_float64" usage:"float64 value"`
TestDuration time.Duration `flag:"test_duration" usage:"time.Duration value~"`
TestCustom customVal `flag:"test_custom" usage:"~custom~ value"`
TestShort bool `flag:"x" usage:"short flag"`
NonFlag int
testunexported int
}{}
flagset := NewFlagSet("program", flag.ContinueOnError)
err := flagset.Struct(&conf)
if err != nil {
t.Error(err)
}
// Check to see each value is as expected.
m := make(map[string]*flag.Flag)
flagset.VisitAll(func(f *flag.Flag) {
m[f.Name] = f
switch {
case f.Value.String() == "0":
return
case f.Value.String() == "false":
return
case f.Name == "test_duration" && f.Value.String() == "0s":
return
case f.Name == "test_string" && f.Value.String() == "":
return
}
t.Error("bad value", f.Value.String(), "for", f.Name)
})
if len(m) != 10 {
t.Error("wrong number of flags", len(m))
}
flagset = NewFlagSet("program", flag.ContinueOnError)
flagset.Configure(&conf, []string{"-test_bool", "-test_duration=1.0s", "-test_custom=23", "-test_string=a.out"})
if !conf.TestBool {
t.Error("expected boolean flag to be true")
}
if conf.TestDuration.Seconds() != 1 {
t.Errorf("expected duration 1s, actual value %q", conf.TestDuration.String())
}
if conf.TestCustom != customVal(23) {
t.Errorf("expected customVal 23, actual value %q", conf.TestCustom.String())
}
// Test output
buf := bytes.Buffer{}
flagset.SetOutput(&buf)
flagset.PrintStruct(&conf)
expectedp := "" +
" -test_bool\n \tbool value (default true)\n" +
" -test_int int\n \tint value\n" +
" -test_int64 int\n \tint64 value\n" +
" -test_uint uint\n \tuint value\n" +
" -test_uint64 uint\n \tuint64 value\n" +
"\n" +
" -test_string string\n \tstring value (default \"a.out\")\n" +
" -test_float64 float\n \tfloat64 value\n" +
" -test_duration duration\n \ttime.Duration value~ (default 1s)\n" +
" -test_custom custom\n \tcustom value (default 23)\n" +
" -x\tshort flag\n"
if buf.String() != expectedp {
t.Error("print output differs from expected.")
t.Logf("expected:\n%q\n", expectedp)
t.Logf("actual:\n%q\n", buf.String())
}
}
func TestGlobal(t *testing.T) {
m := make(map[string]*flag.Flag)
visitor := func(f *flag.Flag) {
if !strings.HasPrefix(f.Name, "test_") {
return
}
m[f.Name] = f
if f.Value.String() != "false" {
t.Error("bad value", f.Value.String(), "for", f.Name)
}
}
conf := struct {
Bool bool `flag:"test_bool" usage:"bool value"`
}{}
// Test Struct + Parse
CommandLine = NewFlagSet("program", flag.ContinueOnError)
Struct(&conf)
CommandLine.VisitAll(visitor)
Parse()
if len(m) != 1 {
t.Error("wrong number of flags", len(m))
}
// Test Configure
CommandLine = NewFlagSet("program", flag.ContinueOnError)
Configure(&conf)
// Test output
buf := bytes.Buffer{}
CommandLine.SetOutput(&buf)
PrintStruct(&conf)
expectedp := " -test_bool\n \tbool value\n"
if buf.String() != expectedp {
t.Error("print output differs from expected.")
t.Logf("expected:\n%q\n", expectedp)
t.Logf("actual:\n%q\n", buf.String())
}
}
func TestBadTypes(t *testing.T) {
conf := struct {
TestInt16 int16 `flag:"test_int16" usage:"int16 value"`
}{}
CommandLine = NewFlagSet("program", flag.ContinueOnError)
err := Struct(&conf)
if err == nil || err.Error() != "unhandled flag type %!t(int16=0)" {
t.Error("unexpected error", err)
}
err = Configure(&conf)
if err == nil || err.Error() != "unhandled flag type %!t(int16=0)" {
t.Error("unexpected error", err)
}
defer func() {
r := recover()
if r == nil {
t.Error("expected panic did not occur")
}
if r.(error).Error() != "unhandled flag type %!t(int16=0)" {
t.Error("wrong error", r.(error).Error())
}
}()
CommandLine = NewFlagSet("program", flag.PanicOnError)
Struct(&conf)
}
func TestEnv(t *testing.T) {
conf := struct {
Ignored bool
NotFound bool `env:"NON_EXISTENT"`
EnvTest bool `env:"ENV_TEST"`
}{}
os.Setenv("ENV_TEST", "True")
CommandLine = NewFlagSet("program", flag.PanicOnError)
CommandLine.Struct(&conf)
CommandLine.ParseEnv()
if conf.EnvTest != true {
t.Error("expected EnvTest to be true")
}
os.Setenv("ENV_TEST", "0")
CommandLine.ParseEnv()
if conf.EnvTest != false {
t.Error("expected EnvTest to be false")
}
}
func TestBadEnv(t *testing.T) {
conf := struct {
TestInt16 int16 `env:"TEST_INT16"`
}{}
CommandLine = NewFlagSet("program", flag.ContinueOnError)
err := Struct(&conf)
if err == nil || err.Error() != "unhandled flag type %!t(int16=0)" {
t.Error("unexpected error", err)
}
err = CommandLine.Configure(&conf, []string{})
if err == nil || err.Error() != "unhandled flag type %!t(int16=0)" {
t.Error("unexpected error", err)
}
defer func() {
r := recover()
if r == nil {
t.Error("expected panic did not occur")
}
if r.(error).Error() != "unhandled flag type %!t(int16=0)" {
t.Error("wrong error", r.(error).Error())
}
}()
CommandLine = NewFlagSet("program", flag.PanicOnError)
Struct(&conf)
}
func TestBadEnvParse(t *testing.T) {
conf := struct {
EnvTest bool `env:"ENV_TEST"`
}{}
os.Setenv("ENV_TEST", "Invalid")
CommandLine = NewFlagSet("program", flag.ContinueOnError)
CommandLine.Struct(&conf)
err := CommandLine.ParseEnv()
if err == nil {
t.Fatal("expected err to not be nil")
}
CommandLine = NewFlagSet("program", flag.ContinueOnError)
CommandLine.Configure(&conf, []string{})
if err == nil {
t.Fatal("expected err to not be nil")
}
CommandLine = NewFlagSet("program", flag.ExitOnError)
Struct(&conf)
exitcode := 0
exit = func(code int) { exitcode = code }
ParseEnv()
if exitcode != 2 {
t.Errorf("exited with code %v, expected %v", exitcode, 2)
}
CommandLine = NewFlagSet("program", flag.PanicOnError)
Struct(&conf)
defer func() {
r := recover()
if r == nil {
t.Error("expected panic did not occur")
}
if r.(error).Error() != `strconv.ParseBool: parsing "Invalid": invalid syntax` {
t.Error("wrong error", r.(error).Error())
}
}()
ParseEnv()
}
func TestOut(t *testing.T) {
s := NewFlagSet("program", flag.ContinueOnError)
if s.out() != os.Stderr {
t.Error("expected out to default to stderr")
}
s.SetOutput(os.Stdout)
if s.out() != os.Stdout {
t.Error("expected out to set to stdout")
}
}
func TestStructUsage(t *testing.T) {
conf := struct {
X bool `flag:"x"`
Bool bool `flag:"test_bool" usage:"bool value"`
Str string `flag:"test_str"`
Str2 string `flag:"test_str2"`
_ struct{}
TestCustom customVal `flag:"test_custom" usage:"~custom~ value"`
}{X: true, Str: "x"}
buf := bytes.Buffer{}
CommandLine = NewFlagSet("program", flag.PanicOnError)
CommandLine.SetOutput(&buf)
CommandLine.Struct(&conf)
buf.Reset()
CommandLine.MakeUsage()()
expectedp := "Usage of program:\n -test_bool\n \tbool value\n -test_custom custom\n \tcustom value\n -test_str string\n \t (default \"x\")\n -test_str2 string\n \t\n -x\t (default true)\n"
if buf.String() != expectedp {
t.Errorf("usage output differs from expected.\nexpected:\n%q\nactual:\n%q\n", expectedp, buf.String())
}
buf.Reset()
CommandLine.MakeStructUsage(&conf)()
expectedp = "Usage of program:\n -x\t (default true)\n -test_bool\n \tbool value\n -test_str string\n \t (default \"x\")\n -test_str2 string\n \t\n\n -test_custom custom\n \tcustom value\n"
if buf.String() != expectedp {
t.Errorf("usage output differs from expected.\nexpected:\n%q\nactual:\n%q\n", expectedp, buf.String())
}
CommandLine.name = ""
buf.Reset()
CommandLine.MakeUsage()()
expectedp = "Usage:\n -test_bool\n \tbool value\n -test_custom custom\n \tcustom value\n -test_str string\n \t (default \"x\")\n -test_str2 string\n \t\n -x\t (default true)\n"
if buf.String() != expectedp {
t.Errorf("usage output differs from expected.\nexpected:\n%q\nactual:\n%q\n", expectedp, buf.String())
}
buf.Reset()
CommandLine.MakeStructUsage(&conf)()
expectedp = "Usage:\n -x\t (default true)\n -test_bool\n \tbool value\n -test_str string\n \t (default \"x\")\n -test_str2 string\n \t\n\n -test_custom custom\n \tcustom value\n"
if buf.String() != expectedp {
t.Errorf("usage output differs from expected.\nexpected:\n%q\nactual:\n%q\n", expectedp, buf.String())
}
}