MCPcopy
hub / github.com/spf13/pflag / TestFuncCompat

Function TestFuncCompat

func_go1.21_test.go:14–102  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

12)
13
14func TestFuncCompat(t *testing.T) {
15 // compare behavior with the stdlib 'flag' package
16 type FuncFlagSet interface {
17 Func(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 FuncFlagSet, 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.Func(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 := "fnflag"
38 args := []string{"--fnflag=xx", "--fnflag", "yy", "--fnflag=zz"}
39
40 stdFSet := flag.NewFlagSet("std test", flag.ContinueOnError)
41 stdValues, err := runCase(stdFSet, flagName, args)
42 if err != nil {
43 t.Fatalf("std flag: expected no error, got %v", err)
44 }
45 expected := []string{"xx", "yy", "zz"}
46 if !cmpLists(expected, stdValues) {
47 t.Fatalf("std flag: expected %v, got %v", expected, stdValues)
48 }
49
50 fset := NewFlagSet("pflag test", ContinueOnError)
51 pflagValues, err := runCase(fset, flagName, args)
52 if err != nil {
53 t.Fatalf("pflag: expected no error, got %v", err)
54 }
55 if !cmpLists(stdValues, pflagValues) {
56 t.Fatalf("pflag: expected %v, got %v", stdValues, pflagValues)
57 }
58 })
59
60 t.Run("error triggered by callback", func(t *testing.T) {
61 flagName := "fnflag"
62 args := []string{"--fnflag", "before", "--fnflag", "err", "--fnflag", "after"}
63
64 // test behavior of standard flag.Fset with an error triggered by the callback:
65 // (note: as can be seen in 'runCase()', if the callback sees "err" as a value
66 // for the flag, it will return an error)
67 stdFSet := flag.NewFlagSet("std test", flag.ContinueOnError)
68 stdFSet.SetOutput(io.Discard) // suppress output
69
70 // run test case with standard flag.Fset
71 stdValues, err := runCase(stdFSet, flagName, args)

Callers

nothing calls this directly

Calls 6

SetOutputMethod · 0.95
cmpListsFunction · 0.85
NewFlagSetFunction · 0.85
FuncMethod · 0.65
ParseMethod · 0.65
ErrorMethod · 0.45

Tested by

no test coverage detected