From ac8b4247cece7a1e0518e7cef811fff4046ecd07 Mon Sep 17 00:00:00 2001 From: Ivan Klymenchenko Date: Wed, 30 Dec 2020 16:36:30 +0200 Subject: [PATCH] Add more tests --- options.go | 9 +++++++- options_test.go | 57 +++++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 58 insertions(+), 8 deletions(-) diff --git a/options.go b/options.go index af6342b..f16a387 100644 --- a/options.go +++ b/options.go @@ -28,6 +28,12 @@ const ( DebugUsage = "Print all commands to ~/.config/smug/smug.log" ) +// Creates a new FlagSet. +// Moved it to a variable to be able to override it in the tests. +var NewFlagSet = func(cmd string) *pflag.FlagSet { + return pflag.NewFlagSet(cmd, pflag.ContinueOnError) +} + func ParseOptions(argv []string, helpRequested func()) (Options, error) { if len(argv) < 2 { helpRequested() @@ -37,7 +43,8 @@ func ParseOptions(argv []string, helpRequested func()) (Options, error) { cmd := argv[0] project := argv[1] - flags := pflag.NewFlagSet(cmd, 0) + flags := NewFlagSet(cmd) + windows := flags.StringArrayP("windows", "w", []string{}, WindowsUsage) attach := flags.BoolP("attach", "a", false, AttachUsage) debug := flags.BoolP("debug", "d", false, DebugUsage) diff --git a/options_test.go b/options_test.go index 1ba517b..d392344 100644 --- a/options_test.go +++ b/options_test.go @@ -3,44 +3,87 @@ package main import ( "reflect" "testing" + + "github.com/spf13/pflag" ) var usageTestTable = []struct { - argv []string - opts Options + argv []string + opts Options + err error + helpCalls int }{ { []string{"start", "smug"}, Options{"start", "smug", []string{}, false, false}, + nil, + 0, }, { []string{"start", "smug", "-w", "foo"}, Options{"start", "smug", []string{"foo"}, false, false}, + nil, + 0, }, { []string{"start", "smug:foo,bar"}, Options{"start", "smug", []string{"foo", "bar"}, false, false}, + nil, + 0, }, { []string{"start", "smug", "--attach", "--debug"}, Options{"start", "smug", []string{}, true, true}, + nil, + 0, }, { []string{"start", "smug", "-ad"}, Options{"start", "smug", []string{}, true, true}, + nil, + 0, + }, + { + []string{"start"}, + Options{}, + ErrHelp, + 1, + }, + { + []string{"start", "--help"}, + Options{}, + ErrHelp, + 1, }, } func TestParseOptions(t *testing.T) { - for _, v := range usageTestTable { - opts, err := ParseOptions(v.argv, func() {}) + helpCalls := 0 + helpRequested := func() { + helpCalls++ + } - if err != nil { - t.Fail() - } + NewFlagSet = func(cmd string) *pflag.FlagSet { + flagSet := pflag.NewFlagSet(cmd, pflag.ContinueOnError) + flagSet.Usage = helpRequested + return flagSet + } + + for _, v := range usageTestTable { + opts, err := ParseOptions(v.argv, helpRequested) if !reflect.DeepEqual(v.opts, opts) { t.Errorf("expected struct %v, got %v", v.opts, opts) } + + if helpCalls != v.helpCalls { + t.Errorf("expected to get %d help calls, got %d", v.helpCalls, helpCalls) + } + + if err != v.err { + t.Errorf("expected to get error %v, got %v", v.err, err) + } + + helpCalls = 0 } }