-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusage_test.go
98 lines (83 loc) · 1.99 KB
/
usage_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
package arg
import (
"fmt"
)
// A user represent a user
type User struct {
ID int64
Name string
Enabled bool
Salary float64
}
var users = []User{
{100, "joe", true, 50000},
{101, "ben", true, 37000},
{101, "bob", true, 60000},
{101, "tod", true, 58000},
}
func ShowUser(args ExecArgs) error {
var id int64
if !args.GetOption("-id", &id) {
return fmt.Errorf("Expected uint64 -id flag")
}
for i := range users {
if users[i].ID == id {
fmt.Printf("%+v\n", users[i])
break
}
}
return nil
}
func DisableUser(args ExecArgs) error {
var id int64
if !args.GetOption("-id", &id) {
return fmt.Errorf("Expected uint64 -id flag")
}
for i := range users {
if users[i].ID == id {
users[i].Enabled = false
fmt.Printf("Disabled user with ID %v\n", id)
break
}
}
return nil
}
// ExampleUsage Shows how this package can be used
func Example_usage() {
showCmd := &Cmd{
Prefix: "users",
Name: "show",
Description: "Displays all the users",
Exec: ShowUser,
}
showCmd.ReqInt64('i', "id", "The user ID to be shown")
disableCmd := &Cmd{
Prefix: "users",
Name: "disable",
Description: "Disables a user by the given ID",
Exec: DisableUser,
}
disableCmd.ReqInt64('i', "id", "The user ID to be disabled")
//The parser can have a nil output writer.
//We could use os.Stdout, but that will
//mess with the testable output.
parser := NewParser(nil)
parser.AddCmd(showCmd)
parser.AddCmd(disableCmd)
showArgs := []string{"a.out", "users", "show", "-id", "100"}
disableArgs := []string{"a.out", "users", "disable", "-id", "100"}
badArgs := []string{"a.out", "unknown"}
//Should not fail since the arguments are fine
parser.Parse(false, showArgs)
parser.Parse(false, disableArgs)
//Should fail with unknown argument
err := parser.Parse(false, badArgs)
if err == ErrInvalidArgs {
fmt.Printf("%v\n", err)
}
/*
// Output: {ID:100 Name:joe Enabled:true Salary:50000}
// Disabled user with ID 100
// Invalid Arguments
*/
}