-
Notifications
You must be signed in to change notification settings - Fork 69
/
testcobra.go
44 lines (37 loc) · 1.61 KB
/
testcobra.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
package testcobra
import (
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
)
// CheckCobraRequiredFlags is a helper function to make sure that
// the Cobra command has certain required flags set
func CheckCobraRequiredFlags(t *testing.T, command *cobra.Command, requiredFlags []string) {
for _, r := range requiredFlags {
x := command.Flag(r)
if x == nil {
t.Errorf("Missing required flag: %s\n", r)
continue
}
assert.Equal(t, []string{"true"}, x.Annotations[cobra.BashCompOneRequiredFlag])
}
}
// CheckCobraCommandAliases is a helper function to make sure that
// the Cobra command has certain required aliases set
func CheckCobraCommandAliases(t *testing.T, command *cobra.Command, requiredAliases []string) {
for _, a := range requiredAliases {
assert.True(t, command.HasAlias(a))
}
}
// CheckCobraMetadata requires metadata fields be set on the command sent and
// any sub-command it contains. Only checks one level deep.
func CheckCobraMetadata(t *testing.T, command *cobra.Command) {
assert.NotEmptyf(t, command.Use, "Need to set Command.Use on Command %s", command.CalledAs())
assert.NotEmptyf(t, command.Short, "Need to set Command.Short on Command %s", command.CalledAs())
for _, c := range command.Commands() {
assert.NotEmptyf(t, c.Use, "Need to set Command.Use on Command %s", c.CommandPath())
assert.NotEmptyf(t, c.Short, "Need to set Command.Short on Command %s", c.CommandPath())
assert.NotEmptyf(t, c.Long, "Need to set Command.Long on Command %s", c.CommandPath())
assert.NotEmptyf(t, c.Example, "Need to set Command.Example on Command %s", c.CommandPath())
}
}