Add test cases

Signed-off-by: JaySon-Huang <tshent@qq.com>
This commit is contained in:
JaySon-Huang 2021-12-03 02:08:41 +08:00
parent 9e1d6f1c2a
commit 7d8e3706d1
No known key found for this signature in database
GPG key ID: 370C14C8CDC7A5ED

View file

@ -2058,3 +2058,93 @@ func TestFParseErrWhitelistSiblingCommand(t *testing.T) {
}
checkStringContains(t, output, "unknown flag: --unknown")
}
func TestFCommandFindSubCommand(t *testing.T) {
root := &Command{
Use: "root",
Run: emptyRun,
}
type testOpts struct {
a bool
b bool
}
var opt testOpts
child := &Command{
Use: "child",
RunE: func(cmd *Command, args []string) error {
fmt.Printf("Done! a=%v b=%v\n", opt.a, opt.b)
return nil
},
}
child.Flags().BoolVar(&opt.a, "a", false, "a")
child.Flags().BoolVar(&opt.b, "b", false, "b")
flag := child.Flags().Lookup("a")
if flag != nil {
if flag.NoOptDefVal != "true" {
t.Errorf("ffff %v", flag.NoOptDefVal)
}
}
root.AddCommand(child)
argsToTest := [][]string{
{"--a", "--b", "child"},
{"child", "--a"},
{"child", "--b"},
{"--a=false", "child"},
{"--a=true", "child"},
{"--a", "child"},
{"--b", "child"},
}
for _, args := range argsToTest {
cmdFound, _, err := root.Find(args)
if err != nil {
t.Errorf("Unexpected error: %v with args: %v", err, args)
}
if cmdFound.Name() != "child" {
t.Errorf("expected found 'child' command with args: %v", args)
}
}
}
func TestFFindSubCommand(t *testing.T) {
root := &Command{
Use: "root",
Run: emptyRun,
}
type testOpts struct {
a bool
b bool
}
var opt testOpts
child := &Command{
Use: "child",
RunE: func(cmd *Command, args []string) error {
fmt.Printf("Done! a=%v b=%v\n", opt.a, opt.b)
return nil
},
}
child.Flags().BoolVar(&opt.a, "a", false, "a")
child.Flags().BoolVar(&opt.b, "b", false, "b")
root.AddCommand(child)
// ok
output, err := executeCommand(root, "--a", "child")
if err == nil {
t.Error("expected unknown flag error")
}
checkStringContains(t, output, "unknown flag: --a")
// ok
output, err = executeCommand(root, "--b", "child")
if err == nil {
t.Error("expected unknown flag error")
}
checkStringContains(t, output, "unknown flag: --b")
// fail?
output, err = executeCommand(root, "--a", "--b", "child")
if err == nil {
t.Error("expected unknown flag error")
}
checkStringContains(t, output, "unknown flag: --a")
}