From 71bb1dfdcd030b2518e5b6a10c531f6fcba65e9f Mon Sep 17 00:00:00 2001 From: spf13 Date: Fri, 13 Jun 2014 20:00:56 -0400 Subject: [PATCH] Cobra behavior is now more consistent. Invalid flags cause Usage to be printed. --- cobra_test.go | 36 +++++++++++++++++++++++------------- command.go | 3 +++ 2 files changed, 26 insertions(+), 13 deletions(-) diff --git a/cobra_test.go b/cobra_test.go index fb4a7c4..44e6afe 100644 --- a/cobra_test.go +++ b/cobra_test.go @@ -119,6 +119,16 @@ func initializeWithRootCmd() *Command { 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) { c := initialize() c.AddCommand(cmdPrint, cmdEcho) @@ -378,29 +388,19 @@ func TestPersistentFlags(t *testing.T) { } func TestHelpCommand(t *testing.T) { - buf := new(bytes.Buffer) c := initialize() cmdEcho.AddCommand(cmdTimes) c.AddCommand(cmdPrint, cmdEcho) c.SetArgs(strings.Split("help echo", " ")) - c.SetOutput(buf) - c.Execute() - if !strings.Contains(buf.String(), cmdEcho.Long) { - t.Errorf("Wrong error message displayed, \n %s", buf.String()) - } + checkOutputContains(t, c, cmdEcho.Long) - buf.Reset() c = initialize() cmdEcho.AddCommand(cmdTimes) c.AddCommand(cmdPrint, cmdEcho) c.SetArgs(strings.Split("help echo times", " ")) - c.SetOutput(buf) - c.Execute() - if !strings.Contains(buf.String(), cmdTimes.Long) { - t.Errorf("Wrong error message displayed, \n %s", buf.String()) - } + checkOutputContains(t, c, cmdTimes.Long) } func TestRunnableRootCommand(t *testing.T) { @@ -427,5 +427,15 @@ func TestRootFlags(t *testing.T) { if flagir != 17 { 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:") } diff --git a/command.go b/command.go index b4c8550..9601d04 100644 --- a/command.go +++ b/command.go @@ -344,6 +344,9 @@ func (c *Command) Execute() (err error) { if err != nil && c.Runnable() { e := c.ParseFlags(args) if e != nil { + // Flags parsing had an error. + fmt.Println(e) + c.Usage() return e } else { argWoFlags := c.Flags().Args()