-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand_test.go
More file actions
119 lines (112 loc) · 2.63 KB
/
command_test.go
File metadata and controls
119 lines (112 loc) · 2.63 KB
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
114
115
116
117
118
119
package cli
import (
"bytes"
"fmt"
"github.com/stretchr/testify/assert"
"strconv"
"strings"
"testing"
)
func Test_CLI(t *testing.T) {
out := &bytes.Buffer{}
app := Command{
Name: "my-cli",
Action: func(ctx Flags, args []string) error {
fmt.Fprintf(out, "Welcome to my cli!")
return nil
},
Subcommands: []*Command{
{
Name: "farewell",
Description: "Says goodbye",
Flags: []Flag{
BoolFlag{
Name: "UPPER",
Required: true,
Default: false,
},
},
Action: func(ctx Flags, args []string) error {
msg := fmt.Sprintf("You are my farewell!")
if ctx.Bool("UPPER") {
msg = strings.ToUpper(msg)
}
fmt.Fprintf(out, msg)
return nil
},
},
{
Name: "greet",
Usage: "greet --name NAME",
Description: "Outputs a greeting",
Flags: []Flag{
StringFlag{
Name: "name",
Description: "Your name",
Required: true,
},
},
Action: func(ctx Flags, args []string) error {
name := ctx.String("name")
greeting := fmt.Sprintf("Hello, %s!", name)
fmt.Fprintf(out, greeting)
return nil
},
},
},
}
addCmd := &Command{
Name: "add",
Usage: "add A B",
Description: "calculates A + B",
Action: func(ctx Flags, args []string) error {
x, err := strconv.Atoi(args[0])
if err != nil {
return err
}
y, err := strconv.Atoi(args[1])
if err != nil {
return err
}
fmt.Fprintf(out, "sum is: %v", x+y)
return nil
},
}
subCmd := &Command{
Name: "sub",
Usage: "sub A B",
Description: "calculates A - B",
Action: func(ctx Flags, args []string) error {
x, err := strconv.Atoi(args[0])
if err != nil {
return err
}
y, err := strconv.Atoi(args[1])
if err != nil {
return err
}
fmt.Fprintf(out, "diff is: %v", x-y)
return nil
},
}
calcCmd := &Command{
Name: "calc",
Usage: "calc [add|sub] X Y",
Description: "calculates X op Y",
Subcommands: []*Command{addCmd, subCmd},
}
app.AddSubcommand(calcCmd)
assertCommand := func(t *testing.T, input string, expected string) {
args := strings.Split(input, " ")
out.Reset()
err := app.Run(args)
assert.NoError(t, err)
assert.Equal(t, expected, out.String())
}
assertCommand(t, "./cli", "Welcome to my cli!")
assertCommand(t, "./cli farewell --UPPER false", "You are my farewell!")
assertCommand(t, "./cli farewell --UPPER true", "YOU ARE MY FAREWELL!")
assertCommand(t, "./cli greet --name Joe", "Hello, Joe!")
assertCommand(t, "./cli calc add 3 7", "sum is: 10")
assertCommand(t, "./cli calc sub 3 7", "diff is: -4")
}