| 12 | ) |
| 13 | |
| 14 | func TestBoolFuncCompat(t *testing.T) { |
| 15 | // compare behavior with the stdlib 'flag' package |
| 16 | type BoolFuncFlagSet interface { |
| 17 | BoolFunc(name string, usage string, fn func(string) error) |
| 18 | Parse([]string) error |
| 19 | } |
| 20 | |
| 21 | unitTestErr := errors.New("unit test error") |
| 22 | runCase := func(f BoolFuncFlagSet, name string, args []string) (values []string, err error) { |
| 23 | fn := func(s string) error { |
| 24 | values = append(values, s) |
| 25 | if s == "err" { |
| 26 | return unitTestErr |
| 27 | } |
| 28 | return nil |
| 29 | } |
| 30 | f.BoolFunc(name, "Callback function", fn) |
| 31 | |
| 32 | err = f.Parse(args) |
| 33 | return values, err |
| 34 | } |
| 35 | |
| 36 | t.Run("regular parsing", func(t *testing.T) { |
| 37 | flagName := "bflag" |
| 38 | args := []string{"--bflag", "--bflag=false", "--bflag=1", "--bflag=bar", "--bflag="} |
| 39 | |
| 40 | // It turns out that, even though the function is called "BoolFunc", |
| 41 | // the standard flag package does not try to parse the value assigned to |
| 42 | // that cli flag as a boolean. The string provided on the command line is |
| 43 | // passed as is to the callback. |
| 44 | // e.g: with "--bflag=not_a_bool" on the command line, the FlagSet does not |
| 45 | // generate an error stating "invalid boolean value", and `fn` will be called |
| 46 | // with "not_a_bool" as an argument. |
| 47 | |
| 48 | stdFSet := flag.NewFlagSet("std test", flag.ContinueOnError) |
| 49 | stdValues, err := runCase(stdFSet, flagName, args) |
| 50 | if err != nil { |
| 51 | t.Fatalf("std flag: expected no error, got %v", err) |
| 52 | } |
| 53 | expected := []string{"true", "false", "1", "bar", ""} |
| 54 | if !cmpLists(expected, stdValues) { |
| 55 | t.Fatalf("std flag: expected %v, got %v", expected, stdValues) |
| 56 | } |
| 57 | |
| 58 | fset := NewFlagSet("pflag test", ContinueOnError) |
| 59 | pflagValues, err := runCase(fset, flagName, args) |
| 60 | if err != nil { |
| 61 | t.Fatalf("pflag: expected no error, got %v", err) |
| 62 | } |
| 63 | if !cmpLists(stdValues, pflagValues) { |
| 64 | t.Fatalf("pflag: expected %v, got %v", stdValues, pflagValues) |
| 65 | } |
| 66 | }) |
| 67 | |
| 68 | t.Run("error triggered by callback", func(t *testing.T) { |
| 69 | flagName := "bflag" |
| 70 | args := []string{"--bflag", "--bflag=err", "--bflag=after"} |
| 71 | |