-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchoice_test.go
108 lines (83 loc) · 2.19 KB
/
choice_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
package cli_test
import (
"regexp"
"strings"
"testing"
"github.com/mailund/cli"
"github.com/mailund/cli/internal/failure"
)
type Args struct {
A cli.Choice `flag:"" short:"a" descr:"optional choice"`
B cli.Choice `pos:"b" descr:"mandatory choice"`
}
var args = &Args{
A: cli.Choice{"A", []string{"A", "B", "C"}},
B: cli.Choice{"B", []string{"A", "B", "C"}},
}
func Init() interface{} { return args }
var cmd = cli.NewCommand(
cli.CommandSpec{
Name: "choices",
Long: "Demonstration of the difficult task of making choices.",
Init: Init,
})
func TestUsage(t *testing.T) {
failure.Failure = func() {}
builder := new(strings.Builder)
cmd.SetOutput(builder)
cmd.Usage()
expected := `Usage: choices [flags] b
Demonstration of the difficult task of making choices.
Flags:
-h,--help show help for choices
-a {A,B,C} optional choice (default A)
Arguments:
b mandatory choice (choose from {A,B,C})
`
msg := builder.String()
space := regexp.MustCompile(`\s+`)
msg = space.ReplaceAllString(msg, " ")
expected = space.ReplaceAllString(expected, " ")
if msg != expected {
t.Errorf("unexpected: %s", msg)
t.Errorf("unexpected: %s", expected)
}
}
func TestSet(t *testing.T) {
err := cmd.RunError([]string{"-a", "B", "C"})
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if args.A.Choice != "B" {
t.Error("A wasn't set correctly")
}
if args.B.Choice != "C" {
t.Error("B wasn't set correctly")
}
err = cmd.RunError([]string{"-a", "X"})
switch err {
case nil:
t.Error("expected an error")
default:
if err.Error() != "parsing flag -a: X is not a valid choice, must be in {A,B,C}" {
t.Errorf("unexpected error: %s", err)
}
}
failed := false
failure.Failure = func() { failed = true }
builder := new(strings.Builder)
cmd.SetOutput(builder)
cmd.Run([]string{"-a", "X"})
if !failed {
t.Error("we expected to fail")
}
expected := "Error: parsing flag -a: X is not a valid choice, must be in {A,B,C}.\n"
msg := builder.String()
space := regexp.MustCompile(`\s+`)
msg = space.ReplaceAllString(msg, " ")
expected = space.ReplaceAllString(expected, " ")
if msg != expected {
t.Errorf("unexpected: %s", msg)
t.Errorf("unexpected: %s", expected)
}
}