Cobra behavior is now more consistent. Invalid flags cause Usage to be printed.

This commit is contained in:
spf13 2014-06-13 20:00:56 -04:00
parent 7ab4fd75e9
commit 71bb1dfdcd
2 changed files with 26 additions and 13 deletions

View file

@ -119,6 +119,16 @@ func initializeWithRootCmd() *Command {
return cmdRootWithRun return cmdRootWithRun
} }
func checkOutputContains(t *testing.T, c *Command, check string) {
buf := new(bytes.Buffer)
c.SetOutput(buf)
c.Execute()
if !strings.Contains(buf.String(), check) {
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", check, buf.String())
}
}
func TestSingleCommand(t *testing.T) { func TestSingleCommand(t *testing.T) {
c := initialize() c := initialize()
c.AddCommand(cmdPrint, cmdEcho) c.AddCommand(cmdPrint, cmdEcho)
@ -378,29 +388,19 @@ func TestPersistentFlags(t *testing.T) {
} }
func TestHelpCommand(t *testing.T) { func TestHelpCommand(t *testing.T) {
buf := new(bytes.Buffer)
c := initialize() c := initialize()
cmdEcho.AddCommand(cmdTimes) cmdEcho.AddCommand(cmdTimes)
c.AddCommand(cmdPrint, cmdEcho) c.AddCommand(cmdPrint, cmdEcho)
c.SetArgs(strings.Split("help echo", " ")) c.SetArgs(strings.Split("help echo", " "))
c.SetOutput(buf)
c.Execute()
if !strings.Contains(buf.String(), cmdEcho.Long) { checkOutputContains(t, c, cmdEcho.Long)
t.Errorf("Wrong error message displayed, \n %s", buf.String())
}
buf.Reset()
c = initialize() c = initialize()
cmdEcho.AddCommand(cmdTimes) cmdEcho.AddCommand(cmdTimes)
c.AddCommand(cmdPrint, cmdEcho) c.AddCommand(cmdPrint, cmdEcho)
c.SetArgs(strings.Split("help echo times", " ")) c.SetArgs(strings.Split("help echo times", " "))
c.SetOutput(buf)
c.Execute()
if !strings.Contains(buf.String(), cmdTimes.Long) { checkOutputContains(t, c, cmdTimes.Long)
t.Errorf("Wrong error message displayed, \n %s", buf.String())
}
} }
func TestRunnableRootCommand(t *testing.T) { func TestRunnableRootCommand(t *testing.T) {
@ -427,5 +427,15 @@ func TestRootFlags(t *testing.T) {
if flagir != 17 { if flagir != 17 {
t.Errorf("flag value should be 17, %d given", flagir) t.Errorf("flag value should be 17, %d given", flagir)
} }
}
func TestRootHelp(t *testing.T) {
fmt.Println("testing root help")
c := initializeWithRootCmd()
c.AddCommand(cmdPrint, cmdEcho)
c.SetArgs(strings.Split("--help", " "))
e := c.Execute()
fmt.Println(e)
checkOutputContains(t, c, "Available Commands:")
} }

View file

@ -344,6 +344,9 @@ func (c *Command) Execute() (err error) {
if err != nil && c.Runnable() { if err != nil && c.Runnable() {
e := c.ParseFlags(args) e := c.ParseFlags(args)
if e != nil { if e != nil {
// Flags parsing had an error.
fmt.Println(e)
c.Usage()
return e return e
} else { } else {
argWoFlags := c.Flags().Args() argWoFlags := c.Flags().Args()