github.com/google/syzkaller@v0.0.0-20240517125934-c0f1611a36d6/pkg/tool/flags_test.go (about) 1 // Copyright 2020 syzkaller project authors. All rights reserved. 2 // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file. 3 4 package tool 5 6 import ( 7 "flag" 8 "fmt" 9 "io" 10 "strings" 11 "testing" 12 13 "github.com/google/go-cmp/cmp" 14 ) 15 16 func TestParseFlags(t *testing.T) { 17 type Values struct { 18 Foo bool 19 Bar int 20 Baz string 21 } 22 type Test struct { 23 args string 24 vals *Values 25 } 26 tests := []Test{ 27 {"", &Values{false, 1, "baz"}}, 28 {"-foo -bar=2", &Values{true, 2, "baz"}}, 29 {"-foo -bar=2 -qux", nil}, 30 {"-foo -bar=2 " + OptionalFlags([]Flag{{"qux", ""}}), &Values{true, 2, "baz"}}, 31 } 32 for i, test := range tests { 33 t.Run(fmt.Sprint(i), func(t *testing.T) { 34 vals := new(Values) 35 flags := flag.NewFlagSet("", flag.ContinueOnError) 36 flags.SetOutput(io.Discard) 37 flags.BoolVar(&vals.Foo, "foo", false, "") 38 flags.IntVar(&vals.Bar, "bar", 1, "") 39 flags.StringVar(&vals.Baz, "baz", "baz", "") 40 args := append(strings.Split(test.args, " "), "arg0", "arg1") 41 if args[0] == "" { 42 args = args[1:] 43 } 44 err := ParseFlags(flags, args) 45 if test.vals == nil { 46 if err == nil { 47 t.Fatalf("parsing did not fail") 48 } 49 return 50 } 51 if err != nil { 52 t.Fatalf("parsing failed: %v", err) 53 } 54 if diff := cmp.Diff(test.vals, vals); diff != "" { 55 t.Fatal(diff) 56 } 57 if flags.NArg() != 2 || flags.Arg(0) != "arg0" || flags.Arg(1) != "arg1" { 58 t.Fatalf("bad args: %q", flags.Args()) 59 } 60 }) 61 } 62 } 63 64 func TestCfgsFlagString(t *testing.T) { 65 cfgs := &CfgsFlag{"a", "b", "c"} 66 if got, want := cfgs.String(), "[a b c]"; got != want { 67 t.Errorf("cfgs.String got: %s, want: %s", got, want) 68 } 69 } 70 71 func TestCfgsFlagSet(t *testing.T) { 72 cfgs := &CfgsFlag{} 73 if err := cfgs.Set("a, b, c"); err != nil { 74 t.Fatalf("cfgs.Set got: %v, want: nil", err) 75 } 76 if diff := cmp.Diff(*cfgs, CfgsFlag{"a", "b", "c"}); diff != "" { 77 t.Errorf("*cfgs mismatch (-want +got):\n%s", diff) 78 } 79 } 80 81 func TestCfgsFlagAlreadySet(t *testing.T) { 82 cfgs := &CfgsFlag{"a", "b", "c"} 83 if err := cfgs.Set("a, b, c"); err == nil { 84 t.Errorf("cfgs.Set got: nil, want: error") 85 } 86 }