From ea3c5beeffa23d89eb3344dd674d81187713de3e Mon Sep 17 00:00:00 2001 From: Albert Nigmatzianov Date: Sun, 23 Apr 2017 09:50:55 +0200 Subject: [PATCH] Add TestHelpFlagInHelp --- cobra_test.go | 4 ++++ command_test.go | 34 ++++++++++++++++++++++++++++++---- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/cobra_test.go b/cobra_test.go index d6593a5..6f3ceb1 100644 --- a/cobra_test.go +++ b/cobra_test.go @@ -3,6 +3,7 @@ package cobra import ( "bytes" "fmt" + "os" "reflect" "runtime" "strings" @@ -1153,6 +1154,9 @@ func TestFlagOnPflagCommandLine(t *testing.T) { r := fullSetupTest("--help") checkResultContains(t, r, flagName) + + // reset CommandLine flagset + pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError) } func TestAddTemplateFunctions(t *testing.T) { diff --git a/command_test.go b/command_test.go index 3921a0b..d8c5021 100644 --- a/command_test.go +++ b/command_test.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "reflect" + "strings" "testing" "github.com/spf13/pflag" @@ -118,7 +119,7 @@ func TestStripFlags(t *testing.T) { } } -func Test_DisableFlagParsing(t *testing.T) { +func TestDisableFlagParsing(t *testing.T) { as := []string{"-v", "-race", "-file", "foo.go"} targs := []string{} cmdPrint := &Command{ @@ -226,7 +227,8 @@ func TestFlagErrorFunc(t *testing.T) { // TestSortedFlags checks, // if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false. -// https://github.com/spf13/cobra/issues/404 +// +// Source: https://github.com/spf13/cobra/issues/404 func TestSortedFlags(t *testing.T) { cmd := &Command{} cmd.Flags().SortFlags = false @@ -240,7 +242,7 @@ func TestSortedFlags(t *testing.T) { if i == len(names) { return } - if contains(f.Name, names) { + if isStringInStringSlice(f.Name, names) { if names[i] != f.Name { t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name) } @@ -250,7 +252,7 @@ func TestSortedFlags(t *testing.T) { } // contains checks, if s is in ss. -func contains(s string, ss []string) bool { +func isStringInStringSlice(s string, ss []string) bool { for _, v := range ss { if v == s { return true @@ -258,3 +260,27 @@ func contains(s string, ss []string) bool { } return false } + +// TestHelpFlagInHelp checks, +// if '--help' flag is shown in help for child (executing `parent help child`), +// that has no other flags. +// +// Source: https://github.com/spf13/cobra/issues/302 +func TestHelpFlagInHelp(t *testing.T) { + output := new(bytes.Buffer) + parent := &Command{Use: "parent", Long: "long", Run: func(*Command, []string) { return }} + parent.SetOutput(output) + + child := &Command{Use: "child", Long: "long", Run: func(*Command, []string) { return }} + parent.AddCommand(child) + + parent.SetArgs([]string{"help", "child"}) + err := parent.Execute() + if err != nil { + t.Fatal(err) + } + + if !strings.Contains(output.String(), "[flags]") { + t.Fatalf("\nExpecting to contain: %v\nGot: %v", "[flags]", output.String()) + } +}