Black Lives Matter. Support the Equal Justice Initiative.

Source file src/flag/flag_test.go

Documentation: flag

     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  	"internal/testenv"
    12  	"io"
    13  	"io/ioutil"
    14  	"os"
    15  	"os/exec"
    16  	"runtime"
    17  	"sort"
    18  	"strconv"
    19  	"strings"
    20  	"testing"
    21  	"time"
    22  )
    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("test_bool", false, "bool value")
    34  	Int("test_int", 0, "int value")
    35  	Int64("test_int64", 0, "int64 value")
    36  	Uint("test_uint", 0, "uint value")
    37  	Uint64("test_uint64", 0, "uint64 value")
    38  	String("test_string", "0", "string value")
    39  	Float64("test_float64", 0, "float64 value")
    40  	Duration("test_duration", 0, "time.Duration value")
    41  
    42  	m := make(map[string]*Flag)
    43  	desired := "0"
    44  	visitor := func(f *Flag) {
    45  		if len(f.Name) > 5 && f.Name[0:5] == "test_" {
    46  			m[f.Name] = f
    47  			ok := false
    48  			switch {
    49  			case f.Value.String() == desired:
    50  				ok = true
    51  			case f.Name == "test_bool" && f.Value.String() == boolString(desired):
    52  				ok = true
    53  			case f.Name == "test_duration" && f.Value.String() == desired+"s":
    54  				ok = true
    55  			}
    56  			if !ok {
    57  				t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
    58  			}
    59  		}
    60  	}
    61  	VisitAll(visitor)
    62  	if len(m) != 8 {
    63  		t.Error("VisitAll misses some flags")
    64  		for k, v := range m {
    65  			t.Log(k, *v)
    66  		}
    67  	}
    68  	m = make(map[string]*Flag)
    69  	Visit(visitor)
    70  	if len(m) != 0 {
    71  		t.Errorf("Visit sees unset flags")
    72  		for k, v := range m {
    73  			t.Log(k, *v)
    74  		}
    75  	}
    76  	// Now set all flags
    77  	Set("test_bool", "true")
    78  	Set("test_int", "1")
    79  	Set("test_int64", "1")
    80  	Set("test_uint", "1")
    81  	Set("test_uint64", "1")
    82  	Set("test_string", "1")
    83  	Set("test_float64", "1")
    84  	Set("test_duration", "1s")
    85  	desired = "1"
    86  	Visit(visitor)
    87  	if len(m) != 8 {
    88  		t.Error("Visit fails after set")
    89  		for k, v := range m {
    90  			t.Log(k, *v)
    91  		}
    92  	}
    93  	// Now test they're visited in sort order.
    94  	var flagNames []string
    95  	Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
    96  	if !sort.StringsAreSorted(flagNames) {
    97  		t.Errorf("flag names not sorted: %v", flagNames)
    98  	}
    99  }
   100  
   101  func TestGet(t *testing.T) {
   102  	ResetForTesting(nil)
   103  	Bool("test_bool", true, "bool value")
   104  	Int("test_int", 1, "int value")
   105  	Int64("test_int64", 2, "int64 value")
   106  	Uint("test_uint", 3, "uint value")
   107  	Uint64("test_uint64", 4, "uint64 value")
   108  	String("test_string", "5", "string value")
   109  	Float64("test_float64", 6, "float64 value")
   110  	Duration("test_duration", 7, "time.Duration value")
   111  
   112  	visitor := func(f *Flag) {
   113  		if len(f.Name) > 5 && f.Name[0:5] == "test_" {
   114  			g, ok := f.Value.(Getter)
   115  			if !ok {
   116  				t.Errorf("Visit: value does not satisfy Getter: %T", f.Value)
   117  				return
   118  			}
   119  			switch f.Name {
   120  			case "test_bool":
   121  				ok = g.Get() == true
   122  			case "test_int":
   123  				ok = g.Get() == int(1)
   124  			case "test_int64":
   125  				ok = g.Get() == int64(2)
   126  			case "test_uint":
   127  				ok = g.Get() == uint(3)
   128  			case "test_uint64":
   129  				ok = g.Get() == uint64(4)
   130  			case "test_string":
   131  				ok = g.Get() == "5"
   132  			case "test_float64":
   133  				ok = g.Get() == float64(6)
   134  			case "test_duration":
   135  				ok = g.Get() == time.Duration(7)
   136  			}
   137  			if !ok {
   138  				t.Errorf("Visit: bad value %T(%v) for %s", g.Get(), g.Get(), f.Name)
   139  			}
   140  		}
   141  	}
   142  	VisitAll(visitor)
   143  }
   144  
   145  func TestUsage(t *testing.T) {
   146  	called := false
   147  	ResetForTesting(func() { called = true })
   148  	if CommandLine.Parse([]string{"-x"}) == nil {
   149  		t.Error("parse did not fail for unknown flag")
   150  	}
   151  	if !called {
   152  		t.Error("did not call Usage for unknown flag")
   153  	}
   154  }
   155  
   156  func testParse(f *FlagSet, t *testing.T) {
   157  	if f.Parsed() {
   158  		t.Error("f.Parse() = true before Parse")
   159  	}
   160  	boolFlag := f.Bool("bool", false, "bool value")
   161  	bool2Flag := f.Bool("bool2", false, "bool2 value")
   162  	intFlag := f.Int("int", 0, "int value")
   163  	int64Flag := f.Int64("int64", 0, "int64 value")
   164  	uintFlag := f.Uint("uint", 0, "uint value")
   165  	uint64Flag := f.Uint64("uint64", 0, "uint64 value")
   166  	stringFlag := f.String("string", "0", "string value")
   167  	float64Flag := f.Float64("float64", 0, "float64 value")
   168  	durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value")
   169  	extra := "one-extra-argument"
   170  	args := []string{
   171  		"-bool",
   172  		"-bool2=true",
   173  		"--int", "22",
   174  		"--int64", "0x23",
   175  		"-uint", "24",
   176  		"--uint64", "25",
   177  		"-string", "hello",
   178  		"-float64", "2718e28",
   179  		"-duration", "2m",
   180  		extra,
   181  	}
   182  	if err := f.Parse(args); err != nil {
   183  		t.Fatal(err)
   184  	}
   185  	if !f.Parsed() {
   186  		t.Error("f.Parse() = false after Parse")
   187  	}
   188  	if *boolFlag != true {
   189  		t.Error("bool flag should be true, is ", *boolFlag)
   190  	}
   191  	if *bool2Flag != true {
   192  		t.Error("bool2 flag should be true, is ", *bool2Flag)
   193  	}
   194  	if *intFlag != 22 {
   195  		t.Error("int flag should be 22, is ", *intFlag)
   196  	}
   197  	if *int64Flag != 0x23 {
   198  		t.Error("int64 flag should be 0x23, is ", *int64Flag)
   199  	}
   200  	if *uintFlag != 24 {
   201  		t.Error("uint flag should be 24, is ", *uintFlag)
   202  	}
   203  	if *uint64Flag != 25 {
   204  		t.Error("uint64 flag should be 25, is ", *uint64Flag)
   205  	}
   206  	if *stringFlag != "hello" {
   207  		t.Error("string flag should be `hello`, is ", *stringFlag)
   208  	}
   209  	if *float64Flag != 2718e28 {
   210  		t.Error("float64 flag should be 2718e28, is ", *float64Flag)
   211  	}
   212  	if *durationFlag != 2*time.Minute {
   213  		t.Error("duration flag should be 2m, is ", *durationFlag)
   214  	}
   215  	if len(f.Args()) != 1 {
   216  		t.Error("expected one argument, got", len(f.Args()))
   217  	} else if f.Args()[0] != extra {
   218  		t.Errorf("expected argument %q got %q", extra, f.Args()[0])
   219  	}
   220  }
   221  
   222  func TestParse(t *testing.T) {
   223  	ResetForTesting(func() { t.Error("bad parse") })
   224  	testParse(CommandLine, t)
   225  }
   226  
   227  func TestFlagSetParse(t *testing.T) {
   228  	testParse(NewFlagSet("test", ContinueOnError), t)
   229  }
   230  
   231  // Declare a user-defined flag type.
   232  type flagVar []string
   233  
   234  func (f *flagVar) String() string {
   235  	return fmt.Sprint([]string(*f))
   236  }
   237  
   238  func (f *flagVar) Set(value string) error {
   239  	*f = append(*f, value)
   240  	return nil
   241  }
   242  
   243  func TestUserDefined(t *testing.T) {
   244  	var flags FlagSet
   245  	flags.Init("test", ContinueOnError)
   246  	var v flagVar
   247  	flags.Var(&v, "v", "usage")
   248  	if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil {
   249  		t.Error(err)
   250  	}
   251  	if len(v) != 3 {
   252  		t.Fatal("expected 3 args; got ", len(v))
   253  	}
   254  	expect := "[1 2 3]"
   255  	if v.String() != expect {
   256  		t.Errorf("expected value %q got %q", expect, v.String())
   257  	}
   258  }
   259  
   260  func TestUserDefinedForCommandLine(t *testing.T) {
   261  	const help = "HELP"
   262  	var result string
   263  	ResetForTesting(func() { result = help })
   264  	Usage()
   265  	if result != help {
   266  		t.Fatalf("got %q; expected %q", result, help)
   267  	}
   268  }
   269  
   270  // Declare a user-defined boolean flag type.
   271  type boolFlagVar struct {
   272  	count int
   273  }
   274  
   275  func (b *boolFlagVar) String() string {
   276  	return fmt.Sprintf("%d", b.count)
   277  }
   278  
   279  func (b *boolFlagVar) Set(value string) error {
   280  	if value == "true" {
   281  		b.count++
   282  	}
   283  	return nil
   284  }
   285  
   286  func (b *boolFlagVar) IsBoolFlag() bool {
   287  	return b.count < 4
   288  }
   289  
   290  func TestUserDefinedBool(t *testing.T) {
   291  	var flags FlagSet
   292  	flags.Init("test", ContinueOnError)
   293  	var b boolFlagVar
   294  	var err error
   295  	flags.Var(&b, "b", "usage")
   296  	if err = flags.Parse([]string{"-b", "-b", "-b", "-b=true", "-b=false", "-b", "barg", "-b"}); err != nil {
   297  		if b.count < 4 {
   298  			t.Error(err)
   299  		}
   300  	}
   301  
   302  	if b.count != 4 {
   303  		t.Errorf("want: %d; got: %d", 4, b.count)
   304  	}
   305  
   306  	if err == nil {
   307  		t.Error("expected error; got none")
   308  	}
   309  }
   310  
   311  func TestSetOutput(t *testing.T) {
   312  	var flags FlagSet
   313  	var buf bytes.Buffer
   314  	flags.SetOutput(&buf)
   315  	flags.Init("test", ContinueOnError)
   316  	flags.Parse([]string{"-unknown"})
   317  	if out := buf.String(); !strings.Contains(out, "-unknown") {
   318  		t.Logf("expected output mentioning unknown; got %q", out)
   319  	}
   320  }
   321  
   322  // This tests that one can reset the flags. This still works but not well, and is
   323  // superseded by FlagSet.
   324  func TestChangingArgs(t *testing.T) {
   325  	ResetForTesting(func() { t.Fatal("bad parse") })
   326  	oldArgs := os.Args
   327  	defer func() { os.Args = oldArgs }()
   328  	os.Args = []string{"cmd", "-before", "subcmd", "-after", "args"}
   329  	before := Bool("before", false, "")
   330  	if err := CommandLine.Parse(os.Args[1:]); err != nil {
   331  		t.Fatal(err)
   332  	}
   333  	cmd := Arg(0)
   334  	os.Args = Args()
   335  	after := Bool("after", false, "")
   336  	Parse()
   337  	args := Args()
   338  
   339  	if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
   340  		t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
   341  	}
   342  }
   343  
   344  // Test that -help invokes the usage message and returns ErrHelp.
   345  func TestHelp(t *testing.T) {
   346  	var helpCalled = false
   347  	fs := NewFlagSet("help test", ContinueOnError)
   348  	fs.Usage = func() { helpCalled = true }
   349  	var flag bool
   350  	fs.BoolVar(&flag, "flag", false, "regular flag")
   351  	// Regular flag invocation should work
   352  	err := fs.Parse([]string{"-flag=true"})
   353  	if err != nil {
   354  		t.Fatal("expected no error; got ", err)
   355  	}
   356  	if !flag {
   357  		t.Error("flag was not set by -flag")
   358  	}
   359  	if helpCalled {
   360  		t.Error("help called for regular flag")
   361  		helpCalled = false // reset for next test
   362  	}
   363  	// Help flag should work as expected.
   364  	err = fs.Parse([]string{"-help"})
   365  	if err == nil {
   366  		t.Fatal("error expected")
   367  	}
   368  	if err != ErrHelp {
   369  		t.Fatal("expected ErrHelp; got ", err)
   370  	}
   371  	if !helpCalled {
   372  		t.Fatal("help was not called")
   373  	}
   374  	// If we define a help flag, that should override.
   375  	var help bool
   376  	fs.BoolVar(&help, "help", false, "help flag")
   377  	helpCalled = false
   378  	err = fs.Parse([]string{"-help"})
   379  	if err != nil {
   380  		t.Fatal("expected no error for defined -help; got ", err)
   381  	}
   382  	if helpCalled {
   383  		t.Fatal("help was called; should not have been for defined help flag")
   384  	}
   385  }
   386  
   387  const defaultOutput = `  -A	for bootstrapping, allow 'any' type
   388    -Alongflagname
   389      	disable bounds checking
   390    -C	a boolean defaulting to true (default true)
   391    -D path
   392      	set relative path for local imports
   393    -E string
   394      	issue 23543 (default "0")
   395    -F number
   396      	a non-zero number (default 2.7)
   397    -G float
   398      	a float that defaults to zero
   399    -M string
   400      	a multiline
   401      	help
   402      	string
   403    -N int
   404      	a non-zero int (default 27)
   405    -O	a flag
   406      	multiline help string (default true)
   407    -Z int
   408      	an int that defaults to zero
   409    -maxT timeout
   410      	set timeout for dial
   411  `
   412  
   413  func TestPrintDefaults(t *testing.T) {
   414  	fs := NewFlagSet("print defaults test", ContinueOnError)
   415  	var buf bytes.Buffer
   416  	fs.SetOutput(&buf)
   417  	fs.Bool("A", false, "for bootstrapping, allow 'any' type")
   418  	fs.Bool("Alongflagname", false, "disable bounds checking")
   419  	fs.Bool("C", true, "a boolean defaulting to true")
   420  	fs.String("D", "", "set relative `path` for local imports")
   421  	fs.String("E", "0", "issue 23543")
   422  	fs.Float64("F", 2.7, "a non-zero `number`")
   423  	fs.Float64("G", 0, "a float that defaults to zero")
   424  	fs.String("M", "", "a multiline\nhelp\nstring")
   425  	fs.Int("N", 27, "a non-zero int")
   426  	fs.Bool("O", true, "a flag\nmultiline help string")
   427  	fs.Int("Z", 0, "an int that defaults to zero")
   428  	fs.Duration("maxT", 0, "set `timeout` for dial")
   429  	fs.PrintDefaults()
   430  	got := buf.String()
   431  	if got != defaultOutput {
   432  		t.Errorf("got %q want %q\n", got, defaultOutput)
   433  	}
   434  }
   435  
   436  // Issue 19230: validate range of Int and Uint flag values.
   437  func TestIntFlagOverflow(t *testing.T) {
   438  	if strconv.IntSize != 32 {
   439  		return
   440  	}
   441  	ResetForTesting(nil)
   442  	Int("i", 0, "")
   443  	Uint("u", 0, "")
   444  	if err := Set("i", "2147483648"); err == nil {
   445  		t.Error("unexpected success setting Int")
   446  	}
   447  	if err := Set("u", "4294967296"); err == nil {
   448  		t.Error("unexpected success setting Uint")
   449  	}
   450  }
   451  
   452  // Issue 20998: Usage should respect CommandLine.output.
   453  func TestUsageOutput(t *testing.T) {
   454  	ResetForTesting(DefaultUsage)
   455  	var buf bytes.Buffer
   456  	CommandLine.SetOutput(&buf)
   457  	defer func(old []string) { os.Args = old }(os.Args)
   458  	os.Args = []string{"app", "-i=1", "-unknown"}
   459  	Parse()
   460  	const want = "flag provided but not defined: -i\nUsage of app:\n"
   461  	if got := buf.String(); got != want {
   462  		t.Errorf("output = %q; want %q", got, want)
   463  	}
   464  }
   465  
   466  func TestGetters(t *testing.T) {
   467  	expectedName := "flag set"
   468  	expectedErrorHandling := ContinueOnError
   469  	expectedOutput := io.Writer(os.Stderr)
   470  	fs := NewFlagSet(expectedName, expectedErrorHandling)
   471  
   472  	if fs.Name() != expectedName {
   473  		t.Errorf("unexpected name: got %s, expected %s", fs.Name(), expectedName)
   474  	}
   475  	if fs.ErrorHandling() != expectedErrorHandling {
   476  		t.Errorf("unexpected ErrorHandling: got %d, expected %d", fs.ErrorHandling(), expectedErrorHandling)
   477  	}
   478  	if fs.Output() != expectedOutput {
   479  		t.Errorf("unexpected output: got %#v, expected %#v", fs.Output(), expectedOutput)
   480  	}
   481  
   482  	expectedName = "gopher"
   483  	expectedErrorHandling = ExitOnError
   484  	expectedOutput = os.Stdout
   485  	fs.Init(expectedName, expectedErrorHandling)
   486  	fs.SetOutput(expectedOutput)
   487  
   488  	if fs.Name() != expectedName {
   489  		t.Errorf("unexpected name: got %s, expected %s", fs.Name(), expectedName)
   490  	}
   491  	if fs.ErrorHandling() != expectedErrorHandling {
   492  		t.Errorf("unexpected ErrorHandling: got %d, expected %d", fs.ErrorHandling(), expectedErrorHandling)
   493  	}
   494  	if fs.Output() != expectedOutput {
   495  		t.Errorf("unexpected output: got %v, expected %v", fs.Output(), expectedOutput)
   496  	}
   497  }
   498  
   499  func TestParseError(t *testing.T) {
   500  	for _, typ := range []string{"bool", "int", "int64", "uint", "uint64", "float64", "duration"} {
   501  		fs := NewFlagSet("parse error test", ContinueOnError)
   502  		fs.SetOutput(ioutil.Discard)
   503  		_ = fs.Bool("bool", false, "")
   504  		_ = fs.Int("int", 0, "")
   505  		_ = fs.Int64("int64", 0, "")
   506  		_ = fs.Uint("uint", 0, "")
   507  		_ = fs.Uint64("uint64", 0, "")
   508  		_ = fs.Float64("float64", 0, "")
   509  		_ = fs.Duration("duration", 0, "")
   510  		// Strings cannot give errors.
   511  		args := []string{"-" + typ + "=x"}
   512  		err := fs.Parse(args) // x is not a valid setting for any flag.
   513  		if err == nil {
   514  			t.Errorf("Parse(%q)=%v; expected parse error", args, err)
   515  			continue
   516  		}
   517  		if !strings.Contains(err.Error(), "invalid") || !strings.Contains(err.Error(), "parse error") {
   518  			t.Errorf("Parse(%q)=%v; expected parse error", args, err)
   519  		}
   520  	}
   521  }
   522  
   523  func TestRangeError(t *testing.T) {
   524  	bad := []string{
   525  		"-int=123456789012345678901",
   526  		"-int64=123456789012345678901",
   527  		"-uint=123456789012345678901",
   528  		"-uint64=123456789012345678901",
   529  		"-float64=1e1000",
   530  	}
   531  	for _, arg := range bad {
   532  		fs := NewFlagSet("parse error test", ContinueOnError)
   533  		fs.SetOutput(ioutil.Discard)
   534  		_ = fs.Int("int", 0, "")
   535  		_ = fs.Int64("int64", 0, "")
   536  		_ = fs.Uint("uint", 0, "")
   537  		_ = fs.Uint64("uint64", 0, "")
   538  		_ = fs.Float64("float64", 0, "")
   539  		// Strings cannot give errors, and bools and durations do not return strconv.NumError.
   540  		err := fs.Parse([]string{arg})
   541  		if err == nil {
   542  			t.Errorf("Parse(%q)=%v; expected range error", arg, err)
   543  			continue
   544  		}
   545  		if !strings.Contains(err.Error(), "invalid") || !strings.Contains(err.Error(), "value out of range") {
   546  			t.Errorf("Parse(%q)=%v; expected range error", arg, err)
   547  		}
   548  	}
   549  }
   550  
   551  func TestExitCode(t *testing.T) {
   552  	testenv.MustHaveExec(t)
   553  
   554  	magic := 123
   555  	if os.Getenv("GO_CHILD_FLAG") != "" {
   556  		fs := NewFlagSet("test", ExitOnError)
   557  		if os.Getenv("GO_CHILD_FLAG_HANDLE") != "" {
   558  			var b bool
   559  			fs.BoolVar(&b, os.Getenv("GO_CHILD_FLAG_HANDLE"), false, "")
   560  		}
   561  		fs.Parse([]string{os.Getenv("GO_CHILD_FLAG")})
   562  		os.Exit(magic)
   563  	}
   564  
   565  	tests := []struct {
   566  		flag       string
   567  		flagHandle string
   568  		expectExit int
   569  	}{
   570  		{
   571  			flag:       "-h",
   572  			expectExit: 0,
   573  		},
   574  		{
   575  			flag:       "-help",
   576  			expectExit: 0,
   577  		},
   578  		{
   579  			flag:       "-undefined",
   580  			expectExit: 2,
   581  		},
   582  		{
   583  			flag:       "-h",
   584  			flagHandle: "h",
   585  			expectExit: magic,
   586  		},
   587  		{
   588  			flag:       "-help",
   589  			flagHandle: "help",
   590  			expectExit: magic,
   591  		},
   592  	}
   593  
   594  	for _, test := range tests {
   595  		cmd := exec.Command(os.Args[0], "-test.run=TestExitCode")
   596  		cmd.Env = append(
   597  			os.Environ(),
   598  			"GO_CHILD_FLAG="+test.flag,
   599  			"GO_CHILD_FLAG_HANDLE="+test.flagHandle,
   600  		)
   601  		cmd.Run()
   602  		got := cmd.ProcessState.ExitCode()
   603  		// ExitCode is either 0 or 1 on Plan 9.
   604  		if runtime.GOOS == "plan9" && test.expectExit != 0 {
   605  			test.expectExit = 1
   606  		}
   607  		if got != test.expectExit {
   608  			t.Errorf("unexpected exit code for test case %+v \n: got %d, expect %d",
   609  				test, got, test.expectExit)
   610  		}
   611  	}
   612  }
   613  

View as plain text