github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/flag/flag_test.go (about)

     1  // Copyright 2009 The 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 flag_test
     6  
     7  import (
     8  	"bytes"
     9  	. "flag"
    10  	"fmt"
    11  	"os"
    12  	"sort"
    13  	"strings"
    14  	"testing"
    15  	"time"
    16  )
    17  
    18  func boolString(s string) string {
    19  	if s == "0" {
    20  		return "false"
    21  	}
    22  	return "true"
    23  }
    24  
    25  func TestEverything(t *testing.T) {
    26  	ResetForTesting(nil)
    27  	Bool("test_bool", false, "bool value")
    28  	Int("test_int", 0, "int value")
    29  	Int64("test_int64", 0, "int64 value")
    30  	Uint("test_uint", 0, "uint value")
    31  	Uint64("test_uint64", 0, "uint64 value")
    32  	String("test_string", "0", "string value")
    33  	Float64("test_float64", 0, "float64 value")
    34  	Duration("test_duration", 0, "time.Duration value")
    35  
    36  	m := make(map[string]*Flag)
    37  	desired := "0"
    38  	visitor := func(f *Flag) {
    39  		if len(f.Name) > 5 && f.Name[0:5] == "test_" {
    40  			m[f.Name] = f
    41  			ok := false
    42  			switch {
    43  			case f.Value.String() == desired:
    44  				ok = true
    45  			case f.Name == "test_bool" && f.Value.String() == boolString(desired):
    46  				ok = true
    47  			case f.Name == "test_duration" && f.Value.String() == desired+"s":
    48  				ok = true
    49  			}
    50  			if !ok {
    51  				t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
    52  			}
    53  		}
    54  	}
    55  	VisitAll(visitor)
    56  	if len(m) != 8 {
    57  		t.Error("VisitAll misses some flags")
    58  		for k, v := range m {
    59  			t.Log(k, *v)
    60  		}
    61  	}
    62  	m = make(map[string]*Flag)
    63  	Visit(visitor)
    64  	if len(m) != 0 {
    65  		t.Errorf("Visit sees unset flags")
    66  		for k, v := range m {
    67  			t.Log(k, *v)
    68  		}
    69  	}
    70  	// Now set all flags
    71  	Set("test_bool", "true")
    72  	Set("test_int", "1")
    73  	Set("test_int64", "1")
    74  	Set("test_uint", "1")
    75  	Set("test_uint64", "1")
    76  	Set("test_string", "1")
    77  	Set("test_float64", "1")
    78  	Set("test_duration", "1s")
    79  	desired = "1"
    80  	Visit(visitor)
    81  	if len(m) != 8 {
    82  		t.Error("Visit fails after set")
    83  		for k, v := range m {
    84  			t.Log(k, *v)
    85  		}
    86  	}
    87  	// Now test they're visited in sort order.
    88  	var flagNames []string
    89  	Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
    90  	if !sort.StringsAreSorted(flagNames) {
    91  		t.Errorf("flag names not sorted: %v", flagNames)
    92  	}
    93  }
    94  
    95  func TestUsage(t *testing.T) {
    96  	called := false
    97  	ResetForTesting(func() { called = true })
    98  	if CommandLine().Parse([]string{"-x"}) == nil {
    99  		t.Error("parse did not fail for unknown flag")
   100  	}
   101  	if !called {
   102  		t.Error("did not call Usage for unknown flag")
   103  	}
   104  }
   105  
   106  func testParse(f *FlagSet, t *testing.T) {
   107  	if f.Parsed() {
   108  		t.Error("f.Parse() = true before Parse")
   109  	}
   110  	boolFlag := f.Bool("bool", false, "bool value")
   111  	bool2Flag := f.Bool("bool2", false, "bool2 value")
   112  	intFlag := f.Int("int", 0, "int value")
   113  	int64Flag := f.Int64("int64", 0, "int64 value")
   114  	uintFlag := f.Uint("uint", 0, "uint value")
   115  	uint64Flag := f.Uint64("uint64", 0, "uint64 value")
   116  	stringFlag := f.String("string", "0", "string value")
   117  	float64Flag := f.Float64("float64", 0, "float64 value")
   118  	durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value")
   119  	extra := "one-extra-argument"
   120  	args := []string{
   121  		"-bool",
   122  		"-bool2=true",
   123  		"--int", "22",
   124  		"--int64", "0x23",
   125  		"-uint", "24",
   126  		"--uint64", "25",
   127  		"-string", "hello",
   128  		"-float64", "2718e28",
   129  		"-duration", "2m",
   130  		extra,
   131  	}
   132  	if err := f.Parse(args); err != nil {
   133  		t.Fatal(err)
   134  	}
   135  	if !f.Parsed() {
   136  		t.Error("f.Parse() = false after Parse")
   137  	}
   138  	if *boolFlag != true {
   139  		t.Error("bool flag should be true, is ", *boolFlag)
   140  	}
   141  	if *bool2Flag != true {
   142  		t.Error("bool2 flag should be true, is ", *bool2Flag)
   143  	}
   144  	if *intFlag != 22 {
   145  		t.Error("int flag should be 22, is ", *intFlag)
   146  	}
   147  	if *int64Flag != 0x23 {
   148  		t.Error("int64 flag should be 0x23, is ", *int64Flag)
   149  	}
   150  	if *uintFlag != 24 {
   151  		t.Error("uint flag should be 24, is ", *uintFlag)
   152  	}
   153  	if *uint64Flag != 25 {
   154  		t.Error("uint64 flag should be 25, is ", *uint64Flag)
   155  	}
   156  	if *stringFlag != "hello" {
   157  		t.Error("string flag should be `hello`, is ", *stringFlag)
   158  	}
   159  	if *float64Flag != 2718e28 {
   160  		t.Error("float64 flag should be 2718e28, is ", *float64Flag)
   161  	}
   162  	if *durationFlag != 2*time.Minute {
   163  		t.Error("duration flag should be 2m, is ", *durationFlag)
   164  	}
   165  	if len(f.Args()) != 1 {
   166  		t.Error("expected one argument, got", len(f.Args()))
   167  	} else if f.Args()[0] != extra {
   168  		t.Errorf("expected argument %q got %q", extra, f.Args()[0])
   169  	}
   170  }
   171  
   172  func TestParse(t *testing.T) {
   173  	ResetForTesting(func() { t.Error("bad parse") })
   174  	testParse(CommandLine(), t)
   175  }
   176  
   177  func TestFlagSetParse(t *testing.T) {
   178  	testParse(NewFlagSet("test", ContinueOnError), t)
   179  }
   180  
   181  // Declare a user-defined flag type.
   182  type flagVar []string
   183  
   184  func (f *flagVar) String() string {
   185  	return fmt.Sprint([]string(*f))
   186  }
   187  
   188  func (f *flagVar) Set(value string) error {
   189  	*f = append(*f, value)
   190  	return nil
   191  }
   192  
   193  func TestUserDefined(t *testing.T) {
   194  	var flags FlagSet
   195  	flags.Init("test", ContinueOnError)
   196  	var v flagVar
   197  	flags.Var(&v, "v", "usage")
   198  	if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil {
   199  		t.Error(err)
   200  	}
   201  	if len(v) != 3 {
   202  		t.Fatal("expected 3 args; got ", len(v))
   203  	}
   204  	expect := "[1 2 3]"
   205  	if v.String() != expect {
   206  		t.Errorf("expected value %q got %q", expect, v.String())
   207  	}
   208  }
   209  
   210  // Declare a user-defined boolean flag type.
   211  type boolFlagVar struct {
   212  	count int
   213  }
   214  
   215  func (b *boolFlagVar) String() string {
   216  	return fmt.Sprintf("%d", b.count)
   217  }
   218  
   219  func (b *boolFlagVar) Set(value string) error {
   220  	if value == "true" {
   221  		b.count++
   222  	}
   223  	return nil
   224  }
   225  
   226  func (b *boolFlagVar) IsBoolFlag() bool {
   227  	return b.count < 4
   228  }
   229  
   230  func TestUserDefinedBool(t *testing.T) {
   231  	var flags FlagSet
   232  	flags.Init("test", ContinueOnError)
   233  	var b boolFlagVar
   234  	var err error
   235  	flags.Var(&b, "b", "usage")
   236  	if err = flags.Parse([]string{"-b", "-b", "-b", "-b=true", "-b=false", "-b", "barg", "-b"}); err != nil {
   237  		if b.count < 4 {
   238  			t.Error(err)
   239  		}
   240  	}
   241  
   242  	if b.count != 4 {
   243  		t.Errorf("want: %d; got: %d", 4, b.count)
   244  	}
   245  
   246  	if err == nil {
   247  		t.Error("expected error; got none")
   248  	}
   249  }
   250  
   251  func TestSetOutput(t *testing.T) {
   252  	var flags FlagSet
   253  	var buf bytes.Buffer
   254  	flags.SetOutput(&buf)
   255  	flags.Init("test", ContinueOnError)
   256  	flags.Parse([]string{"-unknown"})
   257  	if out := buf.String(); !strings.Contains(out, "-unknown") {
   258  		t.Logf("expected output mentioning unknown; got %q", out)
   259  	}
   260  }
   261  
   262  // This tests that one can reset the flags. This still works but not well, and is
   263  // superseded by FlagSet.
   264  func TestChangingArgs(t *testing.T) {
   265  	ResetForTesting(func() { t.Fatal("bad parse") })
   266  	oldArgs := os.Args
   267  	defer func() { os.Args = oldArgs }()
   268  	os.Args = []string{"cmd", "-before", "subcmd", "-after", "args"}
   269  	before := Bool("before", false, "")
   270  	if err := CommandLine().Parse(os.Args[1:]); err != nil {
   271  		t.Fatal(err)
   272  	}
   273  	cmd := Arg(0)
   274  	os.Args = Args()
   275  	after := Bool("after", false, "")
   276  	Parse()
   277  	args := Args()
   278  
   279  	if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
   280  		t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
   281  	}
   282  }
   283  
   284  // Test that -help invokes the usage message and returns ErrHelp.
   285  func TestHelp(t *testing.T) {
   286  	var helpCalled = false
   287  	fs := NewFlagSet("help test", ContinueOnError)
   288  	fs.Usage = func() { helpCalled = true }
   289  	var flag bool
   290  	fs.BoolVar(&flag, "flag", false, "regular flag")
   291  	// Regular flag invocation should work
   292  	err := fs.Parse([]string{"-flag=true"})
   293  	if err != nil {
   294  		t.Fatal("expected no error; got ", err)
   295  	}
   296  	if !flag {
   297  		t.Error("flag was not set by -flag")
   298  	}
   299  	if helpCalled {
   300  		t.Error("help called for regular flag")
   301  		helpCalled = false // reset for next test
   302  	}
   303  	// Help flag should work as expected.
   304  	err = fs.Parse([]string{"-help"})
   305  	if err == nil {
   306  		t.Fatal("error expected")
   307  	}
   308  	if err != ErrHelp {
   309  		t.Fatal("expected ErrHelp; got ", err)
   310  	}
   311  	if !helpCalled {
   312  		t.Fatal("help was not called")
   313  	}
   314  	// If we define a help flag, that should override.
   315  	var help bool
   316  	fs.BoolVar(&help, "help", false, "help flag")
   317  	helpCalled = false
   318  	err = fs.Parse([]string{"-help"})
   319  	if err != nil {
   320  		t.Fatal("expected no error for defined -help; got ", err)
   321  	}
   322  	if helpCalled {
   323  		t.Fatal("help was called; should not have been for defined help flag")
   324  	}
   325  }