...
1 package pflag
2
3 import (
4 "os"
5 "testing"
6 )
7
8 func setUpCount(c *int) *FlagSet {
9 f := NewFlagSet("test", ContinueOnError)
10 f.CountVarP(c, "verbose", "v", "a counter")
11 return f
12 }
13
14 func TestCount(t *testing.T) {
15 testCases := []struct {
16 input []string
17 success bool
18 expected int
19 }{
20 {[]string{}, true, 0},
21 {[]string{"-v"}, true, 1},
22 {[]string{"-vvv"}, true, 3},
23 {[]string{"-v", "-v", "-v"}, true, 3},
24 {[]string{"-v", "--verbose", "-v"}, true, 3},
25 {[]string{"-v=3", "-v"}, true, 4},
26 {[]string{"--verbose=0"}, true, 0},
27 {[]string{"-v=0"}, true, 0},
28 {[]string{"-v=a"}, false, 0},
29 }
30
31 devnull, _ := os.Open(os.DevNull)
32 os.Stderr = devnull
33 for i := range testCases {
34 var count int
35 f := setUpCount(&count)
36
37 tc := &testCases[i]
38
39 err := f.Parse(tc.input)
40 if err != nil && tc.success == true {
41 t.Errorf("expected success, got %q", err)
42 continue
43 } else if err == nil && tc.success == false {
44 t.Errorf("expected failure, got success")
45 continue
46 } else if tc.success {
47 c, err := f.GetCount("verbose")
48 if err != nil {
49 t.Errorf("Got error trying to fetch the counter flag")
50 }
51 if c != tc.expected {
52 t.Errorf("expected %d, got %d", tc.expected, c)
53 }
54 }
55 }
56 }
57
View as plain text