Skip to content
Myr

Fix tests so they give correct args (#445)

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

* Fix tests so they give correct args Shell already deletes all quotes and unite args under quotes, so we don't need to test it. * Simplify stripFlags * Fix 'unused' and 'gosimple' complaints

authored by Albert Nigmatzianov · committed by Eric Paris · parent b536627 · Browse files · 2 files+87 added−131 removed
This commit

State

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

Diff stats

2 files+87 added−131 removed

  • other:+87 added−131 removed

2 files+87 added−131 removed

modified:cobra_test.go+72 added-107 removed
11 unmodified lines
1213 "github.com/spf13/pflag"14)1516var tp, te, tt, t1, tr []string16var 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 globalFlag1 bool22var flagEcho, rootcalled bool21var rootcalled bool22var versionUsed int2324const strtwoParentHelp = "help message for parent flag strtwo"25const strtwoChildHelp = "help message for child flag strtwo"
199 unmodified lines
225 Output string226 Command *Command227}228230func fullSetupTest(input string) resulter {229func fullSetupTest(args ...string) resulter {230 c := initializeWithRootCmd()231233 return fullTester(c, input)232 return fullTester(c, args...)233}234236func noRRSetupTestSilenced(input string) resulter {235func noRRSetupTestSilenced(args ...string) resulter {236 c := initialize()237 c.SilenceErrors = true238 c.SilenceUsage = true240 return fullTester(c, input)239 return fullTester(c, args...)240}241243func noRRSetupTest(input string) resulter {242func noRRSetupTest(args ...string) resulter {243 c := initialize()244246 return fullTester(c, input)245 return fullTester(c, args...)246}247249func rootOnlySetupTest(input string) resulter {248func rootOnlySetupTest(args ...string) resulter {249 c := initializeWithRootCmd()250252 return simpleTester(c, input)251 return simpleTester(c, args...)252}253255func simpleTester(c *Command, input string) resulter {254func simpleTester(c *Command, args ...string) resulter {255 buf := new(bytes.Buffer)256 // Testing flag with invalid input257 c.SetOutput(buf)259 c.SetArgs(strings.Split(input, " "))258 c.SetArgs(args)259260 err := c.Execute()261 output := buf.String()262263 return resulter{err, output, c}264}265267func simpleTesterC(c *Command, input string) resulter {266func simpleTesterC(c *Command, args ...string) resulter {267 buf := new(bytes.Buffer)268 // Testing flag with invalid input269 c.SetOutput(buf)271 c.SetArgs(strings.Split(input, " "))270 c.SetArgs(args)271272 cmd, err := c.ExecuteC()273 output := buf.String()274275 return resulter{err, output, cmd}276}277279func fullTester(c *Command, input string) resulter {278func fullTester(c *Command, args ...string) resulter {279 buf := new(bytes.Buffer)280 // Testing flag with invalid input281 c.SetOutput(buf)282 cmdEcho.AddCommand(cmdTimes)283 c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdCustomFlags, cmdDeprecated)285 c.SetArgs(strings.Split(input, " "))284 c.SetArgs(args)285286 err := c.Execute()287 output := buf.String()288
41 unmodified lines
330 }331}332333func TestSingleCommand(t *testing.T) {335 noRRSetupTest("print one two")334 noRRSetupTest("print", "one", "two")335336 if te != nil || tt != nil {337 t.Error("Wrong command called")338 }
5 unmodified lines
344 }345}346347func TestChildCommand(t *testing.T) {349 noRRSetupTest("echo times one two")348 noRRSetupTest("echo", "times", "one", "two")349350 if te != nil || tp != nil {351 t.Error("Wrong command called")352 }
5 unmodified lines
358 }359}360361func TestCommandAlias(t *testing.T) {363 noRRSetupTest("say times one two")362 noRRSetupTest("say", "times", "one", "two")363364 if te != nil || tp != nil {365 t.Error("Wrong command called")366 }
6 unmodified lines
373}374375func TestPrefixMatching(t *testing.T) {376 EnablePrefixMatching = true378 noRRSetupTest("ech times one two")377 noRRSetupTest("ech", "times", "one", "two")378379 if te != nil || tp != nil {380 t.Error("Wrong command called")381 }
9 unmodified lines
391392func TestNoPrefixMatching(t *testing.T) {393 EnablePrefixMatching = false394396 noRRSetupTest("ech times one two")395 noRRSetupTest("ech", "times", "one", "two")396397 if !(tt == nil && te == nil && tp == nil) {398 t.Error("Wrong command called")399 }400}401402func TestAliasPrefixMatching(t *testing.T) {403 EnablePrefixMatching = true405 noRRSetupTest("sa times one two")404 noRRSetupTest("sa", "times", "one", "two")405406 if te != nil || tp != nil {407 t.Error("Wrong command called")408 }
8 unmodified lines
417418func TestChildSameName(t *testing.T) {419 c := initializeWithSameName()420 c.AddCommand(cmdPrint, cmdEcho)422 c.SetArgs(strings.Split("print one two", " "))421 c.SetArgs([]string{"print", "one", "two"})422 c.Execute()423424 if te != nil || tt != nil {425 t.Error("Wrong command called")
9 unmodified lines
435func TestGrandChildSameName(t *testing.T) {436 c := initializeWithSameName()437 cmdTimes.AddCommand(cmdPrint)438 c.AddCommand(cmdTimes)440 c.SetArgs(strings.Split("times print one two", " "))439 c.SetArgs([]string{"times", "print", "one", "two"})440 c.Execute()441442 if te != nil || tt != nil {443 t.Error("Wrong command called")
8 unmodified lines
452453func TestUsage(t *testing.T) {454 x := fullSetupTest("help")455 checkResultContains(t, x, cmdRootWithRun.Use+" [flags]")457 x = fullSetupTest("help customflags")456 x = fullSetupTest("help", "customflags")457 checkResultContains(t, x, cmdCustomFlags.Use)458 checkResultOmits(t, x, cmdCustomFlags.Use+" [flags]")459}460461func TestFlagLong(t *testing.T) {463 noRRSetupTest("echo --intone=13 something -- here")462 noRRSetupTest("echo", "--intone=13", "something", "--", "here")463464 if cmdEcho.ArgsLenAtDash() != 1 {465 t.Errorf("expected argsLenAtDash: %d but got %d", 1, cmdRootNoRun.ArgsLenAtDash())466 }
8 unmodified lines
475 }476}477478func TestFlagShort(t *testing.T) {480 noRRSetupTest("echo -i13 -- something here")479 noRRSetupTest("echo", "-i13", "--", "something", "here")480481 if cmdEcho.ArgsLenAtDash() != 0 {482 t.Errorf("expected argsLenAtDash: %d but got %d", 0, cmdRootNoRun.ArgsLenAtDash())483 }
6 unmodified lines
490 if flagi2 != 234 {491 t.Errorf("default flag value changed, 234 expected, %d given", flagi2)492 }493495 noRRSetupTest("echo -i 13 something here")494 noRRSetupTest("echo", "-i", "13", "something", "here")495496 if strings.Join(te, " ") != "something here" {497 t.Errorf("flags didn't leave proper args remaining..%s given", te)498 }
3 unmodified lines
502 if flagi2 != 234 {503 t.Errorf("default flag value changed, 234 expected, %d given", flagi2)504 }505507 noRRSetupTest("print -i99 one two")506 noRRSetupTest("print", "-i99", "one", "two")507508 if strings.Join(tp, " ") != "one two" {509 t.Errorf("flags didn't leave proper args remaining..%s given", tp)510 }
5 unmodified lines
516 }517}518519func TestChildCommandFlags(t *testing.T) {521 noRRSetupTest("echo times -j 99 one two")520 noRRSetupTest("echo", "times", "-j", "99", "one", "two")521522 if strings.Join(tt, " ") != "one two" {523 t.Errorf("flags didn't leave proper args remaining..%s given", tt)524 }525526 // Testing with flag that shouldn't be persistent528 r := noRRSetupTest("echo times -j 99 -i77 one two")527 r := noRRSetupTest("echo", "times", "-j", "99", "-i77", "one", "two")528529 if r.Error == nil {530 t.Errorf("invalid flag should generate error")531 }
10 unmodified lines
542 t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)543 }544545 // Testing with flag only existing on child547 r = noRRSetupTest("echo -j 99 -i77 one two")546 r = noRRSetupTest("echo", "-j", "99", "-i77", "one", "two")547548 if r.Error == nil {549 t.Errorf("invalid flag should generate error")550 }
1 unmodified line
552 t.Errorf("Wrong error message displayed, \n %s", r.Error)553 }554555 // Testing with persistent flag overwritten by child557 noRRSetupTest("echo times --strtwo=child one two")556 noRRSetupTest("echo", "times", "--strtwo=child", "one", "two")557558 if flags2b != "child" {559 t.Errorf("flag value should be child, %s given", flags2b)560 }
2 unmodified lines
563 t.Errorf("unset flag should have default value, expecting two, given %s", flags2a)564 }565566 // Testing flag with invalid input568 r = noRRSetupTest("echo -i10E")567 r = noRRSetupTest("echo", "-i10E")568569 if r.Error == nil {570 t.Errorf("invalid input should generate error")571 }
2 unmodified lines
574 }575}576577func TestTrailingCommandFlags(t *testing.T) {579 x := fullSetupTest("echo two -x")578 x := fullSetupTest("echo", "two", "-x")579580 if x.Error == nil {581 t.Errorf("invalid flag should generate error")582 }
2 unmodified lines
585func TestInvalidSubcommandFlags(t *testing.T) {586 cmd := initializeWithRootCmd()587 cmd.AddCommand(cmdTimes)588590 result := simpleTester(cmd, "times --inttwo=2 --badflag=bar")589 result := simpleTester(cmd, "times", "--inttwo=2", "--badflag=bar")590 // given that we are not checking here result.Error we check for591 // stock usage message592 checkResultContains(t, result, "cobra-test times [# times]")593 if strings.Contains(result.Error.Error(), "unknown flag: --inttwo") {
21 unmodified lines
615 }616617 cmd.AddCommand(double, echo)618620 result := simpleTesterC(cmd, "double hello world")619 result := simpleTesterC(cmd, "double", "hello", "world")620 checkResultContains(t, result, "hello world hello world")621622 if result.Command.Name() != "double" {623 t.Errorf("invalid cmd returned from ExecuteC: should be 'double' but got %s", result.Command.Name())624 }625627 result = simpleTesterC(cmd, "echo msg to be echoed")626 result = simpleTesterC(cmd, "echo", "msg", "to", "be", "echoed")627 checkResultContains(t, result, "msg to be echoed")628629 if result.Command.Name() != "echo" {630 t.Errorf("invalid cmd returned from ExecuteC: should be 'echo' but got %s", result.Command.Name())
17 unmodified lines
648 },649 }650 first.AddCommand(second)651653 result := simpleTester(cmd, "first second first third")652 result := simpleTester(cmd, "first", "second", "first", "third")653655 expectedOutput := fmt.Sprintf("%v", []string{"first third"})654 expectedOutput := fmt.Sprint([]string{"first third"})655 if result.Output != expectedOutput {656 t.Errorf("exptected %v, got %v", expectedOutput, result.Output)657 }658}659660func TestPersistentFlags(t *testing.T) {662 fullSetupTest("echo -s something -p more here")661 fullSetupTest("echo", "-s", "something", "-p", "more", "here")662663 // persistentFlag should act like normal flag on its own command664 if strings.Join(te, " ") != "more here" {665 t.Errorf("flags didn't leave proper args remaining..%s given", te)
5 unmodified lines
671 t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)672 }673674 // persistentFlag should act like normal flag on its own command676 fullSetupTest("echo times -s again -c -p test here")675 fullSetupTest("echo", "times", "-s", "again", "-c", "-p", "test", "here")676677 if strings.Join(tt, " ") != "test here" {678 t.Errorf("flags didn't leave proper args remaining. %s given", tt)679 }
13 unmodified lines
693func TestHelpCommand(t *testing.T) {694 x := fullSetupTest("help")695 checkResultContains(t, x, cmdRootWithRun.Long)696698 x = fullSetupTest("help echo")697 x = fullSetupTest("help", "echo")698 checkResultContains(t, x, cmdEcho.Long)699701 x = fullSetupTest("help echo times")700 x = fullSetupTest("help", "echo", "times")701 checkResultContains(t, x, cmdTimes.Long)702}703704func TestChildCommandHelp(t *testing.T) {706 c := noRRSetupTest("print --help")705 c := noRRSetupTest("print", "--help")706 checkResultContains(t, c, strtwoParentHelp)708 r := noRRSetupTest("echo times --help")707 r := noRRSetupTest("echo", "times", "--help")708 checkResultContains(t, r, strtwoChildHelp)709}710711func TestNonRunChildHelp(t *testing.T) {
3 unmodified lines
715716func TestRunnableRootCommand(t *testing.T) {717 x := fullSetupTest("")718720 if rootcalled != true {719 if !rootcalled {720 t.Errorf("Root Function was not called\n out:%v", x.Error)721 }722}723
25 unmodified lines
749 }750}751752func TestRunnableRootCommandNilInput(t *testing.T) {754 var emptyArg []string753 c := initializeWithRootCmd()754755 buf := new(bytes.Buffer)756 // Testing flag with invalid input757 c.SetOutput(buf)758 cmdEcho.AddCommand(cmdTimes)759 c.AddCommand(cmdPrint, cmdEcho)762 c.SetArgs(emptyArg)760 c.SetArgs([]string{})761762 err := c.Execute()763 if err != nil {764 t.Errorf("Execute() failed with %v", err)765 }766769 if rootcalled != true {767 if !rootcalled {768 t.Errorf("Root Function was not called")769 }770}771772func TestRunnableRootCommandEmptyInput(t *testing.T) {775 args := make([]string, 3)776 args[0] = ""777 args[1] = "--introot=12"778 args[2] = ""773 args := []string{"", "--introot=12", ""}774 c := initializeWithRootCmd()775776 buf := new(bytes.Buffer)777 // Testing flag with invalid input
3 unmodified lines
781 c.SetArgs(args)782783 c.Execute()784790 if rootcalled != true {791 t.Errorf("Root Function was not called.\n\nOutput was:\n\n%s\n", buf)785 if !rootcalled {786 t.Errorf("Root Function was not called.\nOutput was:\n%s\n", buf)787 }788}789790func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {796 fullSetupTest("echo invalid-sub")791 fullSetupTest("echo", "invalid-sub")792793 if te[0] != "invalid-sub" {794 t.Errorf("Subcommand didn't work...")795 }796}797798func TestRootFlags(t *testing.T) {804 fullSetupTest("-i 17 -b")799 fullSetupTest("-i", "17", "-b")800806 if flagbr != true {801 if !flagbr {802 t.Errorf("flag value should be true, %v given", flagbr)803 }804805 if flagir != 17 {
14 unmodified lines
820 if strings.Contains(x.Output, cmdEcho.Use) {821 t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output)822 }823829 x = fullSetupTest("echo --help")824 x = fullSetupTest("echo", "--help")825826 if strings.Contains(x.Output, cmdTimes.Use) {827 t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output)828 }
26 unmodified lines
855 }856}857858func TestNoNRunnableRootCommandNilInput(t *testing.T) {864 var args []string859 c := initialize()860861 buf := new(bytes.Buffer)862 // Testing flag with invalid input863 c.SetOutput(buf)864 cmdEcho.AddCommand(cmdTimes)865 c.AddCommand(cmdPrint, cmdEcho)872 c.SetArgs(args)866 c.SetArgs([]string{})867868 c.Execute()869870 if !strings.Contains(buf.String(), cmdRootNoRun.Long) {
10 unmodified lines
881 if strings.Contains(x.Output, "unknown flag: --help") {882 t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)883 }884891 x = rootOnlySetupTest("echo --help")885 x = rootOnlySetupTest("echo", "--help")886887 checkResultOmits(t, x, "Available Commands:")888 checkResultOmits(t, x, "for more information about a command")889
9 unmodified lines
899 if r.Output != s {900 t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)901 }902909 r = noRRSetupTest("--strtwo=a bogus")903 r = noRRSetupTest("--strtwo=a", "bogus")904 if r.Output != s {905 t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)906 }907}
4 unmodified lines
912 if r.Output != "" {913 t.Errorf("Unexpected response.\nExpecting to be: \n\"\"\n Got:\n %q\n", r.Output)914 }915922 r = noRRSetupTestSilenced("--strtwo=a bogus")916 r = noRRSetupTestSilenced("--strtwo=a", "bogus")917 if r.Output != "" {918 t.Errorf("Unexpected response.\nExpecting to be:\n\"\"\nGot:\n %q\n", r.Output)919 }920}
38 unmodified lines
959}960961func TestFlagsBeforeCommand(t *testing.T) {962 // short without space969 x := fullSetupTest("-i10 echo")963 x := fullSetupTest("-i10", "echo")964 if x.Error != nil {965 t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)966 }967974 // short (int) with equals975 // It appears that pflags doesn't support this...976 // Commenting out until support can be added968 x = noRRSetupTest("echo", "-i=10")969 if x.Error != nil {970 t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)971 }972978 //x = noRRSetupTest("echo -i=10")979 //if x.Error != nil {980 //t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)981 //}982973 // long with equals984 x = noRRSetupTest("--intone=123 echo one two")974 x = noRRSetupTest("--intone=123", "echo", "one", "two")975 if x.Error != nil {976 t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)977 }978979 // With parsing error properly reported990 x = fullSetupTest("-i10E echo")980 x = fullSetupTest("-i10E", "echo")981 if !strings.Contains(x.Error.Error(), "invalid syntax") {982 t.Errorf("Wrong error message displayed, \n %s", x.Error)983 }994995 //With quotes996 x = fullSetupTest("-s=\"walking\" echo")997 if x.Error != nil {998 t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)999 }10001001 //With quotes and space1002 x = fullSetupTest("-s=\"walking fast\" echo")1003 if x.Error != nil {1004 t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)1005 }10061007 //With inner quote1008 x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")1009 if x.Error != nil {1010 t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)1011 }10121013 //With quotes and space1014 x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")1015 if x.Error != nil {1016 t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)1017 }1018984}985986func TestRemoveCommand(t *testing.T) {987 versionUsed = 0
57 unmodified lines
1045 checkResultContains(t, c, cmdDeprecated.Deprecated)1046}10471048func TestPreRun(t *testing.T) {1084 noRRSetupTest("echo one two")1049 noRRSetupTest("echo", "one", "two")1050 if echoPre == nil || echoPersPre == nil {1051 t.Error("PreRun or PersistentPreRun not called")1052 }1053 if rootPersPre != nil || timesPersPre != nil {1054 t.Error("Wrong *Pre functions called!")1055 }10561092 noRRSetupTest("echo times one two")1057 noRRSetupTest("echo", "times", "one", "two")1058 if timesPersPre == nil {1059 t.Error("PreRun or PersistentPreRun not called")1060 }1061 if echoPre != nil || echoPersPre != nil || rootPersPre != nil {1062 t.Error("Wrong *Pre functions called!")1063 }10641100 noRRSetupTest("print one two")1065 noRRSetupTest("print", "one", "two")1066 if rootPersPre == nil {1067 t.Error("Parent PersistentPreRun not called but should not have been")1068 }1069 if echoPre != nil || echoPersPre != nil || timesPersPre != nil {
9 unmodified lines
1079 cmdPrint.AddCommand(cmdEchoSub)1080 // Now add cmdPrint to rootCmd1081 rootCmd.AddCommand(cmdPrint)10821118 rootCmd.SetArgs(strings.Split("print echosub lala", " "))1083 rootCmd.SetArgs([]string{"print", "echosub", "lala"})1084 rootCmd.Execute()10851121 if rootPersPre == nil || len(rootPersPre) == 0 || rootPersPre[0] != "lala" {1086 if len(rootPersPre) == 0 || rootPersPre[0] != "lala" {1087 t.Error("RootCmd PersistentPreRun not called but should have been")1088 }1089}1090
83 unmodified lines
modified:command.go+15 added-24 removed
428 unmodified lines
429 }430 c.mergePersistentFlags()431432 commands := []string{}433 inQuote := false433 flags := c.Flags()434435Loop:436 for len(args) > 0 {437 s := args[0]438 args = args[1:]440 if !inQuote {441 switch {442 case strings.HasPrefix(s, "\"") || strings.Contains(s, "=\""):443 inQuote = true444 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):445 // If '--flag arg' then446 // delete arg from args.447 fallthrough // (do the same as below)448 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):449 // If '-f arg' then450 // delete 'arg' from args or break the loop if len(args) <= 1.451 if len(args) <= 1 {452 break Loop453 } else {454 args = args[1:]455 continue439 switch {440 case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):441 // If '--flag arg' then442 // delete arg from args.443 fallthrough // (do the same as below)444 case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags):445 // If '-f arg' then446 // delete 'arg' from args or break the loop if len(args) <= 1.447 if len(args) <= 1 {448 break Loop449 } else {450 args = args[1:]451 continue456 }457 case s != "" && !strings.HasPrefix(s, "-"):458 commands = append(commands, s)452 }453 case s != "" && !strings.HasPrefix(s, "-"):454 commands = append(commands, s)455 }461462 if strings.HasSuffix(s, "\"") && !strings.HasSuffix(s, "\\\"") {463 inQuote = false464 }456 }457458 return commands459}
830 unmodified lines