Source file src/flag/flag_test.go

     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  	"os"
    14  	"os/exec"
    15  	"runtime"
    16  	"sort"
    17  	"strconv"
    18  	"strings"
    19  	"testing"
    20  	"time"
    21  )
    22  
    23  func boolString(s string) string {
    24  	if s == "0" {
    25  		return "false"
    26  	}
    27  	return "true"
    28  }
    29  
    30  func TestEverything(t *testing.T) {
    31  	ResetForTesting(nil)
    32  	Bool("test_bool", false, "bool value")
    33  	Int("test_int", 0, "int value")
    34  	Int64("test_int64", 0, "int64 value")
    35  	Uint("test_uint", 0, "uint value")
    36  	Uint64("test_uint64", 0, "uint64 value")
    37  	String("test_string", "0", "string value")
    38  	Float64("test_float64", 0, "float64 value")
    39  	Duration("test_duration", 0, "time.Duration value")
    40  	Func("test_func", "func value", func(string) error { return nil })
    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  			case f.Name == "test_func" && f.Value.String() == "":
    56  				ok = true
    57  			}
    58  			if !ok {
    59  				t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
    60  			}
    61  		}
    62  	}
    63  	VisitAll(visitor)
    64  	if len(m) != 9 {
    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  	Set("test_func", "1")
    88  	desired = "1"
    89  	Visit(visitor)
    90  	if len(m) != 9 {
    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) { flagNames = append(flagNames, f.Name) })
    99  	if !sort.StringsAreSorted(flagNames) {
   100  		t.Errorf("flag names not sorted: %v", flagNames)
   101  	}
   102  }
   103  
   104  func TestGet(t *testing.T) {
   105  	ResetForTesting(nil)
   106  	Bool("test_bool", true, "bool value")
   107  	Int("test_int", 1, "int value")
   108  	Int64("test_int64", 2, "int64 value")
   109  	Uint("test_uint", 3, "uint value")
   110  	Uint64("test_uint64", 4, "uint64 value")
   111  	String("test_string", "5", "string value")
   112  	Float64("test_float64", 6, "float64 value")
   113  	Duration("test_duration", 7, "time.Duration value")
   114  
   115  	visitor := func(f *Flag) {
   116  		if len(f.Name) > 5 && f.Name[0:5] == "test_" {
   117  			g, ok := f.Value.(Getter)
   118  			if !ok {
   119  				t.Errorf("Visit: value does not satisfy Getter: %T", f.Value)
   120  				return
   121  			}
   122  			switch f.Name {
   123  			case "test_bool":
   124  				ok = g.Get() == true
   125  			case "test_int":
   126  				ok = g.Get() == int(1)
   127  			case "test_int64":
   128  				ok = g.Get() == int64(2)
   129  			case "test_uint":
   130  				ok = g.Get() == uint(3)
   131  			case "test_uint64":
   132  				ok = g.Get() == uint64(4)
   133  			case "test_string":
   134  				ok = g.Get() == "5"
   135  			case "test_float64":
   136  				ok = g.Get() == float64(6)
   137  			case "test_duration":
   138  				ok = g.Get() == time.Duration(7)
   139  			}
   140  			if !ok {
   141  				t.Errorf("Visit: bad value %T(%v) for %s", g.Get(), g.Get(), f.Name)
   142  			}
   143  		}
   144  	}
   145  	VisitAll(visitor)
   146  }
   147  
   148  func TestUsage(t *testing.T) {
   149  	called := false
   150  	ResetForTesting(func() { called = true })
   151  	if CommandLine.Parse([]string{"-x"}) == nil {
   152  		t.Error("parse did not fail for unknown flag")
   153  	}
   154  	if !called {
   155  		t.Error("did not call Usage for unknown flag")
   156  	}
   157  }
   158  
   159  func testParse(f *FlagSet, t *testing.T) {
   160  	if f.Parsed() {
   161  		t.Error("f.Parse() = true before Parse")
   162  	}
   163  	boolFlag := f.Bool("bool", false, "bool value")
   164  	bool2Flag := f.Bool("bool2", false, "bool2 value")
   165  	intFlag := f.Int("int", 0, "int value")
   166  	int64Flag := f.Int64("int64", 0, "int64 value")
   167  	uintFlag := f.Uint("uint", 0, "uint value")
   168  	uint64Flag := f.Uint64("uint64", 0, "uint64 value")
   169  	stringFlag := f.String("string", "0", "string value")
   170  	float64Flag := f.Float64("float64", 0, "float64 value")
   171  	durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value")
   172  	extra := "one-extra-argument"
   173  	args := []string{
   174  		"-bool",
   175  		"-bool2=true",
   176  		"--int", "22",
   177  		"--int64", "0x23",
   178  		"-uint", "24",
   179  		"--uint64", "25",
   180  		"-string", "hello",
   181  		"-float64", "2718e28",
   182  		"-duration", "2m",
   183  		extra,
   184  	}
   185  	if err := f.Parse(args); err != nil {
   186  		t.Fatal(err)
   187  	}
   188  	if !f.Parsed() {
   189  		t.Error("f.Parse() = false after Parse")
   190  	}
   191  	if *boolFlag != true {
   192  		t.Error("bool flag should be true, is ", *boolFlag)
   193  	}
   194  	if *bool2Flag != true {
   195  		t.Error("bool2 flag should be true, is ", *bool2Flag)
   196  	}
   197  	if *intFlag != 22 {
   198  		t.Error("int flag should be 22, is ", *intFlag)
   199  	}
   200  	if *int64Flag != 0x23 {
   201  		t.Error("int64 flag should be 0x23, is ", *int64Flag)
   202  	}
   203  	if *uintFlag != 24 {
   204  		t.Error("uint flag should be 24, is ", *uintFlag)
   205  	}
   206  	if *uint64Flag != 25 {
   207  		t.Error("uint64 flag should be 25, is ", *uint64Flag)
   208  	}
   209  	if *stringFlag != "hello" {
   210  		t.Error("string flag should be `hello`, is ", *stringFlag)
   211  	}
   212  	if *float64Flag != 2718e28 {
   213  		t.Error("float64 flag should be 2718e28, is ", *float64Flag)
   214  	}
   215  	if *durationFlag != 2*time.Minute {
   216  		t.Error("duration flag should be 2m, is ", *durationFlag)
   217  	}
   218  	if len(f.Args()) != 1 {
   219  		t.Error("expected one argument, got", len(f.Args()))
   220  	} else if f.Args()[0] != extra {
   221  		t.Errorf("expected argument %q got %q", extra, f.Args()[0])
   222  	}
   223  }
   224  
   225  func TestParse(t *testing.T) {
   226  	ResetForTesting(func() { t.Error("bad parse") })
   227  	testParse(CommandLine, t)
   228  }
   229  
   230  func TestFlagSetParse(t *testing.T) {
   231  	testParse(NewFlagSet("test", ContinueOnError), t)
   232  }
   233  
   234  // Declare a user-defined flag type.
   235  type flagVar []string
   236  
   237  func (f *flagVar) String() string {
   238  	return fmt.Sprint([]string(*f))
   239  }
   240  
   241  func (f *flagVar) Set(value string) error {
   242  	*f = append(*f, value)
   243  	return nil
   244  }
   245  
   246  func TestUserDefined(t *testing.T) {
   247  	var flags FlagSet
   248  	flags.Init("test", ContinueOnError)
   249  	flags.SetOutput(io.Discard)
   250  	var v flagVar
   251  	flags.Var(&v, "v", "usage")
   252  	if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil {
   253  		t.Error(err)
   254  	}
   255  	if len(v) != 3 {
   256  		t.Fatal("expected 3 args; got ", len(v))
   257  	}
   258  	expect := "[1 2 3]"
   259  	if v.String() != expect {
   260  		t.Errorf("expected value %q got %q", expect, v.String())
   261  	}
   262  }
   263  
   264  func TestUserDefinedFunc(t *testing.T) {
   265  	flags := NewFlagSet("test", ContinueOnError)
   266  	flags.SetOutput(io.Discard)
   267  	var ss []string
   268  	flags.Func("v", "usage", func(s string) error {
   269  		ss = append(ss, s)
   270  		return nil
   271  	})
   272  	if err := flags.Parse([]string{"-v", "1", "-v", "2", "-v=3"}); err != nil {
   273  		t.Error(err)
   274  	}
   275  	if len(ss) != 3 {
   276  		t.Fatal("expected 3 args; got ", len(ss))
   277  	}
   278  	expect := "[1 2 3]"
   279  	if got := fmt.Sprint(ss); got != expect {
   280  		t.Errorf("expected value %q got %q", expect, got)
   281  	}
   282  	// test usage
   283  	var buf strings.Builder
   284  	flags.SetOutput(&buf)
   285  	flags.Parse([]string{"-h"})
   286  	if usage := buf.String(); !strings.Contains(usage, "usage") {
   287  		t.Errorf("usage string not included: %q", usage)
   288  	}
   289  	// test Func error
   290  	flags = NewFlagSet("test", ContinueOnError)
   291  	flags.SetOutput(io.Discard)
   292  	flags.Func("v", "usage", func(s string) error {
   293  		return fmt.Errorf("test error")
   294  	})
   295  	// flag not set, so no error
   296  	if err := flags.Parse(nil); err != nil {
   297  		t.Error(err)
   298  	}
   299  	// flag set, expect error
   300  	if err := flags.Parse([]string{"-v", "1"}); err == nil {
   301  		t.Error("expected error; got none")
   302  	} else if errMsg := err.Error(); !strings.Contains(errMsg, "test error") {
   303  		t.Errorf(`error should contain "test error"; got %q`, errMsg)
   304  	}
   305  }
   306  
   307  func TestUserDefinedForCommandLine(t *testing.T) {
   308  	const help = "HELP"
   309  	var result string
   310  	ResetForTesting(func() { result = help })
   311  	Usage()
   312  	if result != help {
   313  		t.Fatalf("got %q; expected %q", result, help)
   314  	}
   315  }
   316  
   317  // Declare a user-defined boolean flag type.
   318  type boolFlagVar struct {
   319  	count int
   320  }
   321  
   322  func (b *boolFlagVar) String() string {
   323  	return fmt.Sprintf("%d", b.count)
   324  }
   325  
   326  func (b *boolFlagVar) Set(value string) error {
   327  	if value == "true" {
   328  		b.count++
   329  	}
   330  	return nil
   331  }
   332  
   333  func (b *boolFlagVar) IsBoolFlag() bool {
   334  	return b.count < 4
   335  }
   336  
   337  func TestUserDefinedBool(t *testing.T) {
   338  	var flags FlagSet
   339  	flags.Init("test", ContinueOnError)
   340  	flags.SetOutput(io.Discard)
   341  	var b boolFlagVar
   342  	var err error
   343  	flags.Var(&b, "b", "usage")
   344  	if err = flags.Parse([]string{"-b", "-b", "-b", "-b=true", "-b=false", "-b", "barg", "-b"}); err != nil {
   345  		if b.count < 4 {
   346  			t.Error(err)
   347  		}
   348  	}
   349  
   350  	if b.count != 4 {
   351  		t.Errorf("want: %d; got: %d", 4, b.count)
   352  	}
   353  
   354  	if err == nil {
   355  		t.Error("expected error; got none")
   356  	}
   357  }
   358  
   359  func TestSetOutput(t *testing.T) {
   360  	var flags FlagSet
   361  	var buf bytes.Buffer
   362  	flags.SetOutput(&buf)
   363  	flags.Init("test", ContinueOnError)
   364  	flags.Parse([]string{"-unknown"})
   365  	if out := buf.String(); !strings.Contains(out, "-unknown") {
   366  		t.Logf("expected output mentioning unknown; got %q", out)
   367  	}
   368  }
   369  
   370  // This tests that one can reset the flags. This still works but not well, and is
   371  // superseded by FlagSet.
   372  func TestChangingArgs(t *testing.T) {
   373  	ResetForTesting(func() { t.Fatal("bad parse") })
   374  	oldArgs := os.Args
   375  	defer func() { os.Args = oldArgs }()
   376  	os.Args = []string{"cmd", "-before", "subcmd", "-after", "args"}
   377  	before := Bool("before", false, "")
   378  	if err := CommandLine.Parse(os.Args[1:]); err != nil {
   379  		t.Fatal(err)
   380  	}
   381  	cmd := Arg(0)
   382  	os.Args = Args()
   383  	after := Bool("after", false, "")
   384  	Parse()
   385  	args := Args()
   386  
   387  	if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
   388  		t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
   389  	}
   390  }
   391  
   392  // Test that -help invokes the usage message and returns ErrHelp.
   393  func TestHelp(t *testing.T) {
   394  	var helpCalled = false
   395  	fs := NewFlagSet("help test", ContinueOnError)
   396  	fs.Usage = func() { helpCalled = true }
   397  	var flag bool
   398  	fs.BoolVar(&flag, "flag", false, "regular flag")
   399  	// Regular flag invocation should work
   400  	err := fs.Parse([]string{"-flag=true"})
   401  	if err != nil {
   402  		t.Fatal("expected no error; got ", err)
   403  	}
   404  	if !flag {
   405  		t.Error("flag was not set by -flag")
   406  	}
   407  	if helpCalled {
   408  		t.Error("help called for regular flag")
   409  		helpCalled = false // reset for next test
   410  	}
   411  	// Help flag should work as expected.
   412  	err = fs.Parse([]string{"-help"})
   413  	if err == nil {
   414  		t.Fatal("error expected")
   415  	}
   416  	if err != ErrHelp {
   417  		t.Fatal("expected ErrHelp; got ", err)
   418  	}
   419  	if !helpCalled {
   420  		t.Fatal("help was not called")
   421  	}
   422  	// If we define a help flag, that should override.
   423  	var help bool
   424  	fs.BoolVar(&help, "help", false, "help flag")
   425  	helpCalled = false
   426  	err = fs.Parse([]string{"-help"})
   427  	if err != nil {
   428  		t.Fatal("expected no error for defined -help; got ", err)
   429  	}
   430  	if helpCalled {
   431  		t.Fatal("help was called; should not have been for defined help flag")
   432  	}
   433  }
   434  
   435  // zeroPanicker is a flag.Value whose String method panics if its dontPanic
   436  // field is false.
   437  type zeroPanicker struct {
   438  	dontPanic bool
   439  	v         string
   440  }
   441  
   442  func (f *zeroPanicker) Set(s string) error {
   443  	f.v = s
   444  	return nil
   445  }
   446  
   447  func (f *zeroPanicker) String() string {
   448  	if !f.dontPanic {
   449  		panic("panic!")
   450  	}
   451  	return f.v
   452  }
   453  
   454  const defaultOutput = `  -A	for bootstrapping, allow 'any' type
   455    -Alongflagname
   456      	disable bounds checking
   457    -C	a boolean defaulting to true (default true)
   458    -D path
   459      	set relative path for local imports
   460    -E string
   461      	issue 23543 (default "0")
   462    -F number
   463      	a non-zero number (default 2.7)
   464    -G float
   465      	a float that defaults to zero
   466    -M string
   467      	a multiline
   468      	help
   469      	string
   470    -N int
   471      	a non-zero int (default 27)
   472    -O	a flag
   473      	multiline help string (default true)
   474    -V list
   475      	a list of strings (default [a b])
   476    -Z int
   477      	an int that defaults to zero
   478    -ZP0 value
   479      	a flag whose String method panics when it is zero
   480    -ZP1 value
   481      	a flag whose String method panics when it is zero
   482    -maxT timeout
   483      	set timeout for dial
   484  
   485  panic calling String method on zero flag_test.zeroPanicker for flag ZP0: panic!
   486  panic calling String method on zero flag_test.zeroPanicker for flag ZP1: panic!
   487  `
   488  
   489  func TestPrintDefaults(t *testing.T) {
   490  	fs := NewFlagSet("print defaults test", ContinueOnError)
   491  	var buf bytes.Buffer
   492  	fs.SetOutput(&buf)
   493  	fs.Bool("A", false, "for bootstrapping, allow 'any' type")
   494  	fs.Bool("Alongflagname", false, "disable bounds checking")
   495  	fs.Bool("C", true, "a boolean defaulting to true")
   496  	fs.String("D", "", "set relative `path` for local imports")
   497  	fs.String("E", "0", "issue 23543")
   498  	fs.Float64("F", 2.7, "a non-zero `number`")
   499  	fs.Float64("G", 0, "a float that defaults to zero")
   500  	fs.String("M", "", "a multiline\nhelp\nstring")
   501  	fs.Int("N", 27, "a non-zero int")
   502  	fs.Bool("O", true, "a flag\nmultiline help string")
   503  	fs.Var(&flagVar{"a", "b"}, "V", "a `list` of strings")
   504  	fs.Int("Z", 0, "an int that defaults to zero")
   505  	fs.Var(&zeroPanicker{true, ""}, "ZP0", "a flag whose String method panics when it is zero")
   506  	fs.Var(&zeroPanicker{true, "something"}, "ZP1", "a flag whose String method panics when it is zero")
   507  	fs.Duration("maxT", 0, "set `timeout` for dial")
   508  	fs.PrintDefaults()
   509  	got := buf.String()
   510  	if got != defaultOutput {
   511  		t.Errorf("got:\n%q\nwant:\n%q", got, defaultOutput)
   512  	}
   513  }
   514  
   515  // Issue 19230: validate range of Int and Uint flag values.
   516  func TestIntFlagOverflow(t *testing.T) {
   517  	if strconv.IntSize != 32 {
   518  		return
   519  	}
   520  	ResetForTesting(nil)
   521  	Int("i", 0, "")
   522  	Uint("u", 0, "")
   523  	if err := Set("i", "2147483648"); err == nil {
   524  		t.Error("unexpected success setting Int")
   525  	}
   526  	if err := Set("u", "4294967296"); err == nil {
   527  		t.Error("unexpected success setting Uint")
   528  	}
   529  }
   530  
   531  // Issue 20998: Usage should respect CommandLine.output.
   532  func TestUsageOutput(t *testing.T) {
   533  	ResetForTesting(DefaultUsage)
   534  	var buf bytes.Buffer
   535  	CommandLine.SetOutput(&buf)
   536  	defer func(old []string) { os.Args = old }(os.Args)
   537  	os.Args = []string{"app", "-i=1", "-unknown"}
   538  	Parse()
   539  	const want = "flag provided but not defined: -i\nUsage of app:\n"
   540  	if got := buf.String(); got != want {
   541  		t.Errorf("output = %q; want %q", got, want)
   542  	}
   543  }
   544  
   545  func TestGetters(t *testing.T) {
   546  	expectedName := "flag set"
   547  	expectedErrorHandling := ContinueOnError
   548  	expectedOutput := io.Writer(os.Stderr)
   549  	fs := NewFlagSet(expectedName, expectedErrorHandling)
   550  
   551  	if fs.Name() != expectedName {
   552  		t.Errorf("unexpected name: got %s, expected %s", fs.Name(), expectedName)
   553  	}
   554  	if fs.ErrorHandling() != expectedErrorHandling {
   555  		t.Errorf("unexpected ErrorHandling: got %d, expected %d", fs.ErrorHandling(), expectedErrorHandling)
   556  	}
   557  	if fs.Output() != expectedOutput {
   558  		t.Errorf("unexpected output: got %#v, expected %#v", fs.Output(), expectedOutput)
   559  	}
   560  
   561  	expectedName = "gopher"
   562  	expectedErrorHandling = ExitOnError
   563  	expectedOutput = os.Stdout
   564  	fs.Init(expectedName, expectedErrorHandling)
   565  	fs.SetOutput(expectedOutput)
   566  
   567  	if fs.Name() != expectedName {
   568  		t.Errorf("unexpected name: got %s, expected %s", fs.Name(), expectedName)
   569  	}
   570  	if fs.ErrorHandling() != expectedErrorHandling {
   571  		t.Errorf("unexpected ErrorHandling: got %d, expected %d", fs.ErrorHandling(), expectedErrorHandling)
   572  	}
   573  	if fs.Output() != expectedOutput {
   574  		t.Errorf("unexpected output: got %v, expected %v", fs.Output(), expectedOutput)
   575  	}
   576  }
   577  
   578  func TestParseError(t *testing.T) {
   579  	for _, typ := range []string{"bool", "int", "int64", "uint", "uint64", "float64", "duration"} {
   580  		fs := NewFlagSet("parse error test", ContinueOnError)
   581  		fs.SetOutput(io.Discard)
   582  		_ = fs.Bool("bool", false, "")
   583  		_ = fs.Int("int", 0, "")
   584  		_ = fs.Int64("int64", 0, "")
   585  		_ = fs.Uint("uint", 0, "")
   586  		_ = fs.Uint64("uint64", 0, "")
   587  		_ = fs.Float64("float64", 0, "")
   588  		_ = fs.Duration("duration", 0, "")
   589  		// Strings cannot give errors.
   590  		args := []string{"-" + typ + "=x"}
   591  		err := fs.Parse(args) // x is not a valid setting for any flag.
   592  		if err == nil {
   593  			t.Errorf("Parse(%q)=%v; expected parse error", args, err)
   594  			continue
   595  		}
   596  		if !strings.Contains(err.Error(), "invalid") || !strings.Contains(err.Error(), "parse error") {
   597  			t.Errorf("Parse(%q)=%v; expected parse error", args, err)
   598  		}
   599  	}
   600  }
   601  
   602  func TestRangeError(t *testing.T) {
   603  	bad := []string{
   604  		"-int=123456789012345678901",
   605  		"-int64=123456789012345678901",
   606  		"-uint=123456789012345678901",
   607  		"-uint64=123456789012345678901",
   608  		"-float64=1e1000",
   609  	}
   610  	for _, arg := range bad {
   611  		fs := NewFlagSet("parse error test", ContinueOnError)
   612  		fs.SetOutput(io.Discard)
   613  		_ = fs.Int("int", 0, "")
   614  		_ = fs.Int64("int64", 0, "")
   615  		_ = fs.Uint("uint", 0, "")
   616  		_ = fs.Uint64("uint64", 0, "")
   617  		_ = fs.Float64("float64", 0, "")
   618  		// Strings cannot give errors, and bools and durations do not return strconv.NumError.
   619  		err := fs.Parse([]string{arg})
   620  		if err == nil {
   621  			t.Errorf("Parse(%q)=%v; expected range error", arg, err)
   622  			continue
   623  		}
   624  		if !strings.Contains(err.Error(), "invalid") || !strings.Contains(err.Error(), "value out of range") {
   625  			t.Errorf("Parse(%q)=%v; expected range error", arg, err)
   626  		}
   627  	}
   628  }
   629  
   630  func TestExitCode(t *testing.T) {
   631  	testenv.MustHaveExec(t)
   632  
   633  	magic := 123
   634  	if os.Getenv("GO_CHILD_FLAG") != "" {
   635  		fs := NewFlagSet("test", ExitOnError)
   636  		if os.Getenv("GO_CHILD_FLAG_HANDLE") != "" {
   637  			var b bool
   638  			fs.BoolVar(&b, os.Getenv("GO_CHILD_FLAG_HANDLE"), false, "")
   639  		}
   640  		fs.Parse([]string{os.Getenv("GO_CHILD_FLAG")})
   641  		os.Exit(magic)
   642  	}
   643  
   644  	tests := []struct {
   645  		flag       string
   646  		flagHandle string
   647  		expectExit int
   648  	}{
   649  		{
   650  			flag:       "-h",
   651  			expectExit: 0,
   652  		},
   653  		{
   654  			flag:       "-help",
   655  			expectExit: 0,
   656  		},
   657  		{
   658  			flag:       "-undefined",
   659  			expectExit: 2,
   660  		},
   661  		{
   662  			flag:       "-h",
   663  			flagHandle: "h",
   664  			expectExit: magic,
   665  		},
   666  		{
   667  			flag:       "-help",
   668  			flagHandle: "help",
   669  			expectExit: magic,
   670  		},
   671  	}
   672  
   673  	for _, test := range tests {
   674  		cmd := exec.Command(os.Args[0], "-test.run=TestExitCode")
   675  		cmd.Env = append(
   676  			os.Environ(),
   677  			"GO_CHILD_FLAG="+test.flag,
   678  			"GO_CHILD_FLAG_HANDLE="+test.flagHandle,
   679  		)
   680  		cmd.Run()
   681  		got := cmd.ProcessState.ExitCode()
   682  		// ExitCode is either 0 or 1 on Plan 9.
   683  		if runtime.GOOS == "plan9" && test.expectExit != 0 {
   684  			test.expectExit = 1
   685  		}
   686  		if got != test.expectExit {
   687  			t.Errorf("unexpected exit code for test case %+v \n: got %d, expect %d",
   688  				test, got, test.expectExit)
   689  		}
   690  	}
   691  }
   692  
   693  func mustPanic(t *testing.T, testName string, expected string, f func()) {
   694  	t.Helper()
   695  	defer func() {
   696  		switch msg := recover().(type) {
   697  		case nil:
   698  			t.Errorf("%s\n: expected panic(%q), but did not panic", testName, expected)
   699  		case string:
   700  			if msg != expected {
   701  				t.Errorf("%s\n: expected panic(%q), but got panic(%q)", testName, expected, msg)
   702  			}
   703  		default:
   704  			t.Errorf("%s\n: expected panic(%q), but got panic(%T%v)", testName, expected, msg, msg)
   705  		}
   706  	}()
   707  	f()
   708  }
   709  
   710  func TestInvalidFlags(t *testing.T) {
   711  	tests := []struct {
   712  		flag     string
   713  		errorMsg string
   714  	}{
   715  		{
   716  			flag:     "-foo",
   717  			errorMsg: "flag \"-foo\" begins with -",
   718  		},
   719  		{
   720  			flag:     "foo=bar",
   721  			errorMsg: "flag \"foo=bar\" contains =",
   722  		},
   723  	}
   724  
   725  	for _, test := range tests {
   726  		testName := fmt.Sprintf("FlagSet.Var(&v, %q, \"\")", test.flag)
   727  
   728  		fs := NewFlagSet("", ContinueOnError)
   729  		buf := bytes.NewBuffer(nil)
   730  		fs.SetOutput(buf)
   731  
   732  		mustPanic(t, testName, test.errorMsg, func() {
   733  			var v flagVar
   734  			fs.Var(&v, test.flag, "")
   735  		})
   736  		if msg := test.errorMsg + "\n"; msg != buf.String() {
   737  			t.Errorf("%s\n: unexpected output: expected %q, bug got %q", testName, msg, buf)
   738  		}
   739  	}
   740  }
   741  
   742  func TestRedefinedFlags(t *testing.T) {
   743  	tests := []struct {
   744  		flagSetName string
   745  		errorMsg    string
   746  	}{
   747  		{
   748  			flagSetName: "",
   749  			errorMsg:    "flag redefined: foo",
   750  		},
   751  		{
   752  			flagSetName: "fs",
   753  			errorMsg:    "fs flag redefined: foo",
   754  		},
   755  	}
   756  
   757  	for _, test := range tests {
   758  		testName := fmt.Sprintf("flag redefined in FlagSet(%q)", test.flagSetName)
   759  
   760  		fs := NewFlagSet(test.flagSetName, ContinueOnError)
   761  		buf := bytes.NewBuffer(nil)
   762  		fs.SetOutput(buf)
   763  
   764  		var v flagVar
   765  		fs.Var(&v, "foo", "")
   766  
   767  		mustPanic(t, testName, test.errorMsg, func() {
   768  			fs.Var(&v, "foo", "")
   769  		})
   770  		if msg := test.errorMsg + "\n"; msg != buf.String() {
   771  			t.Errorf("%s\n: unexpected output: expected %q, bug got %q", testName, msg, buf)
   772  		}
   773  	}
   774  }
   775  

View as plain text