aboutsummaryrefslogtreecommitdiffstats
path: root/pkg/tool/flags_test.go
diff options
context:
space:
mode:
authorDmitry Vyukov <dvyukov@google.com>2020-12-16 08:57:04 +0100
committerDmitry Vyukov <dvyukov@google.com>2020-12-25 10:12:41 +0100
commit3bcdec13657598f6a6163c7ddecff58c2d3a2a71 (patch)
tree3ff27333aeecc6eb7be333bc4407647792968ff1 /pkg/tool/flags_test.go
parent80795712865ca86bb21ebb9841598ccbcbd375c9 (diff)
pkg/tool: add package
Package tool contains various helper utilitites useful for implementation of command line tools. Currently it contains Fail/Failf functions that we commonly use and new support for optional command line flags.
Diffstat (limited to 'pkg/tool/flags_test.go')
-rw-r--r--pkg/tool/flags_test.go62
1 files changed, 62 insertions, 0 deletions
diff --git a/pkg/tool/flags_test.go b/pkg/tool/flags_test.go
new file mode 100644
index 000000000..6d52a4780
--- /dev/null
+++ b/pkg/tool/flags_test.go
@@ -0,0 +1,62 @@
+// Copyright 2020 syzkaller project authors. All rights reserved.
+// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
+
+package tool
+
+import (
+ "flag"
+ "fmt"
+ "io/ioutil"
+ "strings"
+ "testing"
+
+ "github.com/google/go-cmp/cmp"
+)
+
+func TestParseFlags(t *testing.T) {
+ type Values struct {
+ Foo bool
+ Bar int
+ Baz string
+ }
+ type Test struct {
+ args string
+ vals *Values
+ }
+ tests := []Test{
+ {"", &Values{false, 1, "baz"}},
+ {"-foo -bar=2", &Values{true, 2, "baz"}},
+ {"-foo -bar=2 -qux", nil},
+ {"-foo -bar=2 " + OptionalFlags(Flag{"qux", ""}), &Values{true, 2, "baz"}},
+ }
+ for i, test := range tests {
+ t.Run(fmt.Sprint(i), func(t *testing.T) {
+ vals := new(Values)
+ flags := flag.NewFlagSet("", flag.ContinueOnError)
+ flags.SetOutput(ioutil.Discard)
+ flags.BoolVar(&vals.Foo, "foo", false, "")
+ flags.IntVar(&vals.Bar, "bar", 1, "")
+ flags.StringVar(&vals.Baz, "baz", "baz", "")
+ args := append(strings.Split(test.args, " "), "arg0", "arg1")
+ if args[0] == "" {
+ args = args[1:]
+ }
+ err := parseFlags(flags, args)
+ if test.vals == nil {
+ if err == nil {
+ t.Fatalf("parsing did not fail")
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("parsing failed: %v", err)
+ }
+ if diff := cmp.Diff(test.vals, vals); diff != "" {
+ t.Fatal(diff)
+ }
+ if flags.NArg() != 2 || flags.Arg(0) != "arg0" || flags.Arg(1) != "arg1" {
+ t.Fatalf("bad args: %q", flags.Args())
+ }
+ })
+ }
+}