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