Skip to content
Myr

Improve tests

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Albert Nigmatzianov · committed by Albert Nigmatzianov · parent 099c5ae · Browse files · 6 files+1405 added−1688 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+1405 added−1688 removed

  • other:+1405 added−1688 removed

6 files+1405 added−1688 removed

modified:bash_completions_test.go+108 added-106 removed
8 unmodified lines
9)1011func checkOmit(t *testing.T, found, unexpected string) {12 if strings.Contains(found, unexpected) {13 t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected)13 t.Errorf("Got: %q\nBut should not have!\n", unexpected)14 }15}1617func check(t *testing.T, found, expected string) {18 if !strings.Contains(found, expected) {19 t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)19 t.Errorf("Expecting to contain: \n %q\nGot:\n %q\n", expected, found)20 }21}2223func runShellCheck(s string) error {
8 unmodified lines
32 if err != nil {33 return err34 }35 go func() {36 defer stdin.Close()36 stdin.Write([]byte(s))37 stdin.Close()38 }()3940 return cmd.Run()41}4243// World worst custom function, just keep telling you to enter hello!44const (45 bashCompletionFunc = `__custom_func() {46COMPREPLY=( "hello" )44const bashCompletionFunc = `__custom_func() {45 COMPREPLY=( "hello" )46}47`49)4849func TestBashCompletions(t *testing.T) {52 c := initializeWithRootCmd()53 cmdEcho.AddCommand(cmdTimes)54 c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated, cmdColon)50 rootCmd := &Command{51 Use: "root",52 ArgAliases: []string{"pods", "nodes", "services", "replicationcontrollers", "po", "no", "svc", "rc"},53 ValidArgs: []string{"pod", "node", "service", "replicationcontroller"},54 BashCompletionFunction: bashCompletionFunc,55 Run: emptyRun,56 }57 rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")58 rootCmd.MarkFlagRequired("introot")5956 // custom completion function57 c.BashCompletionFunction = bashCompletionFunc60 // Filename.61 rootCmd.Flags().String("filename", "", "Enter a filename")62 rootCmd.MarkFlagFilename("filename", "json", "yaml", "yml")6359 // required flag60 c.MarkFlagRequired("introot")64 // Persistent filename.65 rootCmd.PersistentFlags().String("persistent-filename", "", "Enter a filename")66 rootCmd.MarkPersistentFlagFilename("persistent-filename")67 rootCmd.MarkPersistentFlagRequired("persistent-filename")6862 // valid nouns63 validArgs := []string{"pod", "node", "service", "replicationcontroller"}64 c.ValidArgs = validArgs69 // Filename extensions.70 rootCmd.Flags().String("filename-ext", "", "Enter a filename (extension limited)")71 rootCmd.MarkFlagFilename("filename-ext")72 rootCmd.Flags().String("custom", "", "Enter a filename (extension limited)")73 rootCmd.MarkFlagCustom("custom", "__complete_custom")7466 // noun aliases67 argAliases := []string{"pods", "nodes", "services", "replicationcontrollers", "po", "no", "svc", "rc"}68 c.ArgAliases = argAliases75 // Subdirectories in a given directory.76 rootCmd.Flags().String("theme", "", "theme to use (located in /themes/THEMENAME/)")77 rootCmd.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"})7870 // filename71 var flagval string72 c.Flags().StringVar(&flagval, "filename", "", "Enter a filename")73 c.MarkFlagFilename("filename", "json", "yaml", "yml")79 echoCmd := &Command{80 Use: "echo [string to echo]",81 Aliases: []string{"say"},82 Short: "Echo anything to the screen",83 Long: "an utterly useless command for testing.",84 Example: "Just run cobra-test echo",85 Run: emptyRun,86 }8775 // persistent filename76 var flagvalPersistent string77 c.PersistentFlags().StringVar(&flagvalPersistent, "persistent-filename", "", "Enter a filename")78 c.MarkPersistentFlagFilename("persistent-filename")79 c.MarkPersistentFlagRequired("persistent-filename")88 printCmd := &Command{89 Use: "print [string to print]",90 Args: MinimumNArgs(1),91 Short: "Print anything to the screen",92 Long: "an absolutely utterly useless command for testing.",93 Run: emptyRun,94 }9581 // filename extensions82 var flagvalExt string83 c.Flags().StringVar(&flagvalExt, "filename-ext", "", "Enter a filename (extension limited)")84 c.MarkFlagFilename("filename-ext")96 deprecatedCmd := &Command{97 Use: "deprecated [can't do anything here]",98 Args: NoArgs,99 Short: "A command which is deprecated",100 Long: "an absolutely utterly useless command for testing deprecation!.",101 Deprecated: "Please use echo instead",102 Run: emptyRun,103 }10486 // filename extensions87 var flagvalCustom string88 c.Flags().StringVar(&flagvalCustom, "custom", "", "Enter a filename (extension limited)")89 c.MarkFlagCustom("custom", "__complete_custom")105 colonCmd := &Command{106 Use: "cmd:colon",107 Run: emptyRun,108 }10991 // subdirectories in a given directory92 var flagvalTheme string93 c.Flags().StringVar(&flagvalTheme, "theme", "", "theme to use (located in /themes/THEMENAME/)")94 c.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"})110 timesCmd := &Command{111 Use: "times [# times] [string to echo]",112 SuggestFor: []string{"counts"},113 Args: OnlyValidArgs,114 ValidArgs: []string{"one", "two", "three", "four"},115 Short: "Echo anything to the screen more times",116 Long: "a slightly useless command for testing.",117 Run: emptyRun,118 }11996 out := new(bytes.Buffer)97 c.GenBashCompletion(out)98 str := out.String()120 echoCmd.AddCommand(timesCmd)121 rootCmd.AddCommand(echoCmd, printCmd, deprecatedCmd, colonCmd)122100 check(t, str, "_cobra-test")101 check(t, str, "_cobra-test_echo")102 check(t, str, "_cobra-test_echo_times")103 check(t, str, "_cobra-test_print")104 check(t, str, "_cobra-test_cmd__colon")123 buf := new(bytes.Buffer)124 rootCmd.GenBashCompletion(buf)125 output := buf.String()126127 check(t, output, "_root")128 check(t, output, "_root_echo")129 check(t, output, "_root_echo_times")130 check(t, output, "_root_print")131 check(t, output, "_root_cmd__colon")132133 // check for required flags107 check(t, str, `must_have_one_flag+=("--introot=")`)108 check(t, str, `must_have_one_flag+=("--persistent-filename=")`)134 check(t, output, `must_have_one_flag+=("--introot=")`)135 check(t, output, `must_have_one_flag+=("--persistent-filename=")`)136 // check for custom completion function110 check(t, str, `COMPREPLY=( "hello" )`)137 check(t, output, `COMPREPLY=( "hello" )`)138 // check for required nouns112 check(t, str, `must_have_one_noun+=("pod")`)139 check(t, output, `must_have_one_noun+=("pod")`)140 // check for noun aliases114 check(t, str, `noun_aliases+=("pods")`)115 check(t, str, `noun_aliases+=("rc")`)116 checkOmit(t, str, `must_have_one_noun+=("pods")`)141 check(t, output, `noun_aliases+=("pods")`)142 check(t, output, `noun_aliases+=("rc")`)143 checkOmit(t, output, `must_have_one_noun+=("pods")`)144 // check for filename extension flags118 check(t, str, `flags_completion+=("_filedir")`)145 check(t, output, `flags_completion+=("_filedir")`)146 // check for filename extension flags120 check(t, str, `must_have_one_noun+=("three")`)147 check(t, output, `must_have_one_noun+=("three")`)148 // check for filename extension flags122 check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`)149 check(t, output, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`)150 // check for custom flags124 check(t, str, `flags_completion+=("__complete_custom")`)151 check(t, output, `flags_completion+=("__complete_custom")`)152 // check for subdirs_in_dir flags126 check(t, str, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`)153 check(t, output, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`)154128 checkOmit(t, str, cmdDeprecated.Name())155 checkOmit(t, output, deprecatedCmd.Name())156130 // if available, run shellcheck against the script157 // If available, run shellcheck against the script.158 if err := exec.Command("which", "shellcheck").Run(); err != nil {159 return160 }134 err := runShellCheck(str)135 if err != nil {161 if err := runShellCheck(output); err != nil {162 t.Fatalf("shellcheck failed: %v", err)163 }164}165166func TestBashCompletionHiddenFlag(t *testing.T) {141 var cmdTrue = &Command{142 Use: "does nothing",143 Run: func(cmd *Command, args []string) {},144 }167 c := &Command{Use: "c", Run: emptyRun}168146 const flagName = "hidden-foo-bar-baz"169 const flagName = "hiddenFlag"170 c.Flags().Bool(flagName, false, "")171 c.Flags().MarkHidden(flagName)172148 var flagValue bool149 cmdTrue.Flags().BoolVar(&flagValue, flagName, false, "hidden flag")150 cmdTrue.Flags().MarkHidden(flagName)173 buf := new(bytes.Buffer)174 c.GenBashCompletion(buf)175 output := buf.String()176152 out := new(bytes.Buffer)153 cmdTrue.GenBashCompletion(out)154 bashCompletion := out.String()155 if strings.Contains(bashCompletion, flagName) {156 t.Errorf("expected completion to not include %q flag: Got %v", flagName, bashCompletion)177 if strings.Contains(output, flagName) {178 t.Errorf("Expected completion to not include %q flag: Got %v", flagName, output)179 }180}181182func TestBashCompletionDeprecatedFlag(t *testing.T) {161 var cmdTrue = &Command{162 Use: "does nothing",163 Run: func(cmd *Command, args []string) {},164 }183 c := &Command{Use: "c", Run: emptyRun}184166 const flagName = "deprecated-foo-bar-baz"185 const flagName = "deprecated-flag"186 c.Flags().Bool(flagName, false, "")187 c.Flags().MarkDeprecated(flagName, "use --not-deprecated instead")188168 var flagValue bool169 cmdTrue.Flags().BoolVar(&flagValue, flagName, false, "hidden flag")170 cmdTrue.Flags().MarkDeprecated(flagName, "use --does-not-exist instead")171172 out := new(bytes.Buffer)173 cmdTrue.GenBashCompletion(out)174 bashCompletion := out.String()175 if strings.Contains(bashCompletion, flagName) {176 t.Errorf("expected completion to not include %q flag: Got %v", flagName, bashCompletion)177 }178}179180func BenchmarkBashCompletion(b *testing.B) {181 c := initializeWithRootCmd()182 cmdEcho.AddCommand(cmdTimes)183 c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated, cmdColon)184189 buf := new(bytes.Buffer)190 c.GenBashCompletion(buf)191 output := buf.String()192187 b.ResetTimer()188 for i := 0; i < b.N; i++ {189 buf.Reset()190 if err := c.GenBashCompletion(buf); err != nil {191 b.Fatal(err)192 }193 if strings.Contains(output, flagName) {194 t.Errorf("expected completion to not include %q flag: Got %v", flagName, output)195 }196}
modified:cobra_test.go+3 added-1295 removed
1package cobra23import (4 "bytes"5 "fmt"6 "os"7 "reflect"8 "runtime"9 "strings"4 "testing"5 "text/template"1213 "github.com/spf13/pflag"6)716var tp, te, tt, tr []string17var rootPersPre, echoPre, echoPersPre, timesPersPre []string18var flagb1, flagb2, flagb3, flagbr, flagbp bool19var flags1, flags2a, flags2b, flags3, outs string20var flagi1, flagi2, flagi3, flagi4, flagir int21var rootcalled bool22var versionUsed int2324const strtwoParentHelp = "help message for parent flag strtwo"25const strtwoChildHelp = "help message for child flag strtwo"2627var cmdHidden = &Command{28 Use: "hide [secret string to print]",29 Short: "Print anything to screen (if command is known)",30 Long: `an absolutely utterly useless command for testing.`,31 Run: func(cmd *Command, args []string) {32 outs = "hidden"33 },34 Hidden: true,35}3637var cmdPrint = &Command{38 Use: "print [string to print]",39 Args: MinimumNArgs(1),40 Short: "Print anything to the screen",41 Long: `an absolutely utterly useless command for testing.`,42 Run: func(cmd *Command, args []string) {43 tp = args44 },45}4647var cmdEcho = &Command{48 Use: "echo [string to echo]",49 Aliases: []string{"say"},50 Short: "Echo anything to the screen",51 Long: `an utterly useless command for testing.`,52 Example: "Just run cobra-test echo",53 PersistentPreRun: func(cmd *Command, args []string) {54 echoPersPre = args55 },56 PreRun: func(cmd *Command, args []string) {57 echoPre = args58 },59 Run: func(cmd *Command, args []string) {60 te = args61 },62}6364var cmdEchoSub = &Command{65 Use: "echosub [string to print]",66 Short: "second sub command for echo",67 Long: `an absolutely utterly useless command for testing gendocs!.`,68 Run: func(cmd *Command, args []string) {69 },70}7172var cmdDeprecated = &Command{73 Use: "deprecated [can't do anything here]",74 Short: "A command which is deprecated",75 Long: `an absolutely utterly useless command for testing deprecation!.`,76 Deprecated: "Please use echo instead",77 Run: func(cmd *Command, args []string) {78 },79 Args: NoArgs,80}8182var cmdTimes = &Command{83 Use: "times [# times] [string to echo]",84 SuggestFor: []string{"counts"},85 Short: "Echo anything to the screen more times",86 Long: `a slightly useless command for testing.`,87 PersistentPreRun: func(cmd *Command, args []string) {88 timesPersPre = args89 },90 Run: func(cmd *Command, args []string) {91 tt = args92 },93 Args: OnlyValidArgs,94 ValidArgs: []string{"one", "two", "three", "four"},95}9697var cmdRootNoRun = &Command{98 Use: "cobra-test",99 Short: "The root can run its own function",100 Long: "The root description for help",101 PersistentPreRun: func(cmd *Command, args []string) {102 rootPersPre = args103 },104}105106var cmdRootSameName = &Command{107 Use: "print",108 Short: "Root with the same name as a subcommand",109 Long: "The root description for help",110}111112var cmdRootTakesArgs = &Command{113 Use: "root-with-args [random args]",114 Short: "The root can run it's own function and takes args!",115 Long: "The root description for help, and some args",116 Run: func(cmd *Command, args []string) {117 tr = args118 },119 Args: ArbitraryArgs,120}121122var cmdRootWithRun = &Command{123 Use: "cobra-test",124 Short: "The root can run its own function",125 Long: "The root description for help",126 Run: func(cmd *Command, args []string) {127 tr = args128 rootcalled = true129 },130}131132var cmdSubNoRun = &Command{133 Use: "subnorun",134 Short: "A subcommand without a Run function",135 Long: "A long output about a subcommand without a Run function",136}137138var cmdCustomFlags = &Command{139 Use: "customflags [flags] -- REMOTE_COMMAND",140 Short: "A command that expects flags in a custom location",141 Long: "A long output about a command that expects flags in a custom location",142 Run: func(cmd *Command, args []string) {143 },144}145146var cmdVersion1 = &Command{147 Use: "version",148 Short: "Print the version number",149 Long: `First version of the version command`,150 Run: func(cmd *Command, args []string) {151 versionUsed = 1152 },153}154155var cmdVersion2 = &Command{156 Use: "version",157 Short: "Print the version number",158 Long: `Second version of the version command`,159 Run: func(cmd *Command, args []string) {160 versionUsed = 2161 },162}163164var cmdColon = &Command{165 Use: "cmd:colon",166 Run: func(cmd *Command, args []string) {167 },168}169170func flagInit() {171 cmdEcho.ResetFlags()172 cmdPrint.ResetFlags()173 cmdTimes.ResetFlags()174 cmdRootNoRun.ResetFlags()175 cmdRootSameName.ResetFlags()176 cmdRootWithRun.ResetFlags()177 cmdSubNoRun.ResetFlags()178 cmdCustomFlags.ResetFlags()179 cmdVersion1.ResetFlags()180 cmdVersion2.ResetFlags()181182 cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp)183 cmdCustomFlags.Flags().IntVar(&flagi4, "intfour", 456, "help message for flag intfour")184 cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone")185 cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")186 cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")187 cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")188 cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")189 cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo")190 cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")191 cmdTimes.Flags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)192 cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)193 cmdTimes.LocalFlags() // populate lflags before parent is set194 cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree")195 cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")196}197198func commandInit() {199 cmdEcho.ResetCommands()200 cmdPrint.ResetCommands()201 cmdTimes.ResetCommands()202 cmdRootNoRun.ResetCommands()203 cmdRootSameName.ResetCommands()204 cmdRootWithRun.ResetCommands()205 cmdSubNoRun.ResetCommands()206 cmdCustomFlags.ResetCommands()207}208209func initialize() *Command {210 tt, tp, te = nil, nil, nil211 rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil212213 var c = cmdRootNoRun214 commandInit()215 flagInit()216 return c217}218219func initializeWithSameName() *Command {220 tt, tp, te = nil, nil, nil221 rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil222 var c = cmdRootSameName223 commandInit()224 flagInit()225 return c226}227228func initializeWithRootCmd() *Command {229 cmdRootWithRun.ResetCommands()230 tt, tp, te, tr, rootcalled = nil, nil, nil, nil, false231 flagInit()232 cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot")233 cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot")234 commandInit()235 return cmdRootWithRun236}237238type resulter struct {239 Error error240 Output string241 Command *Command242}243244func fullSetupTest(args ...string) resulter {245 c := initializeWithRootCmd()246247 return fullTester(c, args...)248}249250func noRRSetupTestSilenced(args ...string) resulter {251 c := initialize()252 c.SilenceErrors = true253 c.SilenceUsage = true254 return fullTester(c, args...)255}256257func noRRSetupTest(args ...string) resulter {258 c := initialize()259260 return fullTester(c, args...)261}262263func rootOnlySetupTest(args ...string) resulter {264 c := initializeWithRootCmd()265266 return simpleTester(c, args...)267}268269func simpleTester(c *Command, args ...string) resulter {270 buf := new(bytes.Buffer)271 // Testing flag with invalid input272 c.SetOutput(buf)273 c.SetArgs(args)274275 err := c.Execute()276 output := buf.String()277278 return resulter{err, output, c}279}280281func simpleTesterC(c *Command, args ...string) resulter {282 buf := new(bytes.Buffer)283 // Testing flag with invalid input284 c.SetOutput(buf)285 c.SetArgs(args)286287 cmd, err := c.ExecuteC()288 output := buf.String()289290 return resulter{err, output, cmd}291}292293func fullTester(c *Command, args ...string) resulter {294 buf := new(bytes.Buffer)295 // Testing flag with invalid input296 c.SetOutput(buf)297 cmdEcho.AddCommand(cmdTimes)298 c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdCustomFlags, cmdDeprecated)299 c.SetArgs(args)300301 err := c.Execute()302 output := buf.String()303304 return resulter{err, output, c}305}306307func logErr(t *testing.T, found, expected string) {308 out := new(bytes.Buffer)309310 _, _, line, ok := runtime.Caller(2)311 if ok {312 fmt.Fprintf(out, "Line: %d ", line)313 }314 fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)315 t.Errorf(out.String())316}317318func checkStringContains(t *testing.T, found, expected string) {319 if !strings.Contains(found, expected) {320 logErr(t, found, expected)321 }322}323324func checkResultContains(t *testing.T, x resulter, check string) {325 checkStringContains(t, x.Output, check)326}327328func checkStringOmits(t *testing.T, found, expected string) {329 if strings.Contains(found, expected) {330 logErr(t, found, expected)331 }332}333334func checkResultOmits(t *testing.T, x resulter, check string) {335 checkStringOmits(t, x.Output, check)336}337338func checkOutputContains(t *testing.T, c *Command, check string) {339 buf := new(bytes.Buffer)340 c.SetOutput(buf)341 c.Execute()342343 if !strings.Contains(buf.String(), check) {344 logErr(t, buf.String(), check)345 }346}347348func TestSingleCommand(t *testing.T) {349 noRRSetupTest("print", "one", "two")350351 if te != nil || tt != nil {352 t.Error("Wrong command called")353 }354 if tp == nil {355 t.Error("Wrong command called")356 }357 if strings.Join(tp, " ") != "one two" {358 t.Error("Command didn't parse correctly")359 }360}361362func TestChildCommand(t *testing.T) {363 noRRSetupTest("echo", "times", "one", "two")364365 if te != nil || tp != nil {366 t.Error("Wrong command called")367 }368 if tt == nil {369 t.Error("Wrong command called")370 }371 if strings.Join(tt, " ") != "one two" {372 t.Error("Command didn't parse correctly")373 }374}375376func TestCommandAlias(t *testing.T) {377 noRRSetupTest("say", "times", "one", "two")378379 if te != nil || tp != nil {380 t.Error("Wrong command called")381 }382 if tt == nil {383 t.Error("Wrong command called")384 }385 if strings.Join(tt, " ") != "one two" {386 t.Error("Command didn't parse correctly")387 }388}389390func TestPrefixMatching(t *testing.T) {391 EnablePrefixMatching = true392 noRRSetupTest("ech", "times", "one", "two")393394 if te != nil || tp != nil {395 t.Error("Wrong command called")396 }397 if tt == nil {398 t.Error("Wrong command called")399 }400 if strings.Join(tt, " ") != "one two" {401 t.Error("Command didn't parse correctly")402 }403404 EnablePrefixMatching = false405}406407func TestNoPrefixMatching(t *testing.T) {408 EnablePrefixMatching = false409410 noRRSetupTest("ech", "times", "one", "two")411412 if !(tt == nil && te == nil && tp == nil) {413 t.Error("Wrong command called")414 }415}416417func TestAliasPrefixMatching(t *testing.T) {418 EnablePrefixMatching = true419 noRRSetupTest("sa", "times", "one", "two")420421 if te != nil || tp != nil {422 t.Error("Wrong command called")423 }424 if tt == nil {425 t.Error("Wrong command called")426 }427 if strings.Join(tt, " ") != "one two" {428 t.Error("Command didn't parse correctly")429 }430 EnablePrefixMatching = false431}432433func TestChildSameName(t *testing.T) {434 c := initializeWithSameName()435 c.AddCommand(cmdPrint, cmdEcho)436 c.SetArgs([]string{"print", "one", "two"})437 c.Execute()438439 if te != nil || tt != nil {440 t.Error("Wrong command called")441 }442 if tp == nil {443 t.Error("Wrong command called")444 }445 if strings.Join(tp, " ") != "one two" {446 t.Error("Command didn't parse correctly")447 }448}449450func TestGrandChildSameName(t *testing.T) {451 c := initializeWithSameName()452 cmdTimes.AddCommand(cmdPrint)453 c.AddCommand(cmdTimes)454 c.SetArgs([]string{"times", "print", "one", "two"})455 c.Execute()456457 if te != nil || tt != nil {458 t.Error("Wrong command called")459 }460 if tp == nil {461 t.Error("Wrong command called")462 }463 if strings.Join(tp, " ") != "one two" {464 t.Error("Command didn't parse correctly")465 }466}467468func TestUsage(t *testing.T) {469 x := fullSetupTest("help")470 checkResultContains(t, x, cmdRootWithRun.Use+" [flags]")471 x = fullSetupTest("help", "customflags")472 checkResultContains(t, x, cmdCustomFlags.Use)473 checkResultOmits(t, x, cmdCustomFlags.Use+" [flags]")474}475476func TestRootTakesNoArgs(t *testing.T) {477 c := initializeWithSameName()478 c.AddCommand(cmdPrint, cmdEcho)479 result := simpleTester(c, "illegal")480481 if result.Error == nil {482 t.Fatal("Expected an error")483 }484485 expectedError := `unknown command "illegal" for "print"`486 if !strings.Contains(result.Error.Error(), expectedError) {487 t.Errorf("exptected %v, got %v", expectedError, result.Error.Error())488 }489}490491func TestRootTakesArgs(t *testing.T) {492 c := cmdRootTakesArgs493 result := simpleTester(c, "legal")494495 if result.Error != nil {496 t.Errorf("expected no error, but got %v", result.Error)497 }498}499500func TestSubCmdTakesNoArgs(t *testing.T) {501 result := fullSetupTest("deprecated", "illegal")502503 if result.Error == nil {504 t.Fatal("Expected an error")505 }506507 expectedError := `unknown command "illegal" for "cobra-test deprecated"`508 if !strings.Contains(result.Error.Error(), expectedError) {509 t.Errorf("expected %v, got %v", expectedError, result.Error.Error())510 }511}512513func TestSubCmdTakesArgs(t *testing.T) {514 noRRSetupTest("echo", "times", "one", "two")515 if strings.Join(tt, " ") != "one two" {516 t.Error("Command didn't parse correctly")517 }518}519520func TestCmdOnlyValidArgs(t *testing.T) {521 result := noRRSetupTest("echo", "times", "one", "two", "five")522523 if result.Error == nil {524 t.Fatal("Expected an error")525 }526527 expectedError := `invalid argument "five"`528 if !strings.Contains(result.Error.Error(), expectedError) {529 t.Errorf("expected %v, got %v", expectedError, result.Error.Error())530 }531}532533func TestFlagLong(t *testing.T) {534 noRRSetupTest("echo", "--intone=13", "something", "--", "here")535536 if cmdEcho.ArgsLenAtDash() != 1 {537 t.Errorf("expected argsLenAtDash: %d but got %d", 1, cmdRootNoRun.ArgsLenAtDash())538 }539 if strings.Join(te, " ") != "something here" {540 t.Errorf("flags didn't leave proper args remaining..%s given", te)541 }542 if flagi1 != 13 {543 t.Errorf("int flag didn't get correct value, had %d", flagi1)544 }545 if flagi2 != 234 {546 t.Errorf("default flag value changed, 234 expected, %d given", flagi2)547 }548}549550func TestFlagShort(t *testing.T) {551 noRRSetupTest("echo", "-i13", "--", "something", "here")552553 if cmdEcho.ArgsLenAtDash() != 0 {554 t.Errorf("expected argsLenAtDash: %d but got %d", 0, cmdRootNoRun.ArgsLenAtDash())555 }556 if strings.Join(te, " ") != "something here" {557 t.Errorf("flags didn't leave proper args remaining..%s given", te)558 }559 if flagi1 != 13 {560 t.Errorf("int flag didn't get correct value, had %d", flagi1)561 }562 if flagi2 != 234 {563 t.Errorf("default flag value changed, 234 expected, %d given", flagi2)564 }565566 noRRSetupTest("echo", "-i", "13", "something", "here")567568 if strings.Join(te, " ") != "something here" {569 t.Errorf("flags didn't leave proper args remaining..%s given", te)570 }571 if flagi1 != 13 {572 t.Errorf("int flag didn't get correct value, had %d", flagi1)573 }574 if flagi2 != 234 {575 t.Errorf("default flag value changed, 234 expected, %d given", flagi2)576 }577578 noRRSetupTest("print", "-i99", "one", "two")579580 if strings.Join(tp, " ") != "one two" {581 t.Errorf("flags didn't leave proper args remaining..%s given", tp)582 }583 if flagi3 != 99 {584 t.Errorf("int flag didn't get correct value, had %d", flagi3)585 }586 if flagi1 != 123 {587 t.Errorf("default flag value changed on different command with same shortname, 234 expected, %d given", flagi2)588 }589}590591func TestChildCommandFlags(t *testing.T) {592 noRRSetupTest("echo", "times", "-j", "99", "one", "two")593594 if strings.Join(tt, " ") != "one two" {595 t.Errorf("flags didn't leave proper args remaining..%s given", tt)596 }597598 // Testing with flag that shouldn't be persistent599 r := noRRSetupTest("echo", "times", "-j", "99", "-i77", "one", "two")600601 if r.Error == nil {602 t.Errorf("invalid flag should generate error")603 }604605 if !strings.Contains(r.Error.Error(), "unknown shorthand") {606 t.Errorf("Wrong error message displayed, \n %s", r.Error)607 }608609 if flagi2 != 99 {610 t.Errorf("flag value should be 99, %d given", flagi2)611 }612613 if flagi1 != 123 {614 t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)615 }616617 // Testing with flag only existing on child618 r = noRRSetupTest("echo", "-j", "99", "-i77", "one", "two")619620 if r.Error == nil {621 t.Errorf("invalid flag should generate error")622 }623 if !strings.Contains(r.Error.Error(), "unknown shorthand flag") {624 t.Errorf("Wrong error message displayed, \n %s", r.Error)625 }626627 // Testing with persistent flag overwritten by child628 noRRSetupTest("echo", "times", "--strtwo=child", "one", "two")629630 if flags2b != "child" {631 t.Errorf("flag value should be child, %s given", flags2b)632 }633634 if flags2a != "two" {635 t.Errorf("unset flag should have default value, expecting two, given %s", flags2a)636 }637638 // Testing flag with invalid input639 r = noRRSetupTest("echo", "-i10E")640641 if r.Error == nil {642 t.Errorf("invalid input should generate error")643 }644 if !strings.Contains(r.Error.Error(), "invalid syntax") {645 t.Errorf("Wrong error message displayed, \n %s", r.Error)646 }647}648649func TestTrailingCommandFlags(t *testing.T) {650 x := fullSetupTest("echo", "two", "-x")651652 if x.Error == nil {653 t.Errorf("invalid flag should generate error")654 }655}656657func TestInvalidSubcommandFlags(t *testing.T) {658 cmd := initializeWithRootCmd()659 cmd.AddCommand(cmdTimes)660661 result := simpleTester(cmd, "times", "--inttwo=2", "--badflag=bar")662 // given that we are not checking here result.Error we check for663 // stock usage message664 checkResultContains(t, result, "cobra-test times [# times]")665 if strings.Contains(result.Error.Error(), "unknown flag: --inttwo") {666 t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag")667 }668669}670671func TestSubcommandExecuteC(t *testing.T) {672 cmd := initializeWithRootCmd()673 double := &Command{674 Use: "double message",675 Run: func(c *Command, args []string) {676 msg := strings.Join(args, " ")677 c.Println(msg, msg)678 },679 }680681 echo := &Command{682 Use: "echo message",683 Run: func(c *Command, args []string) {684 msg := strings.Join(args, " ")685 c.Println(msg)686 },687 }688689 cmd.AddCommand(double, echo)690691 result := simpleTesterC(cmd, "double", "hello", "world")692 checkResultContains(t, result, "hello world hello world")693694 if result.Command.Name() != "double" {695 t.Errorf("invalid cmd returned from ExecuteC: should be 'double' but got %s", result.Command.Name())696 }697698 result = simpleTesterC(cmd, "echo", "msg", "to", "be", "echoed")699 checkResultContains(t, result, "msg to be echoed")700701 if result.Command.Name() != "echo" {702 t.Errorf("invalid cmd returned from ExecuteC: should be 'echo' but got %s", result.Command.Name())703 }704}705706func TestSubcommandArgEvaluation(t *testing.T) {707 cmd := initializeWithRootCmd()708709 first := &Command{710 Use: "first",711 Run: func(cmd *Command, args []string) {712 },713 }714 cmd.AddCommand(first)715716 second := &Command{717 Use: "second",718 Run: func(cmd *Command, args []string) {719 fmt.Fprintf(cmd.OutOrStdout(), "%v", args)720 },721 }722 first.AddCommand(second)723724 result := simpleTester(cmd, "first", "second", "first", "third")725726 expectedOutput := fmt.Sprint([]string{"first third"})727 if result.Output != expectedOutput {728 t.Errorf("exptected %v, got %v", expectedOutput, result.Output)729 }730}731732func TestPersistentFlags(t *testing.T) {733 fullSetupTest("echo", "-s", "something", "-p", "more", "here")734735 // persistentFlag should act like normal flag on its own command736 if strings.Join(te, " ") != "more here" {737 t.Errorf("flags didn't leave proper args remaining..%s given", te)738 }739 if flags1 != "something" {740 t.Errorf("string flag didn't get correct value, had %v", flags1)741 }742 if !flagbp {743 t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)744 }745746 // persistentFlag should act like normal flag on its own command747 fullSetupTest("echo", "times", "-s", "again", "-c", "-p", "one", "two")748749 if strings.Join(tt, " ") != "one two" {750 t.Errorf("flags didn't leave proper args remaining. %s given", tt)751 }752753 if flags1 != "again" {754 t.Errorf("string flag didn't get correct value, had %v", flags1)755 }756757 if !flagb2 {758 t.Errorf("local flag not parsed correctly. Expected true, had %v", flagb2)759 }760 if !flagbp {761 t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)762 }763}764765func TestHelpCommand(t *testing.T) {766 x := fullSetupTest("help")767 checkResultContains(t, x, cmdRootWithRun.Long)768769 x = fullSetupTest("help", "echo")770 checkResultContains(t, x, cmdEcho.Long)771772 x = fullSetupTest("help", "echo", "times")773 checkResultContains(t, x, cmdTimes.Long)774}775776func TestChildCommandHelp(t *testing.T) {777 c := noRRSetupTest("print", "--help")778 checkResultContains(t, c, strtwoParentHelp)779 r := noRRSetupTest("echo", "times", "--help")780 checkResultContains(t, r, strtwoChildHelp)781}782783func TestNonRunChildHelp(t *testing.T) {784 x := noRRSetupTest("subnorun")785 checkResultContains(t, x, cmdSubNoRun.Long)786}787788func TestRunnableRootCommand(t *testing.T) {789 x := fullSetupTest("")790791 if !rootcalled {792 t.Errorf("Root Function was not called\n out:%v", x.Error)793 }794}795796func TestVisitParents(t *testing.T) {797 c := &Command{Use: "app"}798 sub := &Command{Use: "sub"}799 dsub := &Command{Use: "dsub"}800 sub.AddCommand(dsub)801 c.AddCommand(sub)802 total := 0803 add := func(x *Command) {804 total++805 }806 sub.VisitParents(add)807 if total != 1 {808 t.Errorf("Should have visited 1 parent but visited %d", total)809 }810811 total = 0812 dsub.VisitParents(add)813 if total != 2 {814 t.Errorf("Should have visited 2 parent but visited %d", total)815 }816817 total = 0818 c.VisitParents(add)819 if total != 0 {820 t.Errorf("Should have not visited any parent but visited %d", total)821 }822}823824func TestRunnableRootCommandNilInput(t *testing.T) {825 c := initializeWithRootCmd()826827 buf := new(bytes.Buffer)828 // Testing flag with invalid input829 c.SetOutput(buf)830 cmdEcho.AddCommand(cmdTimes)831 c.AddCommand(cmdPrint, cmdEcho)832 c.SetArgs([]string{})833834 err := c.Execute()835 if err != nil {836 t.Errorf("Execute() failed with %v", err)837 }838839 if !rootcalled {840 t.Errorf("Root Function was not called")841 }842}843844func TestRunnableRootCommandEmptyInput(t *testing.T) {845 args := []string{"", "--introot=12", ""}846 c := initializeWithRootCmd()847848 buf := new(bytes.Buffer)849 // Testing flag with invalid input850 c.SetOutput(buf)851 cmdEcho.AddCommand(cmdTimes)852 c.AddCommand(cmdPrint, cmdEcho)853 c.SetArgs(args)854855 c.Execute()856857 if !rootcalled {858 t.Errorf("Root Function was not called.\nOutput was:\n%s\n", buf)859 }860}861862func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {863 fullSetupTest("echo", "invalid-sub")864865 if te[0] != "invalid-sub" {866 t.Errorf("Subcommand didn't work...")867 }868}869870func TestRootFlags(t *testing.T) {871 fullSetupTest("-i", "17", "-b")872873 if !flagbr {874 t.Errorf("flag value should be true, %v given", flagbr)875 }876877 if flagir != 17 {878 t.Errorf("flag value should be 17, %d given", flagir)879 }880}881882func TestRootHelp(t *testing.T) {883 x := fullSetupTest("--help")884885 checkResultContains(t, x, "Available Commands:")886 checkResultContains(t, x, "for more information about a command")887888 if strings.Contains(x.Output, "unknown flag: --help") {889 t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)890 }891892 if strings.Contains(x.Output, cmdEcho.Use) {893 t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output)894 }895896 x = fullSetupTest("echo", "--help")897898 if strings.Contains(x.Output, cmdTimes.Use) {899 t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output)900 }901902 checkResultContains(t, x, "Available Commands:")903 checkResultContains(t, x, "for more information about a command")904905 if strings.Contains(x.Output, "unknown flag: --help") {906 t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)907 }908909}910911func TestFlagAccess(t *testing.T) {912 initialize()913914 cmdEcho.AddCommand(cmdTimes)915 local := cmdTimes.LocalFlags()916 inherited := cmdTimes.InheritedFlags()917918 for _, f := range []string{"inttwo", "strtwo", "booltwo"} {919 if local.Lookup(f) == nil {920 t.Errorf("LocalFlags expected to contain %s, Got: nil", f)921 }922 }923 if inherited.Lookup("strone") == nil {924 t.Errorf("InheritedFlags expected to contain strone, Got: nil")925 }926 if inherited.Lookup("strtwo") != nil {927 t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo")928 }929}930931func TestNoNRunnableRootCommandNilInput(t *testing.T) {932 c := initialize()933934 buf := new(bytes.Buffer)935 // Testing flag with invalid input936 c.SetOutput(buf)937 cmdEcho.AddCommand(cmdTimes)938 c.AddCommand(cmdPrint, cmdEcho)939 c.SetArgs([]string{})940941 c.Execute()942943 if !strings.Contains(buf.String(), cmdRootNoRun.Long) {944 t.Errorf("Expected to get help output, Got: \n %s", buf)945 }946}947948func TestRootNoCommandHelp(t *testing.T) {949 x := rootOnlySetupTest("--help")950951 checkResultOmits(t, x, "Available Commands:")952 checkResultOmits(t, x, "for more information about a command")953954 if strings.Contains(x.Output, "unknown flag: --help") {955 t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)956 }957958 x = rootOnlySetupTest("echo", "--help")959960 checkResultOmits(t, x, "Available Commands:")961 checkResultOmits(t, x, "for more information about a command")962963 if strings.Contains(x.Output, "unknown flag: --help") {964 t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)965 }966}967968func TestRootUnknownCommand(t *testing.T) {969 r := noRRSetupTest("bogus")970 s := "Error: unknown command \"bogus\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n"971972 if r.Output != s {973 t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)974 }975976 r = noRRSetupTest("--strtwo=a", "bogus")977 if r.Output != s {978 t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)979 }980}981982func TestRootUnknownCommandSilenced(t *testing.T) {983 r := noRRSetupTestSilenced("bogus")984985 if r.Output != "" {986 t.Errorf("Unexpected response.\nExpecting to be: \n\"\"\n Got:\n %q\n", r.Output)987 }988989 r = noRRSetupTestSilenced("--strtwo=a", "bogus")990 if r.Output != "" {991 t.Errorf("Unexpected response.\nExpecting to be:\n\"\"\nGot:\n %q\n", r.Output)992 }993}994995func TestRootSuggestions(t *testing.T) {996 outputWithSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\n\nDid you mean this?\n\t%s\n\nRun 'cobra-test --help' for usage.\n"997 outputWithoutSuggestions := "Error: unknown command \"%s\" for \"cobra-test\"\nRun 'cobra-test --help' for usage.\n"998999 cmd := initializeWithRootCmd()1000 cmd.AddCommand(cmdTimes)10011002 tests := map[string]string{1003 "time": "times",1004 "tiems": "times",1005 "tims": "times",1006 "timeS": "times",1007 "rimes": "times",1008 "ti": "times",1009 "t": "times",1010 "timely": "times",1011 "ri": "",1012 "timezone": "",1013 "foo": "",1014 "counts": "times",1015 }10161017 for typo, suggestion := range tests {1018 for _, suggestionsDisabled := range []bool{false, true} {1019 cmd.DisableSuggestions = suggestionsDisabled1020 result := simpleTester(cmd, typo)1021 expected := ""1022 if len(suggestion) == 0 || suggestionsDisabled {1023 expected = fmt.Sprintf(outputWithoutSuggestions, typo)1024 } else {1025 expected = fmt.Sprintf(outputWithSuggestions, typo, suggestion)1026 }1027 if result.Output != expected {1028 t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", expected, result.Output)1029 }1030 }1031 }1032}10331034func TestFlagsBeforeCommand(t *testing.T) {1035 // short without space1036 x := fullSetupTest("-i10", "echo")1037 if x.Error != nil {1038 t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)1039 }10401041 x = noRRSetupTest("echo", "-i=10")1042 if x.Error != nil {1043 t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)1044 }10451046 // long with equals1047 x = noRRSetupTest("--intone=123", "echo", "one", "two")1048 if x.Error != nil {1049 t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)1050 }10511052 // With parsing error properly reported1053 x = fullSetupTest("-i10E", "echo")1054 if !strings.Contains(x.Error.Error(), "invalid syntax") {1055 t.Errorf("Wrong error message displayed, \n %s", x.Error)1056 }1057}10581059func TestRemoveCommand(t *testing.T) {1060 versionUsed = 01061 c := initializeWithRootCmd()1062 c.AddCommand(cmdVersion1)1063 c.RemoveCommand(cmdVersion1)1064 x := fullTester(c, "version")1065 if x.Error == nil {1066 t.Errorf("Removed command should not have been called\n")1067 return1068 }1069}10701071func TestCommandWithoutSubcommands(t *testing.T) {1072 c := initializeWithRootCmd()10731074 x := simpleTester(c, "")1075 if x.Error != nil {1076 t.Errorf("Calling command without subcommands should not have error: %v", x.Error)1077 return1078 }1079}10801081func TestCommandWithoutSubcommandsWithArg(t *testing.T) {1082 c := initializeWithRootCmd()1083 expectedArgs := []string{"arg"}10841085 x := simpleTester(c, "arg")1086 if x.Error != nil {1087 t.Errorf("Calling command without subcommands but with arg should not have error: %v", x.Error)1088 return1089 }1090 if !reflect.DeepEqual(expectedArgs, tr) {1091 t.Errorf("Calling command without subcommands but with arg has wrong args: expected: %v, actual: %v", expectedArgs, tr)1092 return1093 }1094}10951096func TestReplaceCommandWithRemove(t *testing.T) {1097 versionUsed = 01098 c := initializeWithRootCmd()1099 c.AddCommand(cmdVersion1)1100 c.RemoveCommand(cmdVersion1)1101 c.AddCommand(cmdVersion2)1102 x := fullTester(c, "version")1103 if x.Error != nil {1104 t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)1105 return1106 }1107 if versionUsed == 1 {1108 t.Errorf("Removed command shouldn't be called\n")1109 }1110 if versionUsed != 2 {1111 t.Errorf("Replacing command should have been called but didn't\n")1112 }1113}11141115func TestDeprecatedSub(t *testing.T) {1116 c := fullSetupTest("deprecated")11171118 checkResultContains(t, c, cmdDeprecated.Deprecated)1119}11201121func TestPreRun(t *testing.T) {1122 noRRSetupTest("echo", "one", "two")1123 if echoPre == nil || echoPersPre == nil {1124 t.Error("PreRun or PersistentPreRun not called")1125 }1126 if rootPersPre != nil || timesPersPre != nil {1127 t.Error("Wrong *Pre functions called!")1128 }11291130 noRRSetupTest("echo", "times", "one", "two")1131 if timesPersPre == nil {1132 t.Error("PreRun or PersistentPreRun not called")1133 }1134 if echoPre != nil || echoPersPre != nil || rootPersPre != nil {1135 t.Error("Wrong *Pre functions called!")1136 }11371138 noRRSetupTest("print", "one", "two")1139 if rootPersPre == nil {1140 t.Error("Parent PersistentPreRun not called but should not have been")1141 }1142 if echoPre != nil || echoPersPre != nil || timesPersPre != nil {1143 t.Error("Wrong *Pre functions called!")1144 }1145}11461147// Check if cmdEchoSub gets PersistentPreRun from rootCmd even if is added last1148func TestPeristentPreRunPropagation(t *testing.T) {1149 rootCmd := initialize()11501151 // First add the cmdEchoSub to cmdPrint1152 cmdPrint.AddCommand(cmdEchoSub)1153 // Now add cmdPrint to rootCmd1154 rootCmd.AddCommand(cmdPrint)11551156 rootCmd.SetArgs([]string{"print", "echosub", "lala"})1157 rootCmd.Execute()11581159 if len(rootPersPre) == 0 || rootPersPre[0] != "lala" {1160 t.Error("RootCmd PersistentPreRun not called but should have been")1161 }1162}11631164func TestGlobalNormFuncPropagation(t *testing.T) {1165 normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1166 return pflag.NormalizedName(name)1167 }11681169 rootCmd := initialize()1170 rootCmd.AddCommand(cmdEcho)11711172 rootCmd.SetGlobalNormalizationFunc(normFunc)1173 if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {1174 t.Error("rootCmd seems to have a wrong normalization function")1175 }11761177 // Also check it propagates retroactively1178 if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(cmdEcho.GlobalNormalizationFunc()).Pointer() {1179 t.Error("cmdEcho should have had the normalization function of rootCmd")1180 }11811182 // First add the cmdEchoSub to cmdPrint1183 cmdPrint.AddCommand(cmdEchoSub)1184 if cmdPrint.GlobalNormalizationFunc() != nil && cmdEchoSub.GlobalNormalizationFunc() != nil {1185 t.Error("cmdPrint and cmdEchoSub should had no normalization functions")1186 }11871188 // Now add cmdPrint to rootCmd1189 rootCmd.AddCommand(cmdPrint)1190 if reflect.ValueOf(cmdPrint.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() ||1191 reflect.ValueOf(cmdEchoSub.GlobalNormalizationFunc()).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {1192 t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd")1193 }1194}11951196func TestNormPassedOnLocal(t *testing.T) {1197 n := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1198 return pflag.NormalizedName(strings.ToUpper(name))1199 }12001201 cmd := &Command{}1202 flagVal := false12031204 cmd.Flags().BoolVar(&flagVal, "flagname", true, "this is a dummy flag")1205 cmd.SetGlobalNormalizationFunc(n)1206 if cmd.LocalFlags().Lookup("flagname") != cmd.LocalFlags().Lookup("FLAGNAME") {1207 t.Error("Normalization function should be passed on to Local flag set")1208 }1209}12101211func TestNormPassedOnInherited(t *testing.T) {1212 n := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1213 return pflag.NormalizedName(strings.ToUpper(name))1214 }12151216 cmd, childBefore, childAfter := &Command{}, &Command{}, &Command{}1217 flagVal := false1218 cmd.AddCommand(childBefore)12191220 cmd.PersistentFlags().BoolVar(&flagVal, "flagname", true, "this is a dummy flag")1221 cmd.SetGlobalNormalizationFunc(n)12221223 cmd.AddCommand(childAfter)12241225 if f := childBefore.InheritedFlags(); f.Lookup("flagname") == nil || f.Lookup("flagname") != f.Lookup("FLAGNAME") {1226 t.Error("Normalization function should be passed on to inherited flag set in command added before flag")1227 }1228 if f := childAfter.InheritedFlags(); f.Lookup("flagname") == nil || f.Lookup("flagname") != f.Lookup("FLAGNAME") {1229 t.Error("Normalization function should be passed on to inherited flag set in command added after flag")1230 }1231}12321233// Related to https://github.com/spf13/cobra/issues/521.1234func TestNormConsistent(t *testing.T) {1235 n := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1236 return pflag.NormalizedName(strings.ToUpper(name))1237 }1238 id := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1239 return pflag.NormalizedName(name)1240 }12411242 cmd := &Command{}1243 flagVal := false12441245 cmd.Flags().BoolVar(&flagVal, "flagname", true, "this is a dummy flag")1246 // Build local flag set1247 cmd.LocalFlags()12481249 cmd.SetGlobalNormalizationFunc(n)1250 cmd.SetGlobalNormalizationFunc(id)12511252 if cmd.LocalFlags().Lookup("flagname") == cmd.LocalFlags().Lookup("FLAGNAME") {1253 t.Error("Normalizing flag names should not result in duplicate flags")1254 }1255}12561257func TestFlagOnPflagCommandLine(t *testing.T) {1258 flagName := "flagOnCommandLine"1259 pflag.String(flagName, "", "about my flag")1260 r := fullSetupTest("--help")12611262 checkResultContains(t, r, flagName)12631264 // Reset pflag.CommandLine flagset.1265 pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)1266}12678func TestAddTemplateFunctions(t *testing.T) {9 AddTemplateFunc("t", func() bool { return true })10 AddTemplateFuncs(template.FuncMap{11 "f": func() bool { return false },12 "h": func() string { return "Hello," },13 "w": func() string { return "world." }})141275 const usage = "Hello, world."127615 c := &Command{}16 c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)171280 if us := c.UsageString(); us != usage {1281 t.Errorf("c.UsageString() != \"%s\", is \"%s\"", usage, us)18 const expected = "Hello, world."19 if got := c.UsageString(); got != expected {20 t.Errorf("Expected UsageString: %v\nGot: %v", expected, got)21 }22}12841285func TestUsageIsNotPrintedTwice(t *testing.T) {1286 var cmd = &Command{Use: "root"}1287 var sub = &Command{Use: "sub"}1288 cmd.AddCommand(sub)12891290 r := simpleTester(cmd, "")1291 if strings.Count(r.Output, "Usage:") != 1 {1292 t.Error("Usage output is not printed exactly once")1293 }1294}12951296func BenchmarkInheritedFlags(b *testing.B) {1297 initialize()1298 cmdEcho.AddCommand(cmdTimes)1299 b.ResetTimer()13001301 for i := 0; i < b.N; i++ {1302 cmdTimes.InheritedFlags()1303 }1304}13051306func BenchmarkLocalFlags(b *testing.B) {1307 initialize()1308 cmdEcho.AddCommand(cmdTimes)1309 b.ResetTimer()13101311 for i := 0; i < b.N; i++ {1312 cmdTimes.LocalFlags()1313 }1314}
modified:cobra.go+9 added
186 unmodified lines
187188 }189 return d[len(s)][len(t)]190}191192func stringInSlice(a string, list []string) bool {193 for _, b := range list {194 if b == a {195 return true196 }197 }198 return false199}
modified:command_test.go+1279 added-280 removed
9 unmodified lines
1011 "github.com/spf13/pflag"12)1314// test to ensure hidden commands run as intended15func TestHiddenCommandExecutes(t *testing.T) {14func emptyRun(*Command, []string) {}1517 // ensure that outs does not already equal what the command will be setting it18 // to, if it did this test would not actually be testing anything...19 if outs == "hidden" {20 t.Errorf("outs should NOT EQUAL hidden")16func executeCommand(root *Command, args ...string) (output string, err error) {17 _, output, err = executeCommandC(root, args...)18 return output, err19}2021func executeCommandC(root *Command, args ...string) (c *Command, output string, err error) {22 buf := new(bytes.Buffer)23 root.SetOutput(buf)24 root.SetArgs(args)2526 c, err = root.ExecuteC()2728 return c, buf.String(), err29}3031func resetCommandLineFlagSet() {32 pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)33}3435func TestSingleCommand(t *testing.T) {36 var rootCmdArgs []string37 rootCmd := &Command{38 Use: "root",39 Args: ExactArgs(2),40 Run: func(_ *Command, args []string) { rootCmdArgs = args },41 }42 aCmd := &Command{Use: "a", Args: NoArgs, Run: emptyRun}43 bCmd := &Command{Use: "b", Args: NoArgs, Run: emptyRun}44 rootCmd.AddCommand(aCmd, bCmd)4523 cmdHidden.Execute()46 output, err := executeCommand(rootCmd, "one", "two")47 if output != "" {48 t.Errorf("Unexpected output: %v", output)49 }50 if err != nil {51 t.Errorf("Unexpected error: %v", err)52 }5325 // upon running the command, the value of outs should now be 'hidden'26 if outs != "hidden" {27 t.Errorf("Hidden command failed to run!")54 got := strings.Join(rootCmdArgs, " ")55 expected := "one two"56 if got != expected {57 t.Errorf("rootCmdArgs expected: %q, got: %q", expected, got)58 }59}6031// test to ensure hidden commands do not show up in usage/help text32func TestHiddenCommandIsHidden(t *testing.T) {33 if cmdHidden.IsAvailableCommand() {34 t.Errorf("Hidden command found!")61func TestChildCommand(t *testing.T) {62 var child1CmdArgs []string63 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}64 child1Cmd := &Command{65 Use: "child1",66 Args: ExactArgs(2),67 Run: func(_ *Command, args []string) { child1CmdArgs = args },68 }69 child2Cmd := &Command{Use: "child2", Args: NoArgs, Run: emptyRun}70 rootCmd.AddCommand(child1Cmd, child2Cmd)7172 output, err := executeCommand(rootCmd, "child1", "one", "two")73 if output != "" {74 t.Errorf("Unexpected output: %v", output)75 }76 if err != nil {77 t.Errorf("Unexpected error: %v", err)78 }7980 got := strings.Join(child1CmdArgs, " ")81 expected := "one two"82 if got != expected {83 t.Errorf("child1CmdArgs expected: %q, got: %q", expected, got)84 }85}8687func TestCallCommandWithoutSubcommands(t *testing.T) {88 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}89 _, err := executeCommand(rootCmd)90 if err != nil {91 t.Errorf("Calling command without subcommands should not have error: %v", err)92 }93}9495func TestRootExecuteUnknownCommand(t *testing.T) {96 rootCmd := &Command{Use: "root", Run: emptyRun}97 rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})9899 output, _ := executeCommand(rootCmd, "unknown")100101 expected := "Error: unknown command \"unknown\" for \"root\"\nRun 'root --help' for usage.\n"102103 if output != expected {104 t.Errorf("Expected:\n %q\nGot:\n %q\n", expected, output)105 }106}107108func TestSubcommandExecuteC(t *testing.T) {109 rootCmd := &Command{Use: "root", Run: emptyRun}110 childCmd := &Command{Use: "child", Run: emptyRun}111 rootCmd.AddCommand(childCmd)112113 c, output, err := executeCommandC(rootCmd, "child")114 if output != "" {115 t.Errorf("Unexpected output: %v", output)116 }117 if err != nil {118 t.Errorf("Unexpected error: %v", err)119 }120121 if c.Name() != "child" {122 t.Errorf(`invalid command returned from ExecuteC: expected "child"', got %q`, c.Name())123 }124}125126func TestRootUnknownCommandSilenced(t *testing.T) {127 rootCmd := &Command{Use: "root", Run: emptyRun}128 rootCmd.SilenceErrors = true129 rootCmd.SilenceUsage = true130 rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})131132 output, _ := executeCommand(rootCmd, "unknown")133 if output != "" {134 t.Errorf("Expected blank output, because of silenced usage.\nGot:\n %q\n", output)135 }136}137138func TestCommandAlias(t *testing.T) {139 var timesCmdArgs []string140 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}141 echoCmd := &Command{142 Use: "echo",143 Aliases: []string{"say", "tell"},144 Args: NoArgs,145 Run: emptyRun,146 }147 timesCmd := &Command{148 Use: "times",149 Args: ExactArgs(2),150 Run: func(_ *Command, args []string) { timesCmdArgs = args },151 }152 echoCmd.AddCommand(timesCmd)153 rootCmd.AddCommand(echoCmd)154155 output, err := executeCommand(rootCmd, "tell", "times", "one", "two")156 if output != "" {157 t.Errorf("Unexpected output: %v", output)158 }159 if err != nil {160 t.Errorf("Unexpected error: %v", err)161 }162163 got := strings.Join(timesCmdArgs, " ")164 expected := "one two"165 if got != expected {166 t.Errorf("timesCmdArgs expected: %v, got: %v", expected, got)167 }168}169170func TestEnablePrefixMatching(t *testing.T) {171 EnablePrefixMatching = true172173 var aCmdArgs []string174 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}175 aCmd := &Command{176 Use: "aCmd",177 Args: ExactArgs(2),178 Run: func(_ *Command, args []string) { aCmdArgs = args },179 }180 bCmd := &Command{Use: "bCmd", Args: NoArgs, Run: emptyRun}181 rootCmd.AddCommand(aCmd, bCmd)182183 output, err := executeCommand(rootCmd, "a", "one", "two")184 if output != "" {185 t.Errorf("Unexpected output: %v", output)186 }187 if err != nil {188 t.Errorf("Unexpected error: %v", err)189 }190191 got := strings.Join(aCmdArgs, " ")192 expected := "one two"193 if got != expected {194 t.Errorf("aCmdArgs expected: %q, got: %q", expected, got)195 }196197 EnablePrefixMatching = false198}199200func TestAliasPrefixMatching(t *testing.T) {201 EnablePrefixMatching = true202203 var timesCmdArgs []string204 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}205 echoCmd := &Command{206 Use: "echo",207 Aliases: []string{"say", "tell"},208 Args: NoArgs,209 Run: emptyRun,210 }211 timesCmd := &Command{212 Use: "times",213 Args: ExactArgs(2),214 Run: func(_ *Command, args []string) { timesCmdArgs = args },215 }216 echoCmd.AddCommand(timesCmd)217 rootCmd.AddCommand(echoCmd)218219 output, err := executeCommand(rootCmd, "sa", "times", "one", "two")220 if output != "" {221 t.Errorf("Unexpected output: %v", output)222 }223 if err != nil {224 t.Errorf("Unexpected error: %v", err)225 }226227 got := strings.Join(timesCmdArgs, " ")228 expected := "one two"229 if got != expected {230 t.Errorf("timesCmdArgs expected: %v, got: %v", expected, got)231 }232233 EnablePrefixMatching = false234}235236// TestChildSameName checks the correct behaviour of cobra in cases,237// when an application with name "foo" and with subcommand "foo"238// is executed with args "foo foo".239func TestChildSameName(t *testing.T) {240 var fooCmdArgs []string241 rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}242 fooCmd := &Command{243 Use: "foo",244 Args: ExactArgs(2),245 Run: func(_ *Command, args []string) { fooCmdArgs = args },246 }247 barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}248 rootCmd.AddCommand(fooCmd, barCmd)249250 output, err := executeCommand(rootCmd, "foo", "one", "two")251 if output != "" {252 t.Errorf("Unexpected output: %v", output)253 }254 if err != nil {255 t.Errorf("Unexpected error: %v", err)256 }257258 got := strings.Join(fooCmdArgs, " ")259 expected := "one two"260 if got != expected {261 t.Errorf("fooCmdArgs expected: %v, got: %v", expected, got)262 }263}264265// TestGrandChildSameName checks the correct behaviour of cobra in cases,266// when user has a root command and a grand child267// with the same name.268func TestGrandChildSameName(t *testing.T) {269 var fooCmdArgs []string270 rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}271 barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}272 fooCmd := &Command{273 Use: "foo",274 Args: ExactArgs(2),275 Run: func(_ *Command, args []string) { fooCmdArgs = args },276 }277 barCmd.AddCommand(fooCmd)278 rootCmd.AddCommand(barCmd)279280 output, err := executeCommand(rootCmd, "bar", "foo", "one", "two")281 if output != "" {282 t.Errorf("Unexpected output: %v", output)283 }284 if err != nil {285 t.Errorf("Unexpected error: %v", err)286 }287288 got := strings.Join(fooCmdArgs, " ")289 expected := "one two"290 if got != expected {291 t.Errorf("fooCmdArgs expected: %v, got: %v", expected, got)292 }293}294295func TestFlagLong(t *testing.T) {296 var cArgs []string297 c := &Command{298 Use: "c",299 Args: ArbitraryArgs,300 Run: func(_ *Command, args []string) { cArgs = args },301 }302303 var intFlagValue int304 var stringFlagValue string305 c.Flags().IntVar(&intFlagValue, "intf", -1, "")306 c.Flags().StringVar(&stringFlagValue, "sf", "", "")307308 output, err := executeCommand(c, "--intf=7", "--sf=abc", "one", "--", "two")309 if output != "" {310 t.Errorf("Unexpected output: %v", err)311 }312 if err != nil {313 t.Errorf("Unexpected error: %v", err)314 }315316 if c.ArgsLenAtDash() != 1 {317 t.Errorf("Expected ArgsLenAtDash: %v but got %v", 1, c.ArgsLenAtDash())318 }319 if intFlagValue != 7 {320 t.Errorf("Expected intFlagValue: %v, got %v", 7, intFlagValue)321 }322 if stringFlagValue != "abc" {323 t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)324 }325326 got := strings.Join(cArgs, " ")327 expected := "one two"328 if got != expected {329 t.Errorf("Expected arguments: %q, got %q", expected, got)330 }331}332333func TestFlagShort(t *testing.T) {334 var cArgs []string335 c := &Command{336 Use: "c",337 Args: ArbitraryArgs,338 Run: func(_ *Command, args []string) { cArgs = args },339 }340341 var intFlagValue int342 var stringFlagValue string343 c.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")344 c.Flags().StringVarP(&stringFlagValue, "sf", "s", "", "")345346 output, err := executeCommand(c, "-i", "7", "-sabc", "one", "two")347 if output != "" {348 t.Errorf("Unexpected output: %v", err)349 }350 if err != nil {351 t.Errorf("Unexpected error: %v", err)352 }353354 if intFlagValue != 7 {355 t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)356 }357 if stringFlagValue != "abc" {358 t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)359 }360361 got := strings.Join(cArgs, " ")362 expected := "one two"363 if got != expected {364 t.Errorf("Expected arguments: %q, got %q", expected, got)365 }366}367368func TestChildFlag(t *testing.T) {369 rootCmd := &Command{Use: "root", Run: emptyRun}370 childCmd := &Command{Use: "child", Run: emptyRun}371 rootCmd.AddCommand(childCmd)372373 var intFlagValue int374 childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")375376 output, err := executeCommand(rootCmd, "child", "-i7")377 if output != "" {378 t.Errorf("Unexpected output: %v", err)379 }380 if err != nil {381 t.Errorf("Unexpected error: %v", err)382 }383384 if intFlagValue != 7 {385 t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)386 }387}388389func TestChildFlagWithParentLocalFlag(t *testing.T) {390 rootCmd := &Command{Use: "root", Run: emptyRun}391 childCmd := &Command{Use: "child", Run: emptyRun}392 rootCmd.AddCommand(childCmd)393394 var intFlagValue int395 rootCmd.Flags().StringP("sf", "s", "", "")396 childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")397398 _, err := executeCommand(rootCmd, "child", "-i7", "-sabc")399 if err == nil {400 t.Errorf("Invalid flag should generate error")401 }402403 if !strings.Contains(err.Error(), "unknown shorthand") {404 t.Errorf("Wrong error message: %q", err.Error())405 }406407 if intFlagValue != 7 {408 t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)409 }410}411412func TestFlagInvalidInput(t *testing.T) {413 rootCmd := &Command{Use: "root", Run: emptyRun}414 rootCmd.Flags().IntP("intf", "i", -1, "")415416 _, err := executeCommand(rootCmd, "-iabc")417 if err == nil {418 t.Errorf("Invalid flag value should generate error")419 }420421 if !strings.Contains(err.Error(), "invalid syntax") {422 t.Errorf("Wrong error message: %q", err)423 }424}425426func TestFlagBeforeCommand(t *testing.T) {427 rootCmd := &Command{Use: "root", Run: emptyRun}428 childCmd := &Command{Use: "child", Run: emptyRun}429 rootCmd.AddCommand(childCmd)430431 var flagValue int432 childCmd.Flags().IntVarP(&flagValue, "intf", "i", -1, "")433434 // With short flag.435 _, err := executeCommand(rootCmd, "-i7", "child")436 if err != nil {437 t.Errorf("Unexpected error: %v", err)438 }439 if flagValue != 7 {440 t.Errorf("Expected flag value: %v, got %v", 7, flagValue)441 }442443 // With long flag.444 _, err = executeCommand(rootCmd, "--intf=8", "child")445 if err != nil {446 t.Errorf("Unexpected error: %v", err)447 }448 if flagValue != 8 {449 t.Errorf("Expected flag value: %v, got %v", 9, flagValue)450 }451}452453func TestStripFlags(t *testing.T) {454 tests := []struct {455 input []string456 output []string
2 unmodified lines
459 []string{"foo", "bar"},460 []string{"foo", "bar"},461 },462 {48 []string{"foo", "--bar", "-b"},463 []string{"foo", "--str", "-s"},464 []string{"foo"},465 },466 {52 []string{"-b", "foo", "--bar", "bar"},467 []string{"-s", "foo", "--str", "bar"},468 []string{},469 },470 {471 []string{"-i10", "echo"},
7 unmodified lines
479 []string{"--int=100", "echo"},480 []string{"echo"},481 },482 {68 []string{"-ib", "echo", "-bfoo", "baz"},483 []string{"-ib", "echo", "-sfoo", "baz"},484 []string{"echo", "baz"},485 },486 {487 []string{"-i=baz", "bar", "-i", "foo", "blah"},488 []string{"bar", "blah"},489 },490 {76 []string{"--int=baz", "-bbar", "-i", "foo", "blah"},491 []string{"--int=baz", "-sbar", "-i", "foo", "blah"},492 []string{"blah"},493 },494 {80 []string{"--cat", "bar", "-i", "foo", "blah"},495 []string{"--bool", "bar", "-i", "foo", "blah"},496 []string{"bar", "blah"},497 },498 {84 []string{"-c", "bar", "-i", "foo", "blah"},499 []string{"-b", "bar", "-i", "foo", "blah"},500 []string{"bar", "blah"},501 },502 {503 []string{"--persist", "bar"},
4 unmodified lines
508 []string{"bar"},509 },510 }51197 cmdPrint := &Command{98 Use: "print [string to print]",99 Short: "Print anything to the screen",100 Long: `an utterly useless command for testing.`,101 Run: func(cmd *Command, args []string) {102 tp = args103 },104 }512 c := &Command{Use: "c", Run: emptyRun}513 c.PersistentFlags().BoolP("persist", "p", false, "")514 c.Flags().IntP("int", "i", -1, "")515 c.Flags().StringP("str", "s", "", "")516 c.Flags().BoolP("bool", "b", false, "")517106 var flagi int107 var flagstr string108 var flagbool bool109 cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one")110 cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int")111 cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string")112 cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool")113114 for _, test := range tests {115 output := stripFlags(test.input, cmdPrint)116 if !reflect.DeepEqual(test.output, output) {117 t.Errorf("expected: %v, got: %v", test.output, output)518 for i, test := range tests {519 got := stripFlags(test.input, c)520 if !reflect.DeepEqual(test.output, got) {521 t.Errorf("(%v) Expected: %v, got: %v", i, test.output, got)522 }523 }524}525526func TestDisableFlagParsing(t *testing.T) {123 targs := []string{}124 cmdPrint := &Command{527 var cArgs []string528 c := &Command{529 Use: "c",530 DisableFlagParsing: true,126 Run: func(cmd *Command, args []string) {127 targs = args531 Run: func(_ *Command, args []string) {532 cArgs = args533 },534 }535536 args := []string{"cmd", "-v", "-race", "-file", "foo.go"}131 cmdPrint.SetArgs(args)132 err := cmdPrint.Execute()537 output, err := executeCommand(c, args...)538 if output != "" {539 t.Errorf("Unexpected output: %v", output)540 }541 if err != nil {134 t.Error(err)542 t.Errorf("Unexpected error: %v", err)543 }544136 if !reflect.DeepEqual(args, targs) {137 t.Errorf("expected: %v, got: %v", args, targs)545 if !reflect.DeepEqual(args, cArgs) {546 t.Errorf("Expected: %v, got: %v", args, cArgs)547 }548}549550func TestPersistentFlagsOnSameCommand(t *testing.T) {551 var rootCmdArgs []string552 rootCmd := &Command{553 Use: "root",554 Args: ArbitraryArgs,555 Run: func(_ *Command, args []string) { rootCmdArgs = args },556 }557558 var flagValue int559 rootCmd.PersistentFlags().IntVarP(&flagValue, "intf", "i", -1, "")560561 output, err := executeCommand(rootCmd, "-i7", "one", "two")562 if output != "" {563 t.Errorf("Unexpected output: %v", output)564 }565 if err != nil {566 t.Errorf("Unexpected error: %v", err)567 }568569 got := strings.Join(rootCmdArgs, " ")570 expected := "one two"571 if got != expected {572 t.Errorf("rootCmdArgs expected: %q, got %q", expected, got)573 }574 if flagValue != 7 {575 t.Errorf("flagValue expected: %v, got %v", 7, flagValue)576 }577}578579// TestEmptyInputs checks,580// if flags correctly parsed with blank strings in args.581func TestEmptyInputs(t *testing.T) {582 c := &Command{Use: "c", Run: emptyRun}583584 var flagValue int585 c.Flags().IntVarP(&flagValue, "intf", "i", -1, "")586587 output, err := executeCommand(c, "", "-i7", "")588 if output != "" {589 t.Errorf("Unexpected output: %v", output)590 }591 if err != nil {592 t.Errorf("Unexpected error: %v", err)593 }594595 if flagValue != 7 {596 t.Errorf("flagValue expected: %v, got %v", 7, flagValue)597 }598}599600func TestOverwrittenFlag(t *testing.T) {601 // TODO: This test fails, but should work.602 t.Skip()603604 parent := &Command{Use: "parent", Run: emptyRun}605 child := &Command{Use: "child", Run: emptyRun}606607 parent.PersistentFlags().Bool("boolf", false, "")608 parent.PersistentFlags().Int("intf", -1, "")609 child.Flags().String("strf", "", "")610 child.Flags().Int("intf", -1, "")611612 parent.AddCommand(child)613614 childInherited := child.InheritedFlags()615 childLocal := child.LocalFlags()616617 if childLocal.Lookup("strf") == nil {618 t.Error(`LocalFlags expected to contain "strf", got "nil"`)619 }620 if childInherited.Lookup("boolf") == nil {621 t.Error(`InheritedFlags expected to contain "boolf", got "nil"`)622 }623624 if childInherited.Lookup("intf") != nil {625 t.Errorf(`InheritedFlags should not contain overwritten flag "intf"`)626 }627 if childLocal.Lookup("intf") == nil {628 t.Error(`LocalFlags expected to contain "intf", got "nil"`)629 }630}631632func TestPersistentFlagsOnChild(t *testing.T) {633 var childCmdArgs []string634 rootCmd := &Command{Use: "root", Run: emptyRun}635 childCmd := &Command{636 Use: "child",637 Args: ArbitraryArgs,638 Run: func(_ *Command, args []string) { childCmdArgs = args },639 }640 rootCmd.AddCommand(childCmd)641642 var parentFlagValue int643 var childFlagValue int644 rootCmd.PersistentFlags().IntVarP(&parentFlagValue, "parentf", "p", -1, "")645 childCmd.Flags().IntVarP(&childFlagValue, "childf", "c", -1, "")646647 output, err := executeCommand(rootCmd, "child", "-c7", "-p8", "one", "two")648 if output != "" {649 t.Errorf("Unexpected output: %v", output)650 }651 if err != nil {652 t.Errorf("Unexpected error: %v", err)653 }654655 got := strings.Join(childCmdArgs, " ")656 expected := "one two"657 if got != expected {658 t.Errorf("childCmdArgs expected: %q, got %q", expected, got)659 }660 if parentFlagValue != 8 {661 t.Errorf("parentFlagValue expected: %v, got %v", 8, parentFlagValue)662 }663 if childFlagValue != 7 {664 t.Errorf("childFlagValue expected: %v, got %v", 7, childFlagValue)665 }666}667668func TestRequiredFlags(t *testing.T) {669 c := &Command{Use: "c", Run: emptyRun}670 c.Flags().String("foo1", "", "")671 c.MarkFlagRequired("foo1")672 c.Flags().String("foo2", "", "")673 c.MarkFlagRequired("foo2")674 c.Flags().String("bar", "", "")675676 expected := fmt.Sprintf("Required flag(s) %q, %q have/has not been set", "foo1", "foo2")677678 _, err := executeCommand(c)679 got := err.Error()680681 if got != expected {682 t.Errorf("Expected error: %q, got: %q", expected, got)683 }684}685686func TestPersistentRequiredFlags(t *testing.T) {687 parent := &Command{Use: "parent", Run: emptyRun}688 parent.PersistentFlags().String("foo1", "", "")689 parent.MarkPersistentFlagRequired("foo1")690 parent.PersistentFlags().String("foo2", "", "")691 parent.MarkPersistentFlagRequired("foo2")692 parent.Flags().String("foo3", "", "")693694 child := &Command{Use: "child", Run: emptyRun}695 child.Flags().String("bar1", "", "")696 child.MarkFlagRequired("bar1")697 child.Flags().String("bar2", "", "")698 child.MarkFlagRequired("bar2")699 child.Flags().String("bar3", "", "")700701 parent.AddCommand(child)702703 expected := fmt.Sprintf("Required flag(s) %q, %q, %q, %q have/has not been set", "bar1", "bar2", "foo1", "foo2")704705 _, err := executeCommand(parent, "child")706 if err.Error() != expected {707 t.Errorf("Expected %q, got %q", expected, err.Error())708 }709}710711func TestInitHelpFlagMergesFlags(t *testing.T) {712 usage := "custom flag"143 baseCmd := Command{Use: "testcmd"}144 baseCmd.PersistentFlags().Bool("help", false, usage)145 cmd := Command{Use: "do"}146 baseCmd.AddCommand(&cmd)713 rootCmd := &Command{Use: "root"}714 rootCmd.PersistentFlags().Bool("help", false, "custom flag")715 childCmd := &Command{Use: "child"}716 rootCmd.AddCommand(childCmd)717148 cmd.InitDefaultHelpFlag()149 actual := cmd.Flags().Lookup("help").Usage150 if actual != usage {151 t.Fatalf("Expected the help flag from the base command with usage '%s', but got the default with usage '%s'", usage, actual)718 childCmd.InitDefaultHelpFlag()719 got := childCmd.Flags().Lookup("help").Usage720 if got != usage {721 t.Errorf("Expected the help flag from the root command with usage: %v\nGot the default with usage: %v", usage, got)722 }723}724725func TestHelpCommandExecuted(t *testing.T) {726 rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}727 rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})728729 output, err := executeCommand(rootCmd, "help")730 if err != nil {731 t.Errorf("Unexpected error: %v", err)732 }733734 if !strings.Contains(output, rootCmd.Long) {735 t.Errorf("Expected to contain: %q, got: %q", rootCmd.Long, output)736 }737}738739func TestHelpCommandExecutedOnChild(t *testing.T) {740 rootCmd := &Command{Use: "root", Run: emptyRun}741 childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}742 rootCmd.AddCommand(childCmd)743744 output, err := executeCommand(rootCmd, "help", "child")745 if err != nil {746 t.Errorf("Unexpected error: %v", err)747 }748749 if !strings.Contains(output, childCmd.Long) {750 t.Errorf("Expected to contain: %q, got: %q", childCmd.Long, output)751 }752}753754func TestSetHelpCommand(t *testing.T) {755 c := &Command{Use: "c", Run: emptyRun}756 c.AddCommand(&Command{Use: "empty", Run: emptyRun})757758 expected := "WORKS"759 c.SetHelpCommand(&Command{760 Use: "help [command]",761 Short: "Help about any command",762 Long: `Help provides help for any command in the application.763 Simply type ` + c.Name() + ` help [path to command] for full details.`,764 Run: func(c *Command, _ []string) { c.Print(expected) },765 })766767 got, err := executeCommand(c, "help")768 if err != nil {769 t.Errorf("Unexpected error: %v", err)770 }771772 if got != expected {773 t.Errorf("Expected to contain %q, got %q", expected, got)774 }775}776777func TestHelpFlagExecuted(t *testing.T) {778 rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}779780 output, err := executeCommand(rootCmd, "--help")781 if err != nil {782 t.Errorf("Unexpected error: %v", err)783 }784785 if !strings.Contains(output, rootCmd.Long) {786 t.Errorf("Expected to contain: %q, got: %q", rootCmd.Long, output)787 }788}789790func TestHelpFlagExecutedOnChild(t *testing.T) {791 rootCmd := &Command{Use: "root", Run: emptyRun}792 childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}793 rootCmd.AddCommand(childCmd)794795 output, err := executeCommand(rootCmd, "child", "--help")796 if err != nil {797 t.Errorf("Unexpected error: %v", err)798 }799800 if !strings.Contains(output, childCmd.Long) {801 t.Errorf("Expected to contain: %q, got: %q", childCmd.Long, output)802 }803}804805// TestHelpFlagInHelp checks,806// if '--help' flag is shown in help for child (executing `parent help child`),807// that has no other flags.808// Related to https://github.com/spf13/cobra/issues/302.809func TestHelpFlagInHelp(t *testing.T) {810 output := new(bytes.Buffer)811 parent := &Command{Use: "parent", Run: func(*Command, []string) {}}812 parent.SetOutput(output)813814 child := &Command{Use: "child", Run: func(*Command, []string) {}}815 parent.AddCommand(child)816817 parent.SetArgs([]string{"help", "child"})818 err := parent.Execute()819 if err != nil {820 t.Fatal(err)821 }822823 if !strings.Contains(output.String(), "[flags]") {824 t.Errorf("\nExpecting to contain: %v\nGot: %v", "[flags]", output.String())825 }826}827828func TestFlagsInUsage(t *testing.T) {829 rootCmd := &Command{Use: "root", Args: NoArgs, Run: func(*Command, []string) {}}830 output, err := executeCommand(rootCmd, "--help")831 if err != nil {832 t.Errorf("Unexpected error: %v", err)833 }834835 expected := "[flags]"836 if !strings.Contains(output, expected) {837 t.Errorf("Expected to contain %q\ngot: %v", expected, output)838 }839}840841func TestHelpExecutedOnNonRunnableChild(t *testing.T) {842 rootCmd := &Command{Use: "root", Run: emptyRun}843 childCmd := &Command{Use: "child", Long: "Long description"}844 rootCmd.AddCommand(childCmd)845846 output, err := executeCommand(rootCmd, "child")847 if err != nil {848 t.Errorf("Unexpected error: %v", err)849 }850851 if !strings.Contains(output, childCmd.Long) {852 t.Errorf("Expected to contain: %q, got: %q", childCmd.Long, output)853 }854}855856func TestUsageIsNotPrintedTwice(t *testing.T) {857 var cmd = &Command{Use: "root"}858 var sub = &Command{Use: "sub"}859 cmd.AddCommand(sub)860861 output, _ := executeCommand(cmd, "")862 if strings.Count(output, "Usage:") != 1 {863 t.Error("Usage output is not printed exactly once")864 }865}866867func TestVisitParents(t *testing.T) {868 c := &Command{Use: "app"}869 sub := &Command{Use: "sub"}870 dsub := &Command{Use: "dsub"}871 sub.AddCommand(dsub)872 c.AddCommand(sub)873874 total := 0875 add := func(x *Command) {876 total++877 }878 sub.VisitParents(add)879 if total != 1 {880 t.Errorf("Should have visited 1 parent but visited %d", total)881 }882883 total = 0884 dsub.VisitParents(add)885 if total != 2 {886 t.Errorf("Should have visited 2 parents but visited %d", total)887 }888889 total = 0890 c.VisitParents(add)891 if total != 0 {892 t.Errorf("Should have visited no parents but visited %d", total)893 }894}895896func TestSuggestions(t *testing.T) {897 rootCmd := &Command{Use: "root", Run: emptyRun}898 timesCmd := &Command{899 Use: "times",900 SuggestFor: []string{"counts"},901 Run: emptyRun,902 }903 rootCmd.AddCommand(timesCmd)904905 templateWithSuggestions := "Error: unknown command \"%s\" for \"root\"\n\nDid you mean this?\n\t%s\n\nRun 'root --help' for usage.\n"906 templateWithoutSuggestions := "Error: unknown command \"%s\" for \"root\"\nRun 'root --help' for usage.\n"907908 tests := map[string]string{909 "time": "times",910 "tiems": "times",911 "tims": "times",912 "timeS": "times",913 "rimes": "times",914 "ti": "times",915 "t": "times",916 "timely": "times",917 "ri": "",918 "timezone": "",919 "foo": "",920 "counts": "times",921 }922923 for typo, suggestion := range tests {924 for _, suggestionsDisabled := range []bool{true, false} {925 rootCmd.DisableSuggestions = suggestionsDisabled926927 var expected string928 output, _ := executeCommand(rootCmd, typo)929930 if suggestion == "" || suggestionsDisabled {931 expected = fmt.Sprintf(templateWithoutSuggestions, typo)932 } else {933 expected = fmt.Sprintf(templateWithSuggestions, typo, suggestion)934 }935936 if output != expected {937 t.Errorf("Unexpected response.\nExpected:\n %q\nGot:\n %q\n", expected, output)938 }939 }940 }941}942943func TestRemoveCommand(t *testing.T) {944 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}945 childCmd := &Command{Use: "child", Run: emptyRun}946 rootCmd.AddCommand(childCmd)947 rootCmd.RemoveCommand(childCmd)948949 _, err := executeCommand(rootCmd, "child")950 if err == nil {951 t.Error("Expected error on calling removed command. Got nil.")952 }953}954955func TestReplaceCommandWithRemove(t *testing.T) {956 childUsed := 0957 rootCmd := &Command{Use: "root", Run: emptyRun}958 child1Cmd := &Command{959 Use: "child",960 Run: func(*Command, []string) { childUsed = 1 },961 }962 child2Cmd := &Command{963 Use: "child",964 Run: func(*Command, []string) { childUsed = 2 },965 }966 rootCmd.AddCommand(child1Cmd)967 rootCmd.RemoveCommand(child1Cmd)968 rootCmd.AddCommand(child2Cmd)969970 output, err := executeCommand(rootCmd, "child")971 if output != "" {972 t.Errorf("Unexpected output: %v", output)973 }974 if err != nil {975 t.Errorf("Unexpected error: %v", err)976 }977978 if childUsed == 1 {979 t.Error("Removed command shouldn't be called")980 }981 if childUsed != 2 {982 t.Error("Replacing command should have been called but didn't")983 }984}985986func TestDeprecatedCommand(t *testing.T) {987 rootCmd := &Command{Use: "root", Run: emptyRun}988 deprecatedCmd := &Command{989 Use: "deprecated",990 Deprecated: "This command is deprecated",991 Run: emptyRun,992 }993 rootCmd.AddCommand(deprecatedCmd)994995 output, err := executeCommand(rootCmd, "deprecated")996 if err != nil {997 t.Errorf("Unexpected error: %v", err)998 }9991000 expected := deprecatedCmd.Deprecated1001 if !strings.Contains(output, expected) {1002 t.Errorf("Expected to contain: %q\nGot:%q", expected, output)1003 }1004}10051006func TestHooks(t *testing.T) {1007 var (1008 persPreArgs string1009 preArgs string1010 runArgs string1011 postArgs string1012 persPostArgs string1013 )10141015 c := &Command{1016 Use: "c",1017 PersistentPreRun: func(_ *Command, args []string) {1018 persPreArgs = strings.Join(args, " ")1019 },1020 PreRun: func(_ *Command, args []string) {1021 preArgs = strings.Join(args, " ")1022 },1023 Run: func(_ *Command, args []string) {1024 runArgs = strings.Join(args, " ")1025 },1026 PostRun: func(_ *Command, args []string) {1027 postArgs = strings.Join(args, " ")1028 },1029 PersistentPostRun: func(_ *Command, args []string) {1030 persPostArgs = strings.Join(args, " ")1031 },1032 }10331034 output, err := executeCommand(c, "one", "two")1035 if output != "" {1036 t.Errorf("Unexpected output: %v", output)1037 }1038 if err != nil {1039 t.Errorf("Unexpected error: %v", err)1040 }10411042 if persPreArgs != "one two" {1043 t.Errorf("Expected persPreArgs %q, got %q", "one two", persPreArgs)1044 }1045 if preArgs != "one two" {1046 t.Errorf("Expected preArgs %q, got %q", "one two", preArgs)1047 }1048 if runArgs != "one two" {1049 t.Errorf("Expected runArgs %q, got %q", "one two", runArgs)1050 }1051 if postArgs != "one two" {1052 t.Errorf("Expected postArgs %q, got %q", "one two", postArgs)1053 }1054 if persPostArgs != "one two" {1055 t.Errorf("Expected persPostArgs %q, got %q", "one two", persPostArgs)1056 }1057}10581059func TestPersistentHooks(t *testing.T) {1060 var (1061 parentPersPreArgs string1062 parentPreArgs string1063 parentRunArgs string1064 parentPostArgs string1065 parentPersPostArgs string1066 )10671068 var (1069 childPersPreArgs string1070 childPreArgs string1071 childRunArgs string1072 childPostArgs string1073 childPersPostArgs string1074 )10751076 parentCmd := &Command{1077 Use: "parent",1078 PersistentPreRun: func(_ *Command, args []string) {1079 parentPersPreArgs = strings.Join(args, " ")1080 },1081 PreRun: func(_ *Command, args []string) {1082 parentPreArgs = strings.Join(args, " ")1083 },1084 Run: func(_ *Command, args []string) {1085 parentRunArgs = strings.Join(args, " ")1086 },1087 PostRun: func(_ *Command, args []string) {1088 parentPostArgs = strings.Join(args, " ")1089 },1090 PersistentPostRun: func(_ *Command, args []string) {1091 parentPersPostArgs = strings.Join(args, " ")1092 },1093 }10941095 childCmd := &Command{1096 Use: "child",1097 PersistentPreRun: func(_ *Command, args []string) {1098 childPersPreArgs = strings.Join(args, " ")1099 },1100 PreRun: func(_ *Command, args []string) {1101 childPreArgs = strings.Join(args, " ")1102 },1103 Run: func(_ *Command, args []string) {1104 childRunArgs = strings.Join(args, " ")1105 },1106 PostRun: func(_ *Command, args []string) {1107 childPostArgs = strings.Join(args, " ")1108 },1109 PersistentPostRun: func(_ *Command, args []string) {1110 childPersPostArgs = strings.Join(args, " ")1111 },1112 }1113 parentCmd.AddCommand(childCmd)11141115 output, err := executeCommand(parentCmd, "child", "one", "two")1116 if output != "" {1117 t.Errorf("Unexpected output: %v", output)1118 }1119 if err != nil {1120 t.Errorf("Unexpected error: %v", err)1121 }11221123 // TODO: This test fails, but should not.1124 // Related to https://github.com/spf13/cobra/issues/252.1125 //1126 // if parentPersPreArgs != "one two" {1127 // t.Errorf("Expected parentPersPreArgs %q, got %q", "one two", parentPersPreArgs)1128 // }1129 if parentPreArgs != "" {1130 t.Errorf("Expected blank parentPreArgs, got %q", parentPreArgs)1131 }1132 if parentRunArgs != "" {1133 t.Errorf("Expected blank parentRunArgs, got %q", parentRunArgs)1134 }1135 if parentPostArgs != "" {1136 t.Errorf("Expected blank parentPostArgs, got %q", parentPostArgs)1137 }1138 // TODO: This test fails, but should not.1139 // Related to https://github.com/spf13/cobra/issues/252.1140 //1141 // if parentPersPostArgs != "one two" {1142 // t.Errorf("Expected parentPersPostArgs %q, got %q", "one two", parentPersPostArgs)1143 // }11441145 if childPersPreArgs != "one two" {1146 t.Errorf("Expected childPersPreArgs %q, got %q", "one two", childPersPreArgs)1147 }1148 if childPreArgs != "one two" {1149 t.Errorf("Expected childPreArgs %q, got %q", "one two", childPreArgs)1150 }1151 if childRunArgs != "one two" {1152 t.Errorf("Expected childRunArgs %q, got %q", "one two", childRunArgs)1153 }1154 if childPostArgs != "one two" {1155 t.Errorf("Expected childPostArgs %q, got %q", "one two", childPostArgs)1156 }1157 if childPersPostArgs != "one two" {1158 t.Errorf("Expected childPersPostArgs %q, got %q", "one two", childPersPostArgs)1159 }1160}11611162// Related to https://github.com/spf13/cobra/issues/521.1163func TestGlobalNormFuncPropagation(t *testing.T) {1164 normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1165 return pflag.NormalizedName(name)1166 }11671168 rootCmd := &Command{Use: "root", Run: emptyRun}1169 childCmd := &Command{Use: "child", Run: emptyRun}1170 rootCmd.AddCommand(childCmd)11711172 rootCmd.SetGlobalNormalizationFunc(normFunc)1173 if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {1174 t.Error("rootCmd seems to have a wrong normalization function")1175 }11761177 if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(childCmd.GlobalNormalizationFunc()).Pointer() {1178 t.Error("childCmd should have had the normalization function of rootCmd")1179 }1180}11811182// Related to https://github.com/spf13/cobra/issues/521.1183func TestNormPassedOnLocal(t *testing.T) {1184 toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1185 return pflag.NormalizedName(strings.ToUpper(name))1186 }11871188 c := &Command{}1189 c.Flags().Bool("flagname", true, "this is a dummy flag")1190 c.SetGlobalNormalizationFunc(toUpper)1191 if c.LocalFlags().Lookup("flagname") != c.LocalFlags().Lookup("FLAGNAME") {1192 t.Error("Normalization function should be passed on to Local flag set")1193 }1194}11951196// Related to https://github.com/spf13/cobra/issues/521.1197func TestNormPassedOnInherited(t *testing.T) {1198 toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1199 return pflag.NormalizedName(strings.ToUpper(name))1200 }12011202 c := &Command{}1203 c.SetGlobalNormalizationFunc(toUpper)12041205 child1 := &Command{}1206 c.AddCommand(child1)12071208 c.PersistentFlags().Bool("flagname", true, "")12091210 child2 := &Command{}1211 c.AddCommand(child2)12121213 inherited := child1.InheritedFlags()1214 if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") {1215 t.Error("Normalization function should be passed on to inherited flag set in command added before flag")1216 }12171218 inherited = child2.InheritedFlags()1219 if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") {1220 t.Error("Normalization function should be passed on to inherited flag set in command added after flag")1221 }1222}12231224// Related to https://github.com/spf13/cobra/issues/521.1225func TestConsistentNormalizedName(t *testing.T) {1226 toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1227 return pflag.NormalizedName(strings.ToUpper(name))1228 }1229 n := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1230 return pflag.NormalizedName(name)1231 }12321233 c := &Command{}1234 c.Flags().Bool("flagname", true, "")1235 c.SetGlobalNormalizationFunc(toUpper)1236 c.SetGlobalNormalizationFunc(n)12371238 if c.LocalFlags().Lookup("flagname") == c.LocalFlags().Lookup("FLAGNAME") {1239 t.Error("Normalizing flag names should not result in duplicate flags")1240 }1241}12421243func TestFlagOnPflagCommandLine(t *testing.T) {1244 flagName := "flagOnCommandLine"1245 pflag.String(flagName, "", "about my flag")12461247 c := &Command{Use: "c", Run: emptyRun}1248 c.AddCommand(&Command{Use: "child", Run: emptyRun})12491250 output, _ := executeCommand(c, "--help")1251 if !strings.Contains(output, flagName) {1252 t.Errorf("Expected to contain: %q\nGot: %v", flagName, output)1253 }12541255 resetCommandLineFlagSet()1256}12571258// TestHiddenCommandExecutes checks,1259// if hidden commands run as intended.1260func TestHiddenCommandExecutes(t *testing.T) {1261 executed := false1262 c := &Command{1263 Use: "c",1264 Hidden: true,1265 Run: func(*Command, []string) { executed = true },1266 }12671268 output, err := executeCommand(c)1269 if output != "" {1270 t.Errorf("Unexpected output: %v", output)1271 }1272 if err != nil {1273 t.Errorf("Unexpected error: %v", err)1274 }12751276 if !executed {1277 t.Error("Hidden command should have been executed")1278 }1279}12801281// test to ensure hidden commands do not show up in usage/help text1282func TestHiddenCommandIsHidden(t *testing.T) {1283 c := &Command{Use: "c", Hidden: true, Run: emptyRun}1284 if c.IsAvailableCommand() {1285 t.Errorf("Hidden command should be unavailable")1286 }1287}12881289func TestCommandsAreSorted(t *testing.T) {1290 EnableCommandSorting = true12911292 originalNames := []string{"middle", "zlast", "afirst"}1293 expectedNames := []string{"afirst", "middle", "zlast"}1294161 var tmpCommand = &Command{Use: "tmp"}1295 var rootCmd = &Command{Use: "root"}12961297 for _, name := range originalNames {164 tmpCommand.AddCommand(&Command{Use: name})1298 rootCmd.AddCommand(&Command{Use: name})1299 }1300167 for i, c := range tmpCommand.Commands() {168 if expectedNames[i] != c.Name() {169 t.Errorf("expected: %s, got: %s", expectedNames[i], c.Name())1301 for i, c := range rootCmd.Commands() {1302 got := c.Name()1303 if expectedNames[i] != got {1304 t.Errorf("Expected: %s, got: %s", expectedNames[i], got)1305 }1306 }13071308 EnableCommandSorting = true
3 unmodified lines
1312 EnableCommandSorting = false13131314 originalNames := []string{"middle", "zlast", "afirst"}1315181 var tmpCommand = &Command{Use: "tmp"}1316 var rootCmd = &Command{Use: "root"}13171318 for _, name := range originalNames {184 tmpCommand.AddCommand(&Command{Use: name})1319 rootCmd.AddCommand(&Command{Use: name})1320 }1321187 for i, c := range tmpCommand.Commands() {188 if originalNames[i] != c.Name() {189 t.Errorf("expected: %s, got: %s", originalNames[i], c.Name())1322 for i, c := range rootCmd.Commands() {1323 got := c.Name()1324 if originalNames[i] != got {1325 t.Errorf("expected: %s, got: %s", originalNames[i], got)1326 }1327 }13281329 EnableCommandSorting = true1330}13311332func TestSetOutput(t *testing.T) {197 cmd := &Command{}198 cmd.SetOutput(nil)199 if out := cmd.OutOrStdout(); out != os.Stdout {200 t.Fatalf("expected setting output to nil to revert back to stdout, got %v", out)1333 c := &Command{}1334 c.SetOutput(nil)1335 if out := c.OutOrStdout(); out != os.Stdout {1336 t.Errorf("Expected setting output to nil to revert back to stdout")1337 }1338}13391340func TestFlagErrorFunc(t *testing.T) {205 cmd := &Command{206 Use: "print",207 RunE: func(cmd *Command, args []string) error {208 return nil209 },210 }211 expectedFmt := "This is expected: %s"1341 c := &Command{Use: "c", Run: emptyRun}1342213 cmd.SetFlagErrorFunc(func(c *Command, err error) error {1343 expectedFmt := "This is expected: %v"1344 c.SetFlagErrorFunc(func(_ *Command, err error) error {1345 return fmt.Errorf(expectedFmt, err)1346 })216 cmd.SetArgs([]string{"--bogus-flag"})217 cmd.SetOutput(new(bytes.Buffer))1347219 err := cmd.Execute()1348 _, err := executeCommand(c, "--unknown-flag")13491350 got := err.Error()221 expected := fmt.Sprintf(expectedFmt, "unknown flag: --bogus-flag")222 if err.Error() != expected {223 t.Errorf("expected %v, got %v", expected, err.Error())1351 expected := fmt.Sprintf(expectedFmt, "unknown flag: --unknown-flag")1352 if got != expected {1353 t.Errorf("Expected %v, got %v", expected, got)1354 }1355}13561357// TestSortedFlags checks,1358// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.1359// Related to https://github.com/spf13/cobra/issues/404.1360func TestSortedFlags(t *testing.T) {231 cmd := &Command{}232 cmd.Flags().SortFlags = false1361 c := &Command{}1362 c.Flags().SortFlags = false1363 names := []string{"C", "B", "A", "D"}1364 for _, name := range names {235 cmd.Flags().Bool(name, false, "")1365 c.Flags().Bool(name, false, "")1366 }13671368 i := 0239 cmd.LocalFlags().VisitAll(func(f *pflag.Flag) {1369 c.LocalFlags().VisitAll(func(f *pflag.Flag) {1370 if i == len(names) {1371 return1372 }243 if isStringInStringSlice(f.Name, names) {1373 if stringInSlice(f.Name, names) {1374 if names[i] != f.Name {1375 t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name)1376 }1377 i++1378 }1379 })1380}1381252// contains checks, if s is in ss.253func isStringInStringSlice(s string, ss []string) bool {254 for _, v := range ss {255 if v == s {256 return true257 }258 }259 return false260}261262// TestHelpFlagInHelp checks,263// if '--help' flag is shown in help for child (executing `parent help child`),264// that has no other flags.265// Related to https://github.com/spf13/cobra/issues/302.266func TestHelpFlagInHelp(t *testing.T) {267 output := new(bytes.Buffer)268 parent := &Command{Use: "parent", Run: func(*Command, []string) {}}269 parent.SetOutput(output)270271 child := &Command{Use: "child", Run: func(*Command, []string) {}}272 parent.AddCommand(child)273274 parent.SetArgs([]string{"help", "child"})275 err := parent.Execute()276 if err != nil {277 t.Fatal(err)278 }279280 if !strings.Contains(output.String(), "[flags]") {281 t.Errorf("\nExpecting to contain: %v\nGot: %v", "[flags]", output.String())282 }283}2841382// TestMergeCommandLineToFlags checks,1383// if pflag.CommandLine is correctly merged to c.Flags() after first call1384// of c.mergePersistentFlags.1385// Related to https://github.com/spf13/cobra/issues/443.1386func TestMergeCommandLineToFlags(t *testing.T) {1387 pflag.Bool("boolflag", false, "")291 c := &Command{Use: "c", Run: func(*Command, []string) {}}1388 c := &Command{Use: "c", Run: emptyRun}1389 c.mergePersistentFlags()1390 if c.Flags().Lookup("boolflag") == nil {1391 t.Fatal("Expecting to have flag from CommandLine in c.Flags()")1392 }1393297 // Reset pflag.CommandLine flagset.298 pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)1394 resetCommandLineFlagSet()1395}13961397// TestUseDeprecatedFlags checks,1398// if cobra.Execute() prints a message, if a deprecated flag is used.1399// Related to https://github.com/spf13/cobra/issues/463.1400func TestUseDeprecatedFlags(t *testing.T) {305 c := &Command{Use: "c", Run: func(*Command, []string) {}}306 output := new(bytes.Buffer)307 c.SetOutput(output)1401 c := &Command{Use: "c", Run: emptyRun}1402 c.Flags().BoolP("deprecated", "d", false, "deprecated flag")1403 c.Flags().MarkDeprecated("deprecated", "This flag is deprecated")1404311 c.SetArgs([]string{"c", "-d"})312 if err := c.Execute(); err != nil {1405 output, err := executeCommand(c, "c", "-d")1406 if err != nil {1407 t.Error("Unexpected error:", err)1408 }315 if !strings.Contains(output.String(), "This flag is deprecated") {316 t.Errorf("Expected to contain deprecated message, but got %q", output.String())1409 if !strings.Contains(output, "This flag is deprecated") {1410 t.Errorf("Expected to contain deprecated message, but got %q", output)1411 }1412}1413320// TestSetHelpCommand checks, if SetHelpCommand works correctly.321func TestSetHelpCommand(t *testing.T) {322 c := &Command{Use: "c", Run: func(*Command, []string) {}}323 output := new(bytes.Buffer)324 c.SetOutput(output)325 c.SetArgs([]string{"help"})326327 // Help will not be shown, if c has no subcommands.328 c.AddCommand(&Command{329 Use: "empty",330 Run: func(cmd *Command, args []string) {},331 })332333 correctMessage := "WORKS"334 c.SetHelpCommand(&Command{335 Use: "help [command]",336 Short: "Help about any command",337 Long: `Help provides help for any command in the application.338 Simply type ` + c.Name() + ` help [path to command] for full details.`,339 Run: func(c *Command, args []string) { c.Print(correctMessage) },340 })341342 if err := c.Execute(); err != nil {343 t.Error("Unexpected error:", err)344 }345346 if output.String() != correctMessage {347 t.Errorf("Expected to contain %q message, but got %q", correctMessage, output.String())348 }349}3501414func TestTraverseWithParentFlags(t *testing.T) {352 cmd := &Command{353 Use: "do",354 TraverseChildren: true,355 }356 cmd.Flags().String("foo", "", "foo things")357 cmd.Flags().BoolP("goo", "g", false, "foo things")1415 rootCmd := &Command{Use: "root", TraverseChildren: true}1416 rootCmd.Flags().String("str", "", "")1417 rootCmd.Flags().BoolP("bool", "b", false, "")1418359 sub := &Command{Use: "next"}360 sub.Flags().String("add", "", "add things")361 cmd.AddCommand(sub)1419 childCmd := &Command{Use: "child"}1420 childCmd.Flags().Int("int", -1, "")1421363 c, args, err := cmd.Traverse([]string{"-g", "--foo", "ok", "next", "--add"})1422 rootCmd.AddCommand(childCmd)14231424 c, args, err := rootCmd.Traverse([]string{"-b", "--str", "ok", "child", "--int"})1425 if err != nil {365 t.Fatalf("Expected no error: %s", err)1426 t.Errorf("Unexpected error: %v", err)1427 }1428 if len(args) != 1 && args[0] != "--add" {368 t.Fatalf("wrong args %s", args)1429 t.Errorf("Wrong args: %v", args)1430 }370 if c.Name() != sub.Name() {371 t.Fatalf("wrong command %q expected %q", c.Name(), sub.Name())1431 if c.Name() != childCmd.Name() {1432 t.Errorf("Expected command: %q, got: %q", childCmd.Name(), c.Name())1433 }1434}14351436func TestTraverseNoParentFlags(t *testing.T) {376 cmd := &Command{377 Use: "do",378 TraverseChildren: true,379 }380 cmd.Flags().String("foo", "", "foo things")1437 rootCmd := &Command{Use: "root", TraverseChildren: true}1438 rootCmd.Flags().String("foo", "", "foo things")1439382 sub := &Command{Use: "next"}383 sub.Flags().String("add", "", "add things")384 cmd.AddCommand(sub)1440 childCmd := &Command{Use: "child"}1441 childCmd.Flags().String("str", "", "")1442 rootCmd.AddCommand(childCmd)1443386 c, args, err := cmd.Traverse([]string{"next"})1444 c, args, err := rootCmd.Traverse([]string{"child"})1445 if err != nil {388 t.Fatalf("Expected no error: %s", err)1446 t.Errorf("Unexpected error: %v", err)1447 }1448 if len(args) != 0 {391 t.Fatalf("wrong args %s", args)1449 t.Errorf("Wrong args %v", args)1450 }393 if c.Name() != sub.Name() {394 t.Fatalf("wrong command %q expected %q", c.Name(), sub.Name())1451 if c.Name() != childCmd.Name() {1452 t.Errorf("Expected command: %q, got: %q", childCmd.Name(), c.Name())1453 }1454}14551456func TestTraverseWithBadParentFlags(t *testing.T) {399 cmd := &Command{400 Use: "do",401 TraverseChildren: true,402 }403 sub := &Command{Use: "next"}404 sub.Flags().String("add", "", "add things")405 cmd.AddCommand(sub)1457 rootCmd := &Command{Use: "root", TraverseChildren: true}1458407 expected := "got unknown flag: --add"1459 childCmd := &Command{Use: "child"}1460 childCmd.Flags().String("str", "", "")1461 rootCmd.AddCommand(childCmd)14621463 expected := "unknown flag: --str"1464409 c, _, err := cmd.Traverse([]string{"--add", "ok", "next"})410 if err == nil || strings.Contains(err.Error(), expected) {411 t.Fatalf("Expected error %s got %s", expected, err)1465 c, _, err := rootCmd.Traverse([]string{"--str", "ok", "child"})1466 if err == nil || !strings.Contains(err.Error(), expected) {1467 t.Errorf("Expected error, %q, got %q", expected, err)1468 }1469 if c != nil {414 t.Fatalf("Expected nil command")1470 t.Errorf("Expected nil command")1471 }1472}14731474func TestTraverseWithBadChildFlag(t *testing.T) {419 cmd := &Command{420 Use: "do",421 TraverseChildren: true,422 }423 cmd.Flags().String("foo", "", "foo things")1475 rootCmd := &Command{Use: "root", TraverseChildren: true}1476 rootCmd.Flags().String("str", "", "")1477425 sub := &Command{Use: "next"}426 cmd.AddCommand(sub)1478 childCmd := &Command{Use: "child"}1479 rootCmd.AddCommand(childCmd)14801481 // Expect no error because the last commands args shouldn't be parsed in429 // Traverse430 c, args, err := cmd.Traverse([]string{"next", "--add"})1482 // Traverse.1483 c, args, err := rootCmd.Traverse([]string{"child", "--str"})1484 if err != nil {432 t.Fatalf("Expected no error: %s", err)1485 t.Errorf("Unexpected error: %v", err)1486 }434 if len(args) != 1 && args[0] != "--add" {435 t.Fatalf("wrong args %s", args)1487 if len(args) != 1 && args[0] != "--str" {1488 t.Errorf("Wrong args: %v", args)1489 }437 if c.Name() != sub.Name() {438 t.Fatalf("wrong command %q expected %q", c.Name(), sub.Name())1490 if c.Name() != childCmd.Name() {1491 t.Errorf("Expected command %q, got: %q", childCmd.Name(), c.Name())1492 }1493}14941495func TestTraverseWithTwoSubcommands(t *testing.T) {443 cmd := &Command{444 Use: "do",445 TraverseChildren: true,446 }1496 rootCmd := &Command{Use: "root", TraverseChildren: true}1497448 sub := &Command{449 Use: "sub",450 TraverseChildren: true,451 }452 cmd.AddCommand(sub)1498 subCmd := &Command{Use: "sub", TraverseChildren: true}1499 rootCmd.AddCommand(subCmd)1500454 subsub := &Command{1501 subsubCmd := &Command{1502 Use: "subsub",1503 }457 sub.AddCommand(subsub)1504 subCmd.AddCommand(subsubCmd)1505459 c, _, err := cmd.Traverse([]string{"sub", "subsub"})1506 c, _, err := rootCmd.Traverse([]string{"sub", "subsub"})1507 if err != nil {461 t.Fatalf("Expected no error: %s", err)1508 t.Fatalf("Unexpected error: %v", err)1509 }463 if c.Name() != subsub.Name() {464 t.Fatalf("wrong command %q expected %q", c.Name(), subsub.Name())1510 if c.Name() != subsubCmd.Name() {1511 t.Fatalf("Expected command: %q, got %q", subsubCmd.Name(), c.Name())1512 }1513}1514468func TestRequiredFlags(t *testing.T) {469 c := &Command{Use: "c", Run: func(*Command, []string) {}}470 output := new(bytes.Buffer)471 c.SetOutput(output)472 c.Flags().String("foo1", "", "required foo1")473 c.MarkFlagRequired("foo1")474 c.Flags().String("foo2", "", "required foo2")475 c.MarkFlagRequired("foo2")476 c.Flags().String("bar", "", "optional bar")477478 expected := fmt.Sprintf("Required flag(s) %q, %q have/has not been set", "foo1", "foo2")479480 if err := c.Execute(); err != nil {481 if err.Error() != expected {482 t.Errorf("expected %v, got %v", expected, err.Error())483 }484 }485}486487func TestPersistentRequiredFlags(t *testing.T) {488 parent := &Command{Use: "parent", Run: func(*Command, []string) {}}489 output := new(bytes.Buffer)490 parent.SetOutput(output)491 parent.PersistentFlags().String("foo1", "", "required foo1")492 parent.MarkPersistentFlagRequired("foo1")493 parent.PersistentFlags().String("foo2", "", "required foo2")494 parent.MarkPersistentFlagRequired("foo2")495 parent.Flags().String("foo3", "", "optional foo3")496497 child := &Command{Use: "child", Run: func(*Command, []string) {}}498 child.Flags().String("bar1", "", "required bar1")499 child.MarkFlagRequired("bar1")500 child.Flags().String("bar2", "", "required bar2")501 child.MarkFlagRequired("bar2")502 child.Flags().String("bar3", "", "optional bar3")503504 parent.AddCommand(child)505 parent.SetArgs([]string{"child"})506507 expected := fmt.Sprintf("Required flag(s) %q, %q, %q, %q have/has not been set", "bar1", "bar2", "foo1", "foo2")508509 if err := parent.Execute(); err != nil {510 if err.Error() != expected {511 t.Errorf("expected %v, got %v", expected, err.Error())512 }513 }514}5151515// TestUpdateName checks if c.Name() updates on changed c.Use.1516// Related to https://github.com/spf13/cobra/pull/422#discussion_r143918343.1517func TestUpdateName(t *testing.T) {1518 c := &Command{Use: "name xyz"}
7 unmodified lines
modified:command.go+2 added-4 removed
619 unmodified lines
620 }621 return c622}623624// ArgsLenAtDash will return the length of f.Args at the moment when a -- was625// found during arg parsing. This allows your program to know which args were626// before the -- and which came after. (Description from627// https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash).624// ArgsLenAtDash will return the length of c.Flags().Args at the moment625// when a -- was found during args parsing.626func (c *Command) ArgsLenAtDash() int {627 return c.Flags().ArgsLenAtDash()628}629
778 unmodified lines
modified:zsh_completions_test.go+4 added-3 removed
75 unmodified lines
76 for _, tc := range tcs {77 t.Run(tc.name, func(t *testing.T) {78 buf := new(bytes.Buffer)79 tc.root.GenZshCompletion(buf)80 completion := buf.String()80 output := buf.String()8182 for _, expectedExpression := range tc.expectedExpressions {82 if !strings.Contains(completion, expectedExpression) {83 t.Errorf("expected completion to contain '%v' somewhere; got '%v'", expectedExpression, completion)83 if !strings.Contains(output, expectedExpression) {84 t.Errorf("Expected completion to contain %q somewhere; got %q", expectedExpression, output)85 }86 }87 })88 }
1 unmodified line