github.com/xuyutom/docker@v1.6.0/pkg/mflag/flag_test.go (about) 1 // Copyright 2014-2015 The Docker & Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package mflag 6 7 import ( 8 "bytes" 9 "fmt" 10 "os" 11 "sort" 12 "strings" 13 "testing" 14 "time" 15 ) 16 17 // ResetForTesting clears all flag state and sets the usage function as directed. 18 // After calling ResetForTesting, parse errors in flag handling will not 19 // exit the program. 20 func ResetForTesting(usage func()) { 21 CommandLine = NewFlagSet(os.Args[0], ContinueOnError) 22 Usage = usage 23 } 24 func boolString(s string) string { 25 if s == "0" { 26 return "false" 27 } 28 return "true" 29 } 30 31 func TestEverything(t *testing.T) { 32 ResetForTesting(nil) 33 Bool([]string{"test_bool"}, false, "bool value") 34 Int([]string{"test_int"}, 0, "int value") 35 Int64([]string{"test_int64"}, 0, "int64 value") 36 Uint([]string{"test_uint"}, 0, "uint value") 37 Uint64([]string{"test_uint64"}, 0, "uint64 value") 38 String([]string{"test_string"}, "0", "string value") 39 Float64([]string{"test_float64"}, 0, "float64 value") 40 Duration([]string{"test_duration"}, 0, "time.Duration value") 41 42 m := make(map[string]*Flag) 43 desired := "0" 44 visitor := func(f *Flag) { 45 for _, name := range f.Names { 46 if len(name) > 5 && name[0:5] == "test_" { 47 m[name] = f 48 ok := false 49 switch { 50 case f.Value.String() == desired: 51 ok = true 52 case name == "test_bool" && f.Value.String() == boolString(desired): 53 ok = true 54 case name == "test_duration" && f.Value.String() == desired+"s": 55 ok = true 56 } 57 if !ok { 58 t.Error("Visit: bad value", f.Value.String(), "for", name) 59 } 60 } 61 } 62 } 63 VisitAll(visitor) 64 if len(m) != 8 { 65 t.Error("VisitAll misses some flags") 66 for k, v := range m { 67 t.Log(k, *v) 68 } 69 } 70 m = make(map[string]*Flag) 71 Visit(visitor) 72 if len(m) != 0 { 73 t.Errorf("Visit sees unset flags") 74 for k, v := range m { 75 t.Log(k, *v) 76 } 77 } 78 // Now set all flags 79 Set("test_bool", "true") 80 Set("test_int", "1") 81 Set("test_int64", "1") 82 Set("test_uint", "1") 83 Set("test_uint64", "1") 84 Set("test_string", "1") 85 Set("test_float64", "1") 86 Set("test_duration", "1s") 87 desired = "1" 88 Visit(visitor) 89 if len(m) != 8 { 90 t.Error("Visit fails after set") 91 for k, v := range m { 92 t.Log(k, *v) 93 } 94 } 95 // Now test they're visited in sort order. 96 var flagNames []string 97 Visit(func(f *Flag) { 98 for _, name := range f.Names { 99 flagNames = append(flagNames, name) 100 } 101 }) 102 if !sort.StringsAreSorted(flagNames) { 103 t.Errorf("flag names not sorted: %v", flagNames) 104 } 105 } 106 107 func TestGet(t *testing.T) { 108 ResetForTesting(nil) 109 Bool([]string{"test_bool"}, true, "bool value") 110 Int([]string{"test_int"}, 1, "int value") 111 Int64([]string{"test_int64"}, 2, "int64 value") 112 Uint([]string{"test_uint"}, 3, "uint value") 113 Uint64([]string{"test_uint64"}, 4, "uint64 value") 114 String([]string{"test_string"}, "5", "string value") 115 Float64([]string{"test_float64"}, 6, "float64 value") 116 Duration([]string{"test_duration"}, 7, "time.Duration value") 117 118 visitor := func(f *Flag) { 119 for _, name := range f.Names { 120 if len(name) > 5 && name[0:5] == "test_" { 121 g, ok := f.Value.(Getter) 122 if !ok { 123 t.Errorf("Visit: value does not satisfy Getter: %T", f.Value) 124 return 125 } 126 switch name { 127 case "test_bool": 128 ok = g.Get() == true 129 case "test_int": 130 ok = g.Get() == int(1) 131 case "test_int64": 132 ok = g.Get() == int64(2) 133 case "test_uint": 134 ok = g.Get() == uint(3) 135 case "test_uint64": 136 ok = g.Get() == uint64(4) 137 case "test_string": 138 ok = g.Get() == "5" 139 case "test_float64": 140 ok = g.Get() == float64(6) 141 case "test_duration": 142 ok = g.Get() == time.Duration(7) 143 } 144 if !ok { 145 t.Errorf("Visit: bad value %T(%v) for %s", g.Get(), g.Get(), name) 146 } 147 } 148 } 149 } 150 VisitAll(visitor) 151 } 152 153 func testParse(f *FlagSet, t *testing.T) { 154 if f.Parsed() { 155 t.Error("f.Parse() = true before Parse") 156 } 157 boolFlag := f.Bool([]string{"bool"}, false, "bool value") 158 bool2Flag := f.Bool([]string{"bool2"}, false, "bool2 value") 159 f.Bool([]string{"bool3"}, false, "bool3 value") 160 bool4Flag := f.Bool([]string{"bool4"}, false, "bool4 value") 161 intFlag := f.Int([]string{"-int"}, 0, "int value") 162 int64Flag := f.Int64([]string{"-int64"}, 0, "int64 value") 163 uintFlag := f.Uint([]string{"uint"}, 0, "uint value") 164 uint64Flag := f.Uint64([]string{"-uint64"}, 0, "uint64 value") 165 stringFlag := f.String([]string{"string"}, "0", "string value") 166 f.String([]string{"string2"}, "0", "string2 value") 167 singleQuoteFlag := f.String([]string{"squote"}, "", "single quoted value") 168 doubleQuoteFlag := f.String([]string{"dquote"}, "", "double quoted value") 169 mixedQuoteFlag := f.String([]string{"mquote"}, "", "mixed quoted value") 170 mixed2QuoteFlag := f.String([]string{"mquote2"}, "", "mixed2 quoted value") 171 nestedQuoteFlag := f.String([]string{"nquote"}, "", "nested quoted value") 172 nested2QuoteFlag := f.String([]string{"nquote2"}, "", "nested2 quoted value") 173 float64Flag := f.Float64([]string{"float64"}, 0, "float64 value") 174 durationFlag := f.Duration([]string{"duration"}, 5*time.Second, "time.Duration value") 175 extra := "one-extra-argument" 176 args := []string{ 177 "-bool", 178 "-bool2=true", 179 "-bool4=false", 180 "--int", "22", 181 "--int64", "0x23", 182 "-uint", "24", 183 "--uint64", "25", 184 "-string", "hello", 185 "-squote='single'", 186 `-dquote="double"`, 187 `-mquote='mixed"`, 188 `-mquote2="mixed2'`, 189 `-nquote="'single nested'"`, 190 `-nquote2='"double nested"'`, 191 "-float64", "2718e28", 192 "-duration", "2m", 193 extra, 194 } 195 if err := f.Parse(args); err != nil { 196 t.Fatal(err) 197 } 198 if !f.Parsed() { 199 t.Error("f.Parse() = false after Parse") 200 } 201 if *boolFlag != true { 202 t.Error("bool flag should be true, is ", *boolFlag) 203 } 204 if *bool2Flag != true { 205 t.Error("bool2 flag should be true, is ", *bool2Flag) 206 } 207 if !f.IsSet("bool2") { 208 t.Error("bool2 should be marked as set") 209 } 210 if f.IsSet("bool3") { 211 t.Error("bool3 should not be marked as set") 212 } 213 if !f.IsSet("bool4") { 214 t.Error("bool4 should be marked as set") 215 } 216 if *bool4Flag != false { 217 t.Error("bool4 flag should be false, is ", *bool4Flag) 218 } 219 if *intFlag != 22 { 220 t.Error("int flag should be 22, is ", *intFlag) 221 } 222 if *int64Flag != 0x23 { 223 t.Error("int64 flag should be 0x23, is ", *int64Flag) 224 } 225 if *uintFlag != 24 { 226 t.Error("uint flag should be 24, is ", *uintFlag) 227 } 228 if *uint64Flag != 25 { 229 t.Error("uint64 flag should be 25, is ", *uint64Flag) 230 } 231 if *stringFlag != "hello" { 232 t.Error("string flag should be `hello`, is ", *stringFlag) 233 } 234 if !f.IsSet("string") { 235 t.Error("string flag should be marked as set") 236 } 237 if f.IsSet("string2") { 238 t.Error("string2 flag should not be marked as set") 239 } 240 if *singleQuoteFlag != "single" { 241 t.Error("single quote string flag should be `single`, is ", *singleQuoteFlag) 242 } 243 if *doubleQuoteFlag != "double" { 244 t.Error("double quote string flag should be `double`, is ", *doubleQuoteFlag) 245 } 246 if *mixedQuoteFlag != `'mixed"` { 247 t.Error("mixed quote string flag should be `'mixed\"`, is ", *mixedQuoteFlag) 248 } 249 if *mixed2QuoteFlag != `"mixed2'` { 250 t.Error("mixed2 quote string flag should be `\"mixed2'`, is ", *mixed2QuoteFlag) 251 } 252 if *nestedQuoteFlag != "'single nested'" { 253 t.Error("nested quote string flag should be `'single nested'`, is ", *nestedQuoteFlag) 254 } 255 if *nested2QuoteFlag != `"double nested"` { 256 t.Error("double quote string flag should be `\"double nested\"`, is ", *nested2QuoteFlag) 257 } 258 if *float64Flag != 2718e28 { 259 t.Error("float64 flag should be 2718e28, is ", *float64Flag) 260 } 261 if *durationFlag != 2*time.Minute { 262 t.Error("duration flag should be 2m, is ", *durationFlag) 263 } 264 if len(f.Args()) != 1 { 265 t.Error("expected one argument, got", len(f.Args())) 266 } else if f.Args()[0] != extra { 267 t.Errorf("expected argument %q got %q", extra, f.Args()[0]) 268 } 269 } 270 271 func testPanic(f *FlagSet, t *testing.T) { 272 f.Int([]string{"-int"}, 0, "int value") 273 if f.Parsed() { 274 t.Error("f.Parse() = true before Parse") 275 } 276 args := []string{ 277 "-int", "21", 278 } 279 f.Parse(args) 280 } 281 282 func TestParsePanic(t *testing.T) { 283 ResetForTesting(func() {}) 284 testPanic(CommandLine, t) 285 } 286 287 func TestParse(t *testing.T) { 288 ResetForTesting(func() { t.Error("bad parse") }) 289 testParse(CommandLine, t) 290 } 291 292 func TestFlagSetParse(t *testing.T) { 293 testParse(NewFlagSet("test", ContinueOnError), t) 294 } 295 296 // Declare a user-defined flag type. 297 type flagVar []string 298 299 func (f *flagVar) String() string { 300 return fmt.Sprint([]string(*f)) 301 } 302 303 func (f *flagVar) Set(value string) error { 304 *f = append(*f, value) 305 return nil 306 } 307 308 func TestUserDefined(t *testing.T) { 309 var flags FlagSet 310 flags.Init("test", ContinueOnError) 311 var v flagVar 312 flags.Var(&v, []string{"v"}, "usage") 313 if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil { 314 t.Error(err) 315 } 316 if len(v) != 3 { 317 t.Fatal("expected 3 args; got ", len(v)) 318 } 319 expect := "[1 2 3]" 320 if v.String() != expect { 321 t.Errorf("expected value %q got %q", expect, v.String()) 322 } 323 } 324 325 // Declare a user-defined boolean flag type. 326 type boolFlagVar struct { 327 count int 328 } 329 330 func (b *boolFlagVar) String() string { 331 return fmt.Sprintf("%d", b.count) 332 } 333 334 func (b *boolFlagVar) Set(value string) error { 335 if value == "true" { 336 b.count++ 337 } 338 return nil 339 } 340 341 func (b *boolFlagVar) IsBoolFlag() bool { 342 return b.count < 4 343 } 344 345 func TestUserDefinedBool(t *testing.T) { 346 var flags FlagSet 347 flags.Init("test", ContinueOnError) 348 var b boolFlagVar 349 var err error 350 flags.Var(&b, []string{"b"}, "usage") 351 if err = flags.Parse([]string{"-b", "-b", "-b", "-b=true", "-b=false", "-b", "barg", "-b"}); err != nil { 352 if b.count < 4 { 353 t.Error(err) 354 } 355 } 356 357 if b.count != 4 { 358 t.Errorf("want: %d; got: %d", 4, b.count) 359 } 360 361 if err == nil { 362 t.Error("expected error; got none") 363 } 364 } 365 366 func TestSetOutput(t *testing.T) { 367 var flags FlagSet 368 var buf bytes.Buffer 369 flags.SetOutput(&buf) 370 flags.Init("test", ContinueOnError) 371 flags.Parse([]string{"-unknown"}) 372 if out := buf.String(); !strings.Contains(out, "-unknown") { 373 t.Logf("expected output mentioning unknown; got %q", out) 374 } 375 } 376 377 // This tests that one can reset the flags. This still works but not well, and is 378 // superseded by FlagSet. 379 func TestChangingArgs(t *testing.T) { 380 ResetForTesting(func() { t.Fatal("bad parse") }) 381 oldArgs := os.Args 382 defer func() { os.Args = oldArgs }() 383 os.Args = []string{"cmd", "-before", "subcmd", "-after", "args"} 384 before := Bool([]string{"before"}, false, "") 385 if err := CommandLine.Parse(os.Args[1:]); err != nil { 386 t.Fatal(err) 387 } 388 cmd := Arg(0) 389 os.Args = Args() 390 after := Bool([]string{"after"}, false, "") 391 Parse() 392 args := Args() 393 394 if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" { 395 t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args) 396 } 397 } 398 399 // Test that -help invokes the usage message and returns ErrHelp. 400 func TestHelp(t *testing.T) { 401 var helpCalled = false 402 fs := NewFlagSet("help test", ContinueOnError) 403 fs.Usage = func() { helpCalled = true } 404 var flag bool 405 fs.BoolVar(&flag, []string{"flag"}, false, "regular flag") 406 // Regular flag invocation should work 407 err := fs.Parse([]string{"-flag=true"}) 408 if err != nil { 409 t.Fatal("expected no error; got ", err) 410 } 411 if !flag { 412 t.Error("flag was not set by -flag") 413 } 414 if helpCalled { 415 t.Error("help called for regular flag") 416 helpCalled = false // reset for next test 417 } 418 // Help flag should work as expected. 419 err = fs.Parse([]string{"-help"}) 420 if err == nil { 421 t.Fatal("error expected") 422 } 423 if err != ErrHelp { 424 t.Fatal("expected ErrHelp; got ", err) 425 } 426 if !helpCalled { 427 t.Fatal("help was not called") 428 } 429 // If we define a help flag, that should override. 430 var help bool 431 fs.BoolVar(&help, []string{"help"}, false, "help flag") 432 helpCalled = false 433 err = fs.Parse([]string{"-help"}) 434 if err != nil { 435 t.Fatal("expected no error for defined -help; got ", err) 436 } 437 if helpCalled { 438 t.Fatal("help was called; should not have been for defined help flag") 439 } 440 } 441 442 // Test the flag count functions. 443 func TestFlagCounts(t *testing.T) { 444 fs := NewFlagSet("help test", ContinueOnError) 445 var flag bool 446 fs.BoolVar(&flag, []string{"flag1"}, false, "regular flag") 447 fs.BoolVar(&flag, []string{"#deprecated1"}, false, "regular flag") 448 fs.BoolVar(&flag, []string{"f", "flag2"}, false, "regular flag") 449 fs.BoolVar(&flag, []string{"#d", "#deprecated2"}, false, "regular flag") 450 fs.BoolVar(&flag, []string{"flag3"}, false, "regular flag") 451 fs.BoolVar(&flag, []string{"g", "#flag4", "-flag4"}, false, "regular flag") 452 453 if fs.FlagCount() != 6 { 454 t.Fatal("FlagCount wrong. ", fs.FlagCount()) 455 } 456 if fs.FlagCountUndeprecated() != 4 { 457 t.Fatal("FlagCountUndeprecated wrong. ", fs.FlagCountUndeprecated()) 458 } 459 if fs.NFlag() != 0 { 460 t.Fatal("NFlag wrong. ", fs.NFlag()) 461 } 462 err := fs.Parse([]string{"-fd", "-g", "-flag4"}) 463 if err != nil { 464 t.Fatal("expected no error for defined -help; got ", err) 465 } 466 if fs.NFlag() != 4 { 467 t.Fatal("NFlag wrong. ", fs.NFlag()) 468 } 469 } 470 471 // Show up bug in sortFlags 472 func TestSortFlags(t *testing.T) { 473 fs := NewFlagSet("help TestSortFlags", ContinueOnError) 474 475 var err error 476 477 var b bool 478 fs.BoolVar(&b, []string{"b", "-banana"}, false, "usage") 479 480 err = fs.Parse([]string{"--banana=true"}) 481 if err != nil { 482 t.Fatal("expected no error; got ", err) 483 } 484 485 count := 0 486 487 fs.VisitAll(func(flag *Flag) { 488 count++ 489 if flag == nil { 490 t.Fatal("VisitAll should not return a nil flag") 491 } 492 }) 493 flagcount := fs.FlagCount() 494 if flagcount != count { 495 t.Fatalf("FlagCount (%d) != number (%d) of elements visited", flagcount, count) 496 } 497 // Make sure its idempotent 498 if flagcount != fs.FlagCount() { 499 t.Fatalf("FlagCount (%d) != fs.FlagCount() (%d) of elements visited", flagcount, fs.FlagCount()) 500 } 501 502 count = 0 503 fs.Visit(func(flag *Flag) { 504 count++ 505 if flag == nil { 506 t.Fatal("Visit should not return a nil flag") 507 } 508 }) 509 nflag := fs.NFlag() 510 if nflag != count { 511 t.Fatalf("NFlag (%d) != number (%d) of elements visited", nflag, count) 512 } 513 if nflag != fs.NFlag() { 514 t.Fatalf("NFlag (%d) != fs.NFlag() (%d) of elements visited", nflag, fs.NFlag()) 515 } 516 }