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
Provenance
- Commit
51b7cf5- Tree
18c695f- Author
Albert Nigmatzianov <albertnigma@gmail.com>- Committer
Eric Paris <eparis@redhat.com>- Parent
b536627
2 files changed+87 added−131 removed
modified:cobra_test.go+72 added-107 removed
11 unmodified lines12 13 "github.com/spf13/pflag"14 )15 16-var tp, te, tt, t1, tr []string16+var tp, te, tt, tr []string17 var rootPersPre, echoPre, echoPersPre, timesPersPre []string18 var flagb1, flagb2, flagb3, flagbr, flagbp bool19 var flags1, flags2a, flags2b, flags3, outs string20 var flagi1, flagi2, flagi3, flagi4, flagir int21-var globalFlag1 bool22-var flagEcho, rootcalled bool21+var rootcalled bool22 var versionUsed int23 24 const strtwoParentHelp = "help message for parent flag strtwo"25 const strtwoChildHelp = "help message for child flag strtwo"199 unmodified lines225 Output string226 Command *Command227 }228 230-func fullSetupTest(input string) resulter {229+func fullSetupTest(args ...string) resulter {230 c := initializeWithRootCmd()231 233- return fullTester(c, input)232+ return fullTester(c, args...)233 }234 236-func noRRSetupTestSilenced(input string) resulter {235+func noRRSetupTestSilenced(args ...string) resulter {236 c := initialize()237 c.SilenceErrors = true238 c.SilenceUsage = true240- return fullTester(c, input)239+ return fullTester(c, args...)240 }241 243-func noRRSetupTest(input string) resulter {242+func noRRSetupTest(args ...string) resulter {243 c := initialize()244 246- return fullTester(c, input)245+ return fullTester(c, args...)246 }247 249-func rootOnlySetupTest(input string) resulter {248+func rootOnlySetupTest(args ...string) resulter {249 c := initializeWithRootCmd()250 252- return simpleTester(c, input)251+ return simpleTester(c, args...)252 }253 255-func simpleTester(c *Command, input string) resulter {254+func 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)259 260 err := c.Execute()261 output := buf.String()262 263 return resulter{err, output, c}264 }265 267-func simpleTesterC(c *Command, input string) resulter {266+func 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)271 272 cmd, err := c.ExecuteC()273 output := buf.String()274 275 return resulter{err, output, cmd}276 }277 279-func fullTester(c *Command, input string) resulter {278+func 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)285 286 err := c.Execute()287 output := buf.String()288 41 unmodified lines330 }331 }332 333 func TestSingleCommand(t *testing.T) {335- noRRSetupTest("print one two")334+ noRRSetupTest("print", "one", "two")335 336 if te != nil || tt != nil {337 t.Error("Wrong command called")338 }5 unmodified lines344 }345 }346 347 func TestChildCommand(t *testing.T) {349- noRRSetupTest("echo times one two")348+ noRRSetupTest("echo", "times", "one", "two")349 350 if te != nil || tp != nil {351 t.Error("Wrong command called")352 }5 unmodified lines358 }359 }360 361 func TestCommandAlias(t *testing.T) {363- noRRSetupTest("say times one two")362+ noRRSetupTest("say", "times", "one", "two")363 364 if te != nil || tp != nil {365 t.Error("Wrong command called")366 }6 unmodified lines373 }374 375 func TestPrefixMatching(t *testing.T) {376 EnablePrefixMatching = true378- noRRSetupTest("ech times one two")377+ noRRSetupTest("ech", "times", "one", "two")378 379 if te != nil || tp != nil {380 t.Error("Wrong command called")381 }9 unmodified lines391 392 func TestNoPrefixMatching(t *testing.T) {393 EnablePrefixMatching = false394 396- noRRSetupTest("ech times one two")395+ noRRSetupTest("ech", "times", "one", "two")396 397 if !(tt == nil && te == nil && tp == nil) {398 t.Error("Wrong command called")399 }400 }401 402 func TestAliasPrefixMatching(t *testing.T) {403 EnablePrefixMatching = true405- noRRSetupTest("sa times one two")404+ noRRSetupTest("sa", "times", "one", "two")405 406 if te != nil || tp != nil {407 t.Error("Wrong command called")408 }8 unmodified lines417 418 func 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()423 424 if te != nil || tt != nil {425 t.Error("Wrong command called")9 unmodified lines435 func 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()441 442 if te != nil || tt != nil {443 t.Error("Wrong command called")8 unmodified lines452 453 func 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 }460 461 func TestFlagLong(t *testing.T) {463- noRRSetupTest("echo --intone=13 something -- here")462+ noRRSetupTest("echo", "--intone=13", "something", "--", "here")463 464 if cmdEcho.ArgsLenAtDash() != 1 {465 t.Errorf("expected argsLenAtDash: %d but got %d", 1, cmdRootNoRun.ArgsLenAtDash())466 }8 unmodified lines475 }476 }477 478 func TestFlagShort(t *testing.T) {480- noRRSetupTest("echo -i13 -- something here")479+ noRRSetupTest("echo", "-i13", "--", "something", "here")480 481 if cmdEcho.ArgsLenAtDash() != 0 {482 t.Errorf("expected argsLenAtDash: %d but got %d", 0, cmdRootNoRun.ArgsLenAtDash())483 }6 unmodified lines490 if flagi2 != 234 {491 t.Errorf("default flag value changed, 234 expected, %d given", flagi2)492 }493 495- noRRSetupTest("echo -i 13 something here")494+ noRRSetupTest("echo", "-i", "13", "something", "here")495 496 if strings.Join(te, " ") != "something here" {497 t.Errorf("flags didn't leave proper args remaining..%s given", te)498 }3 unmodified lines502 if flagi2 != 234 {503 t.Errorf("default flag value changed, 234 expected, %d given", flagi2)504 }505 507- noRRSetupTest("print -i99 one two")506+ noRRSetupTest("print", "-i99", "one", "two")507 508 if strings.Join(tp, " ") != "one two" {509 t.Errorf("flags didn't leave proper args remaining..%s given", tp)510 }5 unmodified lines516 }517 }518 519 func TestChildCommandFlags(t *testing.T) {521- noRRSetupTest("echo times -j 99 one two")520+ noRRSetupTest("echo", "times", "-j", "99", "one", "two")521 522 if strings.Join(tt, " ") != "one two" {523 t.Errorf("flags didn't leave proper args remaining..%s given", tt)524 }525 526 // 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")528 529 if r.Error == nil {530 t.Errorf("invalid flag should generate error")531 }10 unmodified lines542 t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)543 }544 545 // Testing with flag only existing on child547- r = noRRSetupTest("echo -j 99 -i77 one two")546+ r = noRRSetupTest("echo", "-j", "99", "-i77", "one", "two")547 548 if r.Error == nil {549 t.Errorf("invalid flag should generate error")550 }1 unmodified line552 t.Errorf("Wrong error message displayed, \n %s", r.Error)553 }554 555 // Testing with persistent flag overwritten by child557- noRRSetupTest("echo times --strtwo=child one two")556+ noRRSetupTest("echo", "times", "--strtwo=child", "one", "two")557 558 if flags2b != "child" {559 t.Errorf("flag value should be child, %s given", flags2b)560 }2 unmodified lines563 t.Errorf("unset flag should have default value, expecting two, given %s", flags2a)564 }565 566 // Testing flag with invalid input568- r = noRRSetupTest("echo -i10E")567+ r = noRRSetupTest("echo", "-i10E")568 569 if r.Error == nil {570 t.Errorf("invalid input should generate error")571 }2 unmodified lines574 }575 }576 577 func TestTrailingCommandFlags(t *testing.T) {579- x := fullSetupTest("echo two -x")578+ x := fullSetupTest("echo", "two", "-x")579 580 if x.Error == nil {581 t.Errorf("invalid flag should generate error")582 }2 unmodified lines585 func TestInvalidSubcommandFlags(t *testing.T) {586 cmd := initializeWithRootCmd()587 cmd.AddCommand(cmdTimes)588 590- 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 lines615 }616 617 cmd.AddCommand(double, echo)618 620- result := simpleTesterC(cmd, "double hello world")619+ result := simpleTesterC(cmd, "double", "hello", "world")620 checkResultContains(t, result, "hello world hello world")621 622 if result.Command.Name() != "double" {623 t.Errorf("invalid cmd returned from ExecuteC: should be 'double' but got %s", result.Command.Name())624 }625 627- 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")628 629 if result.Command.Name() != "echo" {630 t.Errorf("invalid cmd returned from ExecuteC: should be 'echo' but got %s", result.Command.Name())17 unmodified lines648 },649 }650 first.AddCommand(second)651 653- result := simpleTester(cmd, "first second first third")652+ result := simpleTester(cmd, "first", "second", "first", "third")653 655- 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 }659 660 func TestPersistentFlags(t *testing.T) {662- fullSetupTest("echo -s something -p more here")661+ fullSetupTest("echo", "-s", "something", "-p", "more", "here")662 663 // 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 lines671 t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)672 }673 674 // 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")676 677 if strings.Join(tt, " ") != "test here" {678 t.Errorf("flags didn't leave proper args remaining. %s given", tt)679 }13 unmodified lines693 func TestHelpCommand(t *testing.T) {694 x := fullSetupTest("help")695 checkResultContains(t, x, cmdRootWithRun.Long)696 698- x = fullSetupTest("help echo")697+ x = fullSetupTest("help", "echo")698 checkResultContains(t, x, cmdEcho.Long)699 701- x = fullSetupTest("help echo times")700+ x = fullSetupTest("help", "echo", "times")701 checkResultContains(t, x, cmdTimes.Long)702 }703 704 func 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 }710 711 func TestNonRunChildHelp(t *testing.T) {3 unmodified lines715 716 func TestRunnableRootCommand(t *testing.T) {717 x := fullSetupTest("")718 720- if rootcalled != true {719+ if !rootcalled {720 t.Errorf("Root Function was not called\n out:%v", x.Error)721 }722 }723 25 unmodified lines749 }750 }751 752 func TestRunnableRootCommandNilInput(t *testing.T) {754- var emptyArg []string753 c := initializeWithRootCmd()754 755 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{})761 762 err := c.Execute()763 if err != nil {764 t.Errorf("Execute() failed with %v", err)765 }766 769- if rootcalled != true {767+ if !rootcalled {768 t.Errorf("Root Function was not called")769 }770 }771 772 func 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()775 776 buf := new(bytes.Buffer)777 // Testing flag with invalid input3 unmodified lines781 c.SetArgs(args)782 783 c.Execute()784 790- 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 }789 790 func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {796- fullSetupTest("echo invalid-sub")791+ fullSetupTest("echo", "invalid-sub")792 793 if te[0] != "invalid-sub" {794 t.Errorf("Subcommand didn't work...")795 }796 }797 798 func TestRootFlags(t *testing.T) {804- fullSetupTest("-i 17 -b")799+ fullSetupTest("-i", "17", "-b")800 806- if flagbr != true {801+ if !flagbr {802 t.Errorf("flag value should be true, %v given", flagbr)803 }804 805 if flagir != 17 {14 unmodified lines820 if strings.Contains(x.Output, cmdEcho.Use) {821 t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output)822 }823 829- x = fullSetupTest("echo --help")824+ x = fullSetupTest("echo", "--help")825 826 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 lines855 }856 }857 858 func TestNoNRunnableRootCommandNilInput(t *testing.T) {864- var args []string859 c := initialize()860 861 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{})867 868 c.Execute()869 870 if !strings.Contains(buf.String(), cmdRootNoRun.Long) {10 unmodified lines881 if strings.Contains(x.Output, "unknown flag: --help") {882 t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)883 }884 891- x = rootOnlySetupTest("echo --help")885+ x = rootOnlySetupTest("echo", "--help")886 887 checkResultOmits(t, x, "Available Commands:")888 checkResultOmits(t, x, "for more information about a command")889 9 unmodified lines899 if r.Output != s {900 t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)901 }902 909- 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 lines912 if r.Output != "" {913 t.Errorf("Unexpected response.\nExpecting to be: \n\"\"\n Got:\n %q\n", r.Output)914 }915 922- 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 lines959 }960 961 func 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 }967 974- // 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+ }972 978- //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- //}982-973 // 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 }978 979 // 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 }994-995- //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- }1000-1001- //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- }1006-1007- //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- }1012-1013- //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- }1018-984 }985 986 func TestRemoveCommand(t *testing.T) {987 versionUsed = 057 unmodified lines1045 checkResultContains(t, c, cmdDeprecated.Deprecated)1046 }1047 1048 func 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 }1056 1092- 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 }1064 1100- 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 lines1079 cmdPrint.AddCommand(cmdEchoSub)1080 // Now add cmdPrint to rootCmd1081 rootCmd.AddCommand(cmdPrint)1082 1118- rootCmd.SetArgs(strings.Split("print echosub lala", " "))1083+ rootCmd.SetArgs([]string{"print", "echosub", "lala"})1084 rootCmd.Execute()1085 1121- 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 linesmodified:command.go+15 added-24 removed
428 unmodified lines429 }430 c.mergePersistentFlags()431 432 commands := []string{}433- inQuote := false433 flags := c.Flags()434 435 Loop: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 }461-462- if strings.HasSuffix(s, "\"") && !strings.HasSuffix(s, "\\\"") {463- inQuote = false464- }456 }457 458 return commands459 }830 unmodified lines