From 95a6a40798df11df014298af8a8250af515fa753 Mon Sep 17 00:00:00 2001 From: Eric Paris Date: Wed, 12 Aug 2015 10:54:26 -0400 Subject: Do not append to default values in {String,Int}Slice I added the ability to do: `-s=bob -s=john` and get `[]string{"bob", "john"}` But if a default value was set to say `[]string{"eric"}` the above operation was mistakenly resulting in: `[]string{"eric", "bob", "john"} which was obviously not what was intended. This is fixed by tracking if a value was parsed and overwriting the default on the first time -s is found, but we append the 2+ time. --- string_slice_test.go | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) (limited to 'string_slice_test.go') diff --git a/string_slice_test.go b/string_slice_test.go index 63eb9de..e8847d5 100644 --- a/string_slice_test.go +++ b/string_slice_test.go @@ -16,6 +16,12 @@ func setUpSSFlagSet(ssp *[]string) *FlagSet { return f } +func setUpSSFlagSetWithDefault(ssp *[]string) *FlagSet { + f := NewFlagSet("test", ContinueOnError) + f.StringSliceVar(ssp, "ss", []string{"default", "values"}, "Command seperated list!") + return f +} + func TestEmptySS(t *testing.T) { var ss []string f := setUpSSFlagSet(&ss) @@ -60,6 +66,60 @@ func TestSS(t *testing.T) { } } +func TestSSDefault(t *testing.T) { + var ss []string + f := setUpSSFlagSetWithDefault(&ss) + + vals := []string{"default", "values"} + + err := f.Parse([]string{}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range ss { + if vals[i] != v { + t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) + } + } + + getSS, err := f.GetStringSlice("ss") + if err != nil { + t.Fatal("got an error from GetStringSlice():", err) + } + for i, v := range getSS { + if vals[i] != v { + t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) + } + } +} + +func TestSSWithDefault(t *testing.T) { + var ss []string + f := setUpSSFlagSetWithDefault(&ss) + + vals := []string{"one", "two", "4", "3"} + arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ",")) + err := f.Parse([]string{arg}) + if err != nil { + t.Fatal("expected no error; got", err) + } + for i, v := range ss { + if vals[i] != v { + t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v) + } + } + + getSS, err := f.GetStringSlice("ss") + if err != nil { + t.Fatal("got an error from GetStringSlice():", err) + } + for i, v := range getSS { + if vals[i] != v { + t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v) + } + } +} + func TestSSCalledTwice(t *testing.T) { var ss []string f := setUpSSFlagSet(&ss) -- cgit v1.2.3