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