-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
flag_validation_test.go
113 lines (104 loc) · 2.04 KB
/
flag_validation_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package cli
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestFlagDefaultValidation(t *testing.T) {
cmd := &Command{
Name: "foo",
Flags: []Flag{
&IntFlag{
Name: "if",
Value: 2, // this value should fail validation
Validator: func(i int64) error {
if (i >= 3 && i <= 10) || (i >= 20 && i <= 24) {
return nil
}
return fmt.Errorf("Value %d not in range [3,10] or [20,24]", i)
},
ValidateDefaults: true,
},
},
}
r := require.New(t)
// Default value of flag is 2 which should fail validation
err := cmd.Run(buildTestContext(t), []string{"foo", "--if", "5"})
r.Error(err)
}
func TestFlagValidation(t *testing.T) {
r := require.New(t)
testCases := []struct {
name string
arg string
errExpected bool
}{
{
name: "first range less than min",
arg: "2",
errExpected: true,
},
{
name: "first range min",
arg: "3",
},
{
name: "first range mid",
arg: "7",
},
{
name: "first range max",
arg: "10",
},
{
name: "first range greater than max",
arg: "15",
errExpected: true,
},
{
name: "second range less than min",
arg: "19",
errExpected: true,
},
{
name: "second range min",
arg: "20",
},
{
name: "second range mid",
arg: "21",
},
{
name: "second range max",
arg: "24",
},
{
name: "second range greater than max",
arg: "27",
errExpected: true,
},
}
for _, testCase := range testCases {
cmd := &Command{
Name: "foo",
Flags: []Flag{
&IntFlag{
Name: "it",
Value: 5, // note that this value should pass validation
Validator: func(i int64) error {
if (i >= 3 && i <= 10) || (i >= 20 && i <= 24) {
return nil
}
return fmt.Errorf("Value %d not in range [3,10]U[20,24]", i)
},
},
},
}
err := cmd.Run(buildTestContext(t), []string{"foo", "--it", testCase.arg})
if !testCase.errExpected {
r.NoError(err)
} else {
r.Error(err)
}
}
}