Best Got code snippet using got.Run
command_test.go
Source:command_test.go
...9 "strings"10 "testing"11 "github.com/spf13/pflag"12)13func emptyRun(*Command, []string) {}14func executeCommand(root *Command, args ...string) (output string, err error) {15 _, output, err = executeCommandC(root, args...)16 return output, err17}18func executeCommandWithContext(ctx context.Context, root *Command, args ...string) (output string, err error) {19 buf := new(bytes.Buffer)20 root.SetOut(buf)21 root.SetErr(buf)22 root.SetArgs(args)23 err = root.ExecuteContext(ctx)24 return buf.String(), err25}26func executeCommandC(root *Command, args ...string) (c *Command, output string, err error) {27 buf := new(bytes.Buffer)28 root.SetOut(buf)29 root.SetErr(buf)30 root.SetArgs(args)31 c, err = root.ExecuteC()32 return c, buf.String(), err33}34func resetCommandLineFlagSet() {35 pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)36}37func checkStringContains(t *testing.T, got, expected string) {38 if !strings.Contains(got, expected) {39 t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got)40 }41}42func checkStringOmits(t *testing.T, got, expected string) {43 if strings.Contains(got, expected) {44 t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got)45 }46}47const onetwo = "one two"48func TestSingleCommand(t *testing.T) {49 var rootCmdArgs []string50 rootCmd := &Command{51 Use: "root",52 Args: ExactArgs(2),53 Run: func(_ *Command, args []string) { rootCmdArgs = args },54 }55 aCmd := &Command{Use: "a", Args: NoArgs, Run: emptyRun}56 bCmd := &Command{Use: "b", Args: NoArgs, Run: emptyRun}57 rootCmd.AddCommand(aCmd, bCmd)58 output, err := executeCommand(rootCmd, "one", "two")59 if output != "" {60 t.Errorf("Unexpected output: %v", output)61 }62 if err != nil {63 t.Errorf("Unexpected error: %v", err)64 }65 got := strings.Join(rootCmdArgs, " ")66 if got != onetwo {67 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)68 }69}70func TestChildCommand(t *testing.T) {71 var child1CmdArgs []string72 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}73 child1Cmd := &Command{74 Use: "child1",75 Args: ExactArgs(2),76 Run: func(_ *Command, args []string) { child1CmdArgs = args },77 }78 child2Cmd := &Command{Use: "child2", Args: NoArgs, Run: emptyRun}79 rootCmd.AddCommand(child1Cmd, child2Cmd)80 output, err := executeCommand(rootCmd, "child1", "one", "two")81 if output != "" {82 t.Errorf("Unexpected output: %v", output)83 }84 if err != nil {85 t.Errorf("Unexpected error: %v", err)86 }87 got := strings.Join(child1CmdArgs, " ")88 if got != onetwo {89 t.Errorf("child1CmdArgs expected: %q, got: %q", onetwo, got)90 }91}92func TestCallCommandWithoutSubcommands(t *testing.T) {93 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}94 _, err := executeCommand(rootCmd)95 if err != nil {96 t.Errorf("Calling command without subcommands should not have error: %v", err)97 }98}99func TestRootExecuteUnknownCommand(t *testing.T) {100 rootCmd := &Command{Use: "root", Run: emptyRun}101 rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})102 output, _ := executeCommand(rootCmd, "unknown")103 expected := "Error: unknown command \"unknown\" for \"root\"\nRun 'root --help' for usage.\n"104 if output != expected {105 t.Errorf("Expected:\n %q\nGot:\n %q\n", expected, output)106 }107}108func TestSubcommandExecuteC(t *testing.T) {109 rootCmd := &Command{Use: "root", Run: emptyRun}110 childCmd := &Command{Use: "child", Run: emptyRun}111 rootCmd.AddCommand(childCmd)112 c, output, err := executeCommandC(rootCmd, "child")113 if output != "" {114 t.Errorf("Unexpected output: %v", output)115 }116 if err != nil {117 t.Errorf("Unexpected error: %v", err)118 }119 if c.Name() != "child" {120 t.Errorf(`invalid command returned from ExecuteC: expected "child"', got: %q`, c.Name())121 }122}123func TestExecuteContext(t *testing.T) {124 ctx := context.TODO()125 ctxRun := func(cmd *Command, args []string) {126 if cmd.Context() != ctx {127 t.Errorf("Command %q must have context when called with ExecuteContext", cmd.Use)128 }129 }130 rootCmd := &Command{Use: "root", Run: ctxRun, PreRun: ctxRun}131 childCmd := &Command{Use: "child", Run: ctxRun, PreRun: ctxRun}132 granchildCmd := &Command{Use: "grandchild", Run: ctxRun, PreRun: ctxRun}133 childCmd.AddCommand(granchildCmd)134 rootCmd.AddCommand(childCmd)135 if _, err := executeCommandWithContext(ctx, rootCmd, ""); err != nil {136 t.Errorf("Root command must not fail: %+v", err)137 }138 if _, err := executeCommandWithContext(ctx, rootCmd, "child"); err != nil {139 t.Errorf("Subcommand must not fail: %+v", err)140 }141 if _, err := executeCommandWithContext(ctx, rootCmd, "child", "grandchild"); err != nil {142 t.Errorf("Command child must not fail: %+v", err)143 }144}145func TestExecute_NoContext(t *testing.T) {146 run := func(cmd *Command, args []string) {147 if cmd.Context() != context.Background() {148 t.Errorf("Command %s must have background context", cmd.Use)149 }150 }151 rootCmd := &Command{Use: "root", Run: run, PreRun: run}152 childCmd := &Command{Use: "child", Run: run, PreRun: run}153 granchildCmd := &Command{Use: "grandchild", Run: run, PreRun: run}154 childCmd.AddCommand(granchildCmd)155 rootCmd.AddCommand(childCmd)156 if _, err := executeCommand(rootCmd, ""); err != nil {157 t.Errorf("Root command must not fail: %+v", err)158 }159 if _, err := executeCommand(rootCmd, "child"); err != nil {160 t.Errorf("Subcommand must not fail: %+v", err)161 }162 if _, err := executeCommand(rootCmd, "child", "grandchild"); err != nil {163 t.Errorf("Command child must not fail: %+v", err)164 }165}166func TestRootUnknownCommandSilenced(t *testing.T) {167 rootCmd := &Command{Use: "root", Run: emptyRun}168 rootCmd.SilenceErrors = true169 rootCmd.SilenceUsage = true170 rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})171 output, _ := executeCommand(rootCmd, "unknown")172 if output != "" {173 t.Errorf("Expected blank output, because of silenced usage.\nGot:\n %q\n", output)174 }175}176func TestCommandAlias(t *testing.T) {177 var timesCmdArgs []string178 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}179 echoCmd := &Command{180 Use: "echo",181 Aliases: []string{"say", "tell"},182 Args: NoArgs,183 Run: emptyRun,184 }185 timesCmd := &Command{186 Use: "times",187 Args: ExactArgs(2),188 Run: func(_ *Command, args []string) { timesCmdArgs = args },189 }190 echoCmd.AddCommand(timesCmd)191 rootCmd.AddCommand(echoCmd)192 output, err := executeCommand(rootCmd, "tell", "times", "one", "two")193 if output != "" {194 t.Errorf("Unexpected output: %v", output)195 }196 if err != nil {197 t.Errorf("Unexpected error: %v", err)198 }199 got := strings.Join(timesCmdArgs, " ")200 if got != onetwo {201 t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got)202 }203}204func TestEnablePrefixMatching(t *testing.T) {205 EnablePrefixMatching = true206 var aCmdArgs []string207 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}208 aCmd := &Command{209 Use: "aCmd",210 Args: ExactArgs(2),211 Run: func(_ *Command, args []string) { aCmdArgs = args },212 }213 bCmd := &Command{Use: "bCmd", Args: NoArgs, Run: emptyRun}214 rootCmd.AddCommand(aCmd, bCmd)215 output, err := executeCommand(rootCmd, "a", "one", "two")216 if output != "" {217 t.Errorf("Unexpected output: %v", output)218 }219 if err != nil {220 t.Errorf("Unexpected error: %v", err)221 }222 got := strings.Join(aCmdArgs, " ")223 if got != onetwo {224 t.Errorf("aCmdArgs expected: %q, got: %q", onetwo, got)225 }226 EnablePrefixMatching = false227}228func TestAliasPrefixMatching(t *testing.T) {229 EnablePrefixMatching = true230 var timesCmdArgs []string231 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}232 echoCmd := &Command{233 Use: "echo",234 Aliases: []string{"say", "tell"},235 Args: NoArgs,236 Run: emptyRun,237 }238 timesCmd := &Command{239 Use: "times",240 Args: ExactArgs(2),241 Run: func(_ *Command, args []string) { timesCmdArgs = args },242 }243 echoCmd.AddCommand(timesCmd)244 rootCmd.AddCommand(echoCmd)245 output, err := executeCommand(rootCmd, "sa", "times", "one", "two")246 if output != "" {247 t.Errorf("Unexpected output: %v", output)248 }249 if err != nil {250 t.Errorf("Unexpected error: %v", err)251 }252 got := strings.Join(timesCmdArgs, " ")253 if got != onetwo {254 t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got)255 }256 EnablePrefixMatching = false257}258// TestChildSameName checks the correct behaviour of cobra in cases,259// when an application with name "foo" and with subcommand "foo"260// is executed with args "foo foo".261func TestChildSameName(t *testing.T) {262 var fooCmdArgs []string263 rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}264 fooCmd := &Command{265 Use: "foo",266 Args: ExactArgs(2),267 Run: func(_ *Command, args []string) { fooCmdArgs = args },268 }269 barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}270 rootCmd.AddCommand(fooCmd, barCmd)271 output, err := executeCommand(rootCmd, "foo", "one", "two")272 if output != "" {273 t.Errorf("Unexpected output: %v", output)274 }275 if err != nil {276 t.Errorf("Unexpected error: %v", err)277 }278 got := strings.Join(fooCmdArgs, " ")279 if got != onetwo {280 t.Errorf("fooCmdArgs expected: %v, got: %v", onetwo, got)281 }282}283// TestGrandChildSameName checks the correct behaviour of cobra in cases,284// when user has a root command and a grand child285// with the same name.286func TestGrandChildSameName(t *testing.T) {287 var fooCmdArgs []string288 rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}289 barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}290 fooCmd := &Command{291 Use: "foo",292 Args: ExactArgs(2),293 Run: func(_ *Command, args []string) { fooCmdArgs = args },294 }295 barCmd.AddCommand(fooCmd)296 rootCmd.AddCommand(barCmd)297 output, err := executeCommand(rootCmd, "bar", "foo", "one", "two")298 if output != "" {299 t.Errorf("Unexpected output: %v", output)300 }301 if err != nil {302 t.Errorf("Unexpected error: %v", err)303 }304 got := strings.Join(fooCmdArgs, " ")305 if got != onetwo {306 t.Errorf("fooCmdArgs expected: %v, got: %v", onetwo, got)307 }308}309func TestFlagLong(t *testing.T) {310 var cArgs []string311 c := &Command{312 Use: "c",313 Args: ArbitraryArgs,314 Run: func(_ *Command, args []string) { cArgs = args },315 }316 var intFlagValue int317 var stringFlagValue string318 c.Flags().IntVar(&intFlagValue, "intf", -1, "")319 c.Flags().StringVar(&stringFlagValue, "sf", "", "")320 output, err := executeCommand(c, "--intf=7", "--sf=abc", "one", "--", "two")321 if output != "" {322 t.Errorf("Unexpected output: %v", err)323 }324 if err != nil {325 t.Errorf("Unexpected error: %v", err)326 }327 if c.ArgsLenAtDash() != 1 {328 t.Errorf("Expected ArgsLenAtDash: %v but got %v", 1, c.ArgsLenAtDash())329 }330 if intFlagValue != 7 {331 t.Errorf("Expected intFlagValue: %v, got %v", 7, intFlagValue)332 }333 if stringFlagValue != "abc" {334 t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)335 }336 got := strings.Join(cArgs, " ")337 if got != onetwo {338 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)339 }340}341func TestFlagShort(t *testing.T) {342 var cArgs []string343 c := &Command{344 Use: "c",345 Args: ArbitraryArgs,346 Run: func(_ *Command, args []string) { cArgs = args },347 }348 var intFlagValue int349 var stringFlagValue string350 c.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")351 c.Flags().StringVarP(&stringFlagValue, "sf", "s", "", "")352 output, err := executeCommand(c, "-i", "7", "-sabc", "one", "two")353 if output != "" {354 t.Errorf("Unexpected output: %v", err)355 }356 if err != nil {357 t.Errorf("Unexpected error: %v", err)358 }359 if intFlagValue != 7 {360 t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)361 }362 if stringFlagValue != "abc" {363 t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)364 }365 got := strings.Join(cArgs, " ")366 if got != onetwo {367 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)368 }369}370func TestChildFlag(t *testing.T) {371 rootCmd := &Command{Use: "root", Run: emptyRun}372 childCmd := &Command{Use: "child", Run: emptyRun}373 rootCmd.AddCommand(childCmd)374 var intFlagValue int375 childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")376 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 }383 if intFlagValue != 7 {384 t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)385 }386}387func TestChildFlagWithParentLocalFlag(t *testing.T) {388 rootCmd := &Command{Use: "root", Run: emptyRun}389 childCmd := &Command{Use: "child", Run: emptyRun}390 rootCmd.AddCommand(childCmd)391 var intFlagValue int392 rootCmd.Flags().StringP("sf", "s", "", "")393 childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")394 _, err := executeCommand(rootCmd, "child", "-i7", "-sabc")395 if err == nil {396 t.Errorf("Invalid flag should generate error")397 }398 checkStringContains(t, err.Error(), "unknown shorthand")399 if intFlagValue != 7 {400 t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)401 }402}403func TestFlagInvalidInput(t *testing.T) {404 rootCmd := &Command{Use: "root", Run: emptyRun}405 rootCmd.Flags().IntP("intf", "i", -1, "")406 _, err := executeCommand(rootCmd, "-iabc")407 if err == nil {408 t.Errorf("Invalid flag value should generate error")409 }410 checkStringContains(t, err.Error(), "invalid syntax")411}412func TestFlagBeforeCommand(t *testing.T) {413 rootCmd := &Command{Use: "root", Run: emptyRun}414 childCmd := &Command{Use: "child", Run: emptyRun}415 rootCmd.AddCommand(childCmd)416 var flagValue int417 childCmd.Flags().IntVarP(&flagValue, "intf", "i", -1, "")418 // With short flag.419 _, err := executeCommand(rootCmd, "-i7", "child")420 if err != nil {421 t.Errorf("Unexpected error: %v", err)422 }423 if flagValue != 7 {424 t.Errorf("Expected flag value: %v, got %v", 7, flagValue)425 }426 // With long flag.427 _, err = executeCommand(rootCmd, "--intf=8", "child")428 if err != nil {429 t.Errorf("Unexpected error: %v", err)430 }431 if flagValue != 8 {432 t.Errorf("Expected flag value: %v, got %v", 9, flagValue)433 }434}435func TestStripFlags(t *testing.T) {436 tests := []struct {437 input []string438 output []string439 }{440 {441 []string{"foo", "bar"},442 []string{"foo", "bar"},443 },444 {445 []string{"foo", "--str", "-s"},446 []string{"foo"},447 },448 {449 []string{"-s", "foo", "--str", "bar"},450 []string{},451 },452 {453 []string{"-i10", "echo"},454 []string{"echo"},455 },456 {457 []string{"-i=10", "echo"},458 []string{"echo"},459 },460 {461 []string{"--int=100", "echo"},462 []string{"echo"},463 },464 {465 []string{"-ib", "echo", "-sfoo", "baz"},466 []string{"echo", "baz"},467 },468 {469 []string{"-i=baz", "bar", "-i", "foo", "blah"},470 []string{"bar", "blah"},471 },472 {473 []string{"--int=baz", "-sbar", "-i", "foo", "blah"},474 []string{"blah"},475 },476 {477 []string{"--bool", "bar", "-i", "foo", "blah"},478 []string{"bar", "blah"},479 },480 {481 []string{"-b", "bar", "-i", "foo", "blah"},482 []string{"bar", "blah"},483 },484 {485 []string{"--persist", "bar"},486 []string{"bar"},487 },488 {489 []string{"-p", "bar"},490 []string{"bar"},491 },492 }493 c := &Command{Use: "c", Run: emptyRun}494 c.PersistentFlags().BoolP("persist", "p", false, "")495 c.Flags().IntP("int", "i", -1, "")496 c.Flags().StringP("str", "s", "", "")497 c.Flags().BoolP("bool", "b", false, "")498 for i, test := range tests {499 got := stripFlags(test.input, c)500 if !reflect.DeepEqual(test.output, got) {501 t.Errorf("(%v) Expected: %v, got: %v", i, test.output, got)502 }503 }504}505func TestDisableFlagParsing(t *testing.T) {506 var cArgs []string507 c := &Command{508 Use: "c",509 DisableFlagParsing: true,510 Run: func(_ *Command, args []string) {511 cArgs = args512 },513 }514 args := []string{"cmd", "-v", "-race", "-file", "foo.go"}515 output, err := executeCommand(c, args...)516 if output != "" {517 t.Errorf("Unexpected output: %v", output)518 }519 if err != nil {520 t.Errorf("Unexpected error: %v", err)521 }522 if !reflect.DeepEqual(args, cArgs) {523 t.Errorf("Expected: %v, got: %v", args, cArgs)524 }525}526func TestPersistentFlagsOnSameCommand(t *testing.T) {527 var rootCmdArgs []string528 rootCmd := &Command{529 Use: "root",530 Args: ArbitraryArgs,531 Run: func(_ *Command, args []string) { rootCmdArgs = args },532 }533 var flagValue int534 rootCmd.PersistentFlags().IntVarP(&flagValue, "intf", "i", -1, "")535 output, err := executeCommand(rootCmd, "-i7", "one", "two")536 if output != "" {537 t.Errorf("Unexpected output: %v", output)538 }539 if err != nil {540 t.Errorf("Unexpected error: %v", err)541 }542 got := strings.Join(rootCmdArgs, " ")543 if got != onetwo {544 t.Errorf("rootCmdArgs expected: %q, got %q", onetwo, got)545 }546 if flagValue != 7 {547 t.Errorf("flagValue expected: %v, got %v", 7, flagValue)548 }549}550// TestEmptyInputs checks,551// if flags correctly parsed with blank strings in args.552func TestEmptyInputs(t *testing.T) {553 c := &Command{Use: "c", Run: emptyRun}554 var flagValue int555 c.Flags().IntVarP(&flagValue, "intf", "i", -1, "")556 output, err := executeCommand(c, "", "-i7", "")557 if output != "" {558 t.Errorf("Unexpected output: %v", output)559 }560 if err != nil {561 t.Errorf("Unexpected error: %v", err)562 }563 if flagValue != 7 {564 t.Errorf("flagValue expected: %v, got %v", 7, flagValue)565 }566}567func TestOverwrittenFlag(t *testing.T) {568 // TODO: This test fails, but should work.569 t.Skip()570 parent := &Command{Use: "parent", Run: emptyRun}571 child := &Command{Use: "child", Run: emptyRun}572 parent.PersistentFlags().Bool("boolf", false, "")573 parent.PersistentFlags().Int("intf", -1, "")574 child.Flags().String("strf", "", "")575 child.Flags().Int("intf", -1, "")576 parent.AddCommand(child)577 childInherited := child.InheritedFlags()578 childLocal := child.LocalFlags()579 if childLocal.Lookup("strf") == nil {580 t.Error(`LocalFlags expected to contain "strf", got "nil"`)581 }582 if childInherited.Lookup("boolf") == nil {583 t.Error(`InheritedFlags expected to contain "boolf", got "nil"`)584 }585 if childInherited.Lookup("intf") != nil {586 t.Errorf(`InheritedFlags should not contain overwritten flag "intf"`)587 }588 if childLocal.Lookup("intf") == nil {589 t.Error(`LocalFlags expected to contain "intf", got "nil"`)590 }591}592func TestPersistentFlagsOnChild(t *testing.T) {593 var childCmdArgs []string594 rootCmd := &Command{Use: "root", Run: emptyRun}595 childCmd := &Command{596 Use: "child",597 Args: ArbitraryArgs,598 Run: func(_ *Command, args []string) { childCmdArgs = args },599 }600 rootCmd.AddCommand(childCmd)601 var parentFlagValue int602 var childFlagValue int603 rootCmd.PersistentFlags().IntVarP(&parentFlagValue, "parentf", "p", -1, "")604 childCmd.Flags().IntVarP(&childFlagValue, "childf", "c", -1, "")605 output, err := executeCommand(rootCmd, "child", "-c7", "-p8", "one", "two")606 if output != "" {607 t.Errorf("Unexpected output: %v", output)608 }609 if err != nil {610 t.Errorf("Unexpected error: %v", err)611 }612 got := strings.Join(childCmdArgs, " ")613 if got != onetwo {614 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)615 }616 if parentFlagValue != 8 {617 t.Errorf("parentFlagValue expected: %v, got %v", 8, parentFlagValue)618 }619 if childFlagValue != 7 {620 t.Errorf("childFlagValue expected: %v, got %v", 7, childFlagValue)621 }622}623func TestRequiredFlags(t *testing.T) {624 c := &Command{Use: "c", Run: emptyRun}625 c.Flags().String("foo1", "", "")626 assertNoErr(t, c.MarkFlagRequired("foo1"))627 c.Flags().String("foo2", "", "")628 assertNoErr(t, c.MarkFlagRequired("foo2"))629 c.Flags().String("bar", "", "")630 expected := fmt.Sprintf("required flag(s) %q, %q not set", "foo1", "foo2")631 _, err := executeCommand(c)632 got := err.Error()633 if got != expected {634 t.Errorf("Expected error: %q, got: %q", expected, got)635 }636}637func TestPersistentRequiredFlags(t *testing.T) {638 parent := &Command{Use: "parent", Run: emptyRun}639 parent.PersistentFlags().String("foo1", "", "")640 assertNoErr(t, parent.MarkPersistentFlagRequired("foo1"))641 parent.PersistentFlags().String("foo2", "", "")642 assertNoErr(t, parent.MarkPersistentFlagRequired("foo2"))643 parent.Flags().String("foo3", "", "")644 child := &Command{Use: "child", Run: emptyRun}645 child.Flags().String("bar1", "", "")646 assertNoErr(t, child.MarkFlagRequired("bar1"))647 child.Flags().String("bar2", "", "")648 assertNoErr(t, child.MarkFlagRequired("bar2"))649 child.Flags().String("bar3", "", "")650 parent.AddCommand(child)651 expected := fmt.Sprintf("required flag(s) %q, %q, %q, %q not set", "bar1", "bar2", "foo1", "foo2")652 _, err := executeCommand(parent, "child")653 if err.Error() != expected {654 t.Errorf("Expected %q, got %q", expected, err.Error())655 }656}657func TestPersistentRequiredFlagsWithDisableFlagParsing(t *testing.T) {658 // Make sure a required persistent flag does not break659 // commands that disable flag parsing660 parent := &Command{Use: "parent", Run: emptyRun}661 parent.PersistentFlags().Bool("foo", false, "")662 flag := parent.PersistentFlags().Lookup("foo")663 assertNoErr(t, parent.MarkPersistentFlagRequired("foo"))664 child := &Command{Use: "child", Run: emptyRun}665 child.DisableFlagParsing = true666 parent.AddCommand(child)667 if _, err := executeCommand(parent, "--foo", "child"); err != nil {668 t.Errorf("Unexpected error: %v", err)669 }670 // Reset the flag or else it will remember the state from the previous command671 flag.Changed = false672 if _, err := executeCommand(parent, "child", "--foo"); err != nil {673 t.Errorf("Unexpected error: %v", err)674 }675 // Reset the flag or else it will remember the state from the previous command676 flag.Changed = false677 if _, err := executeCommand(parent, "child"); err != nil {678 t.Errorf("Unexpected error: %v", err)679 }680}681func TestInitHelpFlagMergesFlags(t *testing.T) {682 usage := "custom flag"683 rootCmd := &Command{Use: "root"}684 rootCmd.PersistentFlags().Bool("help", false, "custom flag")685 childCmd := &Command{Use: "child"}686 rootCmd.AddCommand(childCmd)687 childCmd.InitDefaultHelpFlag()688 got := childCmd.Flags().Lookup("help").Usage689 if got != usage {690 t.Errorf("Expected the help flag from the root command with usage: %v\nGot the default with usage: %v", usage, got)691 }692}693func TestHelpCommandExecuted(t *testing.T) {694 rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}695 rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})696 output, err := executeCommand(rootCmd, "help")697 if err != nil {698 t.Errorf("Unexpected error: %v", err)699 }700 checkStringContains(t, output, rootCmd.Long)701}702func TestHelpCommandExecutedOnChild(t *testing.T) {703 rootCmd := &Command{Use: "root", Run: emptyRun}704 childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}705 rootCmd.AddCommand(childCmd)706 output, err := executeCommand(rootCmd, "help", "child")707 if err != nil {708 t.Errorf("Unexpected error: %v", err)709 }710 checkStringContains(t, output, childCmd.Long)711}712func TestSetHelpCommand(t *testing.T) {713 c := &Command{Use: "c", Run: emptyRun}714 c.AddCommand(&Command{Use: "empty", Run: emptyRun})715 expected := "WORKS"716 c.SetHelpCommand(&Command{717 Use: "help [command]",718 Short: "Help about any command",719 Long: `Help provides help for any command in the application.720 Simply type ` + c.Name() + ` help [path to command] for full details.`,721 Run: func(c *Command, _ []string) { c.Print(expected) },722 })723 got, err := executeCommand(c, "help")724 if err != nil {725 t.Errorf("Unexpected error: %v", err)726 }727 if got != expected {728 t.Errorf("Expected to contain %q, got %q", expected, got)729 }730}731func TestHelpFlagExecuted(t *testing.T) {732 rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}733 output, err := executeCommand(rootCmd, "--help")734 if err != nil {735 t.Errorf("Unexpected error: %v", err)736 }737 checkStringContains(t, output, rootCmd.Long)738}739func TestHelpFlagExecutedOnChild(t *testing.T) {740 rootCmd := &Command{Use: "root", Run: emptyRun}741 childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}742 rootCmd.AddCommand(childCmd)743 output, err := executeCommand(rootCmd, "child", "--help")744 if err != nil {745 t.Errorf("Unexpected error: %v", err)746 }747 checkStringContains(t, output, childCmd.Long)748}749// TestHelpFlagInHelp checks,750// if '--help' flag is shown in help for child (executing `parent help child`),751// that has no other flags.752// Related to https://github.com/spf13/cobra/issues/302.753func TestHelpFlagInHelp(t *testing.T) {754 parentCmd := &Command{Use: "parent", Run: func(*Command, []string) {}}755 childCmd := &Command{Use: "child", Run: func(*Command, []string) {}}756 parentCmd.AddCommand(childCmd)757 output, err := executeCommand(parentCmd, "help", "child")758 if err != nil {759 t.Errorf("Unexpected error: %v", err)760 }761 checkStringContains(t, output, "[flags]")762}763func TestFlagsInUsage(t *testing.T) {764 rootCmd := &Command{Use: "root", Args: NoArgs, Run: func(*Command, []string) {}}765 output, err := executeCommand(rootCmd, "--help")766 if err != nil {767 t.Errorf("Unexpected error: %v", err)768 }769 checkStringContains(t, output, "[flags]")770}771func TestHelpExecutedOnNonRunnableChild(t *testing.T) {772 rootCmd := &Command{Use: "root", Run: emptyRun}773 childCmd := &Command{Use: "child", Long: "Long description"}774 rootCmd.AddCommand(childCmd)775 output, err := executeCommand(rootCmd, "child")776 if err != nil {777 t.Errorf("Unexpected error: %v", err)778 }779 checkStringContains(t, output, childCmd.Long)780}781func TestVersionFlagExecuted(t *testing.T) {782 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}783 output, err := executeCommand(rootCmd, "--version", "arg1")784 if err != nil {785 t.Errorf("Unexpected error: %v", err)786 }787 checkStringContains(t, output, "root version 1.0.0")788}789func TestVersionFlagExecutedWithNoName(t *testing.T) {790 rootCmd := &Command{Version: "1.0.0", Run: emptyRun}791 output, err := executeCommand(rootCmd, "--version", "arg1")792 if err != nil {793 t.Errorf("Unexpected error: %v", err)794 }795 checkStringContains(t, output, "version 1.0.0")796}797func TestShortAndLongVersionFlagInHelp(t *testing.T) {798 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}799 output, err := executeCommand(rootCmd, "--help")800 if err != nil {801 t.Errorf("Unexpected error: %v", err)802 }803 checkStringContains(t, output, "-v, --version")804}805func TestLongVersionFlagOnlyInHelpWhenShortPredefined(t *testing.T) {806 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}807 rootCmd.Flags().StringP("foo", "v", "", "not a version flag")808 output, err := executeCommand(rootCmd, "--help")809 if err != nil {810 t.Errorf("Unexpected error: %v", err)811 }812 checkStringOmits(t, output, "-v, --version")813 checkStringContains(t, output, "--version")814}815func TestShorthandVersionFlagExecuted(t *testing.T) {816 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}817 output, err := executeCommand(rootCmd, "-v", "arg1")818 if err != nil {819 t.Errorf("Unexpected error: %v", err)820 }821 checkStringContains(t, output, "root version 1.0.0")822}823func TestVersionTemplate(t *testing.T) {824 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}825 rootCmd.SetVersionTemplate(`customized version: {{.Version}}`)826 output, err := executeCommand(rootCmd, "--version", "arg1")827 if err != nil {828 t.Errorf("Unexpected error: %v", err)829 }830 checkStringContains(t, output, "customized version: 1.0.0")831}832func TestShorthandVersionTemplate(t *testing.T) {833 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}834 rootCmd.SetVersionTemplate(`customized version: {{.Version}}`)835 output, err := executeCommand(rootCmd, "-v", "arg1")836 if err != nil {837 t.Errorf("Unexpected error: %v", err)838 }839 checkStringContains(t, output, "customized version: 1.0.0")840}841func TestVersionFlagExecutedOnSubcommand(t *testing.T) {842 rootCmd := &Command{Use: "root", Version: "1.0.0"}843 rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})844 output, err := executeCommand(rootCmd, "--version", "sub")845 if err != nil {846 t.Errorf("Unexpected error: %v", err)847 }848 checkStringContains(t, output, "root version 1.0.0")849}850func TestShorthandVersionFlagExecutedOnSubcommand(t *testing.T) {851 rootCmd := &Command{Use: "root", Version: "1.0.0"}852 rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})853 output, err := executeCommand(rootCmd, "-v", "sub")854 if err != nil {855 t.Errorf("Unexpected error: %v", err)856 }857 checkStringContains(t, output, "root version 1.0.0")858}859func TestVersionFlagOnlyAddedToRoot(t *testing.T) {860 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}861 rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})862 _, err := executeCommand(rootCmd, "sub", "--version")863 if err == nil {864 t.Errorf("Expected error")865 }866 checkStringContains(t, err.Error(), "unknown flag: --version")867}868func TestShortVersionFlagOnlyAddedToRoot(t *testing.T) {869 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}870 rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})871 _, err := executeCommand(rootCmd, "sub", "-v")872 if err == nil {873 t.Errorf("Expected error")874 }875 checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v")876}877func TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {878 rootCmd := &Command{Use: "root", Run: emptyRun}879 _, err := executeCommand(rootCmd, "--version")880 if err == nil {881 t.Errorf("Expected error")882 }883 checkStringContains(t, err.Error(), "unknown flag: --version")884}885func TestShorthandVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {886 rootCmd := &Command{Use: "root", Run: emptyRun}887 _, err := executeCommand(rootCmd, "-v")888 if err == nil {889 t.Errorf("Expected error")890 }891 checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v")892}893func TestShorthandVersionFlagOnlyAddedIfShorthandNotDefined(t *testing.T) {894 rootCmd := &Command{Use: "root", Run: emptyRun, Version: "1.2.3"}895 rootCmd.Flags().StringP("notversion", "v", "", "not a version flag")896 _, err := executeCommand(rootCmd, "-v")897 if err == nil {898 t.Errorf("Expected error")899 }900 check(t, rootCmd.Flags().ShorthandLookup("v").Name, "notversion")901 checkStringContains(t, err.Error(), "flag needs an argument: 'v' in -v")902}903func TestShorthandVersionFlagOnlyAddedIfVersionNotDefined(t *testing.T) {904 rootCmd := &Command{Use: "root", Run: emptyRun, Version: "1.2.3"}905 rootCmd.Flags().Bool("version", false, "a different kind of version flag")906 _, err := executeCommand(rootCmd, "-v")907 if err == nil {908 t.Errorf("Expected error")909 }910 checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v")911}912func TestUsageIsNotPrintedTwice(t *testing.T) {913 var cmd = &Command{Use: "root"}914 var sub = &Command{Use: "sub"}915 cmd.AddCommand(sub)916 output, _ := executeCommand(cmd, "")917 if strings.Count(output, "Usage:") != 1 {918 t.Error("Usage output is not printed exactly once")919 }920}921func TestVisitParents(t *testing.T) {922 c := &Command{Use: "app"}923 sub := &Command{Use: "sub"}924 dsub := &Command{Use: "dsub"}925 sub.AddCommand(dsub)926 c.AddCommand(sub)927 total := 0928 add := func(x *Command) {929 total++930 }931 sub.VisitParents(add)932 if total != 1 {933 t.Errorf("Should have visited 1 parent but visited %d", total)934 }935 total = 0936 dsub.VisitParents(add)937 if total != 2 {938 t.Errorf("Should have visited 2 parents but visited %d", total)939 }940 total = 0941 c.VisitParents(add)942 if total != 0 {943 t.Errorf("Should have visited no parents but visited %d", total)944 }945}946func TestSuggestions(t *testing.T) {947 rootCmd := &Command{Use: "root", Run: emptyRun}948 timesCmd := &Command{949 Use: "times",950 SuggestFor: []string{"counts"},951 Run: emptyRun,952 }953 rootCmd.AddCommand(timesCmd)954 templateWithSuggestions := "Error: unknown command \"%s\" for \"root\"\n\nDid you mean this?\n\t%s\n\nRun 'root --help' for usage.\n"955 templateWithoutSuggestions := "Error: unknown command \"%s\" for \"root\"\nRun 'root --help' for usage.\n"956 tests := map[string]string{957 "time": "times",958 "tiems": "times",959 "tims": "times",960 "timeS": "times",961 "rimes": "times",962 "ti": "times",963 "t": "times",964 "timely": "times",965 "ri": "",966 "timezone": "",967 "foo": "",968 "counts": "times",969 }970 for typo, suggestion := range tests {971 for _, suggestionsDisabled := range []bool{true, false} {972 rootCmd.DisableSuggestions = suggestionsDisabled973 var expected string974 output, _ := executeCommand(rootCmd, typo)975 if suggestion == "" || suggestionsDisabled {976 expected = fmt.Sprintf(templateWithoutSuggestions, typo)977 } else {978 expected = fmt.Sprintf(templateWithSuggestions, typo, suggestion)979 }980 if output != expected {981 t.Errorf("Unexpected response.\nExpected:\n %q\nGot:\n %q\n", expected, output)982 }983 }984 }985}986func TestRemoveCommand(t *testing.T) {987 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}988 childCmd := &Command{Use: "child", Run: emptyRun}989 rootCmd.AddCommand(childCmd)990 rootCmd.RemoveCommand(childCmd)991 _, err := executeCommand(rootCmd, "child")992 if err == nil {993 t.Error("Expected error on calling removed command. Got nil.")994 }995}996func TestReplaceCommandWithRemove(t *testing.T) {997 childUsed := 0998 rootCmd := &Command{Use: "root", Run: emptyRun}999 child1Cmd := &Command{1000 Use: "child",1001 Run: func(*Command, []string) { childUsed = 1 },1002 }1003 child2Cmd := &Command{1004 Use: "child",1005 Run: func(*Command, []string) { childUsed = 2 },1006 }1007 rootCmd.AddCommand(child1Cmd)1008 rootCmd.RemoveCommand(child1Cmd)1009 rootCmd.AddCommand(child2Cmd)1010 output, err := executeCommand(rootCmd, "child")1011 if output != "" {1012 t.Errorf("Unexpected output: %v", output)1013 }1014 if err != nil {1015 t.Errorf("Unexpected error: %v", err)1016 }1017 if childUsed == 1 {1018 t.Error("Removed command shouldn't be called")1019 }1020 if childUsed != 2 {1021 t.Error("Replacing command should have been called but didn't")1022 }1023}1024func TestDeprecatedCommand(t *testing.T) {1025 rootCmd := &Command{Use: "root", Run: emptyRun}1026 deprecatedCmd := &Command{1027 Use: "deprecated",1028 Deprecated: "This command is deprecated",1029 Run: emptyRun,1030 }1031 rootCmd.AddCommand(deprecatedCmd)1032 output, err := executeCommand(rootCmd, "deprecated")1033 if err != nil {1034 t.Errorf("Unexpected error: %v", err)1035 }1036 checkStringContains(t, output, deprecatedCmd.Deprecated)1037}1038func TestHooks(t *testing.T) {1039 var (1040 persPreArgs string1041 preArgs string1042 runArgs string1043 postArgs string1044 persPostArgs string1045 )1046 c := &Command{1047 Use: "c",1048 PersistentPreRun: func(_ *Command, args []string) {1049 persPreArgs = strings.Join(args, " ")1050 },1051 PreRun: func(_ *Command, args []string) {1052 preArgs = strings.Join(args, " ")1053 },1054 Run: func(_ *Command, args []string) {1055 runArgs = strings.Join(args, " ")1056 },1057 PostRun: func(_ *Command, args []string) {1058 postArgs = strings.Join(args, " ")1059 },1060 PersistentPostRun: func(_ *Command, args []string) {1061 persPostArgs = strings.Join(args, " ")1062 },1063 }1064 output, err := executeCommand(c, "one", "two")1065 if output != "" {1066 t.Errorf("Unexpected output: %v", output)1067 }1068 if err != nil {1069 t.Errorf("Unexpected error: %v", err)1070 }1071 for _, v := range []struct {1072 name string1073 got string1074 }{1075 {"persPreArgs", persPreArgs},1076 {"preArgs", preArgs},1077 {"runArgs", runArgs},1078 {"postArgs", postArgs},1079 {"persPostArgs", persPostArgs},1080 } {1081 if v.got != onetwo {1082 t.Errorf("Expected %s %q, got %q", v.name, onetwo, v.got)1083 }1084 }1085}1086func TestPersistentHooks(t *testing.T) {1087 var (1088 parentPersPreArgs string1089 parentPreArgs string1090 parentRunArgs string1091 parentPostArgs string1092 parentPersPostArgs string1093 )1094 var (1095 childPersPreArgs string1096 childPreArgs string1097 childRunArgs string1098 childPostArgs string1099 childPersPostArgs string1100 )1101 parentCmd := &Command{1102 Use: "parent",1103 PersistentPreRun: func(_ *Command, args []string) {1104 parentPersPreArgs = strings.Join(args, " ")1105 },1106 PreRun: func(_ *Command, args []string) {1107 parentPreArgs = strings.Join(args, " ")1108 },1109 Run: func(_ *Command, args []string) {1110 parentRunArgs = strings.Join(args, " ")1111 },1112 PostRun: func(_ *Command, args []string) {1113 parentPostArgs = strings.Join(args, " ")1114 },1115 PersistentPostRun: func(_ *Command, args []string) {1116 parentPersPostArgs = strings.Join(args, " ")1117 },1118 }1119 childCmd := &Command{1120 Use: "child",1121 PersistentPreRun: func(_ *Command, args []string) {1122 childPersPreArgs = strings.Join(args, " ")1123 },1124 PreRun: func(_ *Command, args []string) {1125 childPreArgs = strings.Join(args, " ")1126 },1127 Run: func(_ *Command, args []string) {1128 childRunArgs = strings.Join(args, " ")1129 },1130 PostRun: func(_ *Command, args []string) {1131 childPostArgs = strings.Join(args, " ")1132 },1133 PersistentPostRun: func(_ *Command, args []string) {1134 childPersPostArgs = strings.Join(args, " ")1135 },1136 }1137 parentCmd.AddCommand(childCmd)1138 output, err := executeCommand(parentCmd, "child", "one", "two")1139 if output != "" {1140 t.Errorf("Unexpected output: %v", output)1141 }1142 if err != nil {1143 t.Errorf("Unexpected error: %v", err)1144 }1145 for _, v := range []struct {1146 name string1147 got string1148 }{1149 // TODO: currently PersistenPreRun* defined in parent does not1150 // run if the matchin child subcommand has PersistenPreRun.1151 // If the behavior changes (https://github.com/spf13/cobra/issues/252)1152 // this test must be fixed.1153 {"parentPersPreArgs", parentPersPreArgs},1154 {"parentPreArgs", parentPreArgs},1155 {"parentRunArgs", parentRunArgs},1156 {"parentPostArgs", parentPostArgs},1157 // TODO: currently PersistenPostRun* defined in parent does not1158 // run if the matchin child subcommand has PersistenPostRun.1159 // If the behavior changes (https://github.com/spf13/cobra/issues/252)1160 // this test must be fixed.1161 {"parentPersPostArgs", parentPersPostArgs},1162 } {1163 if v.got != "" {1164 t.Errorf("Expected blank %s, got %q", v.name, v.got)1165 }1166 }1167 for _, v := range []struct {1168 name string1169 got string1170 }{1171 {"childPersPreArgs", childPersPreArgs},1172 {"childPreArgs", childPreArgs},1173 {"childRunArgs", childRunArgs},1174 {"childPostArgs", childPostArgs},1175 {"childPersPostArgs", childPersPostArgs},1176 } {1177 if v.got != onetwo {1178 t.Errorf("Expected %s %q, got %q", v.name, onetwo, v.got)1179 }1180 }1181}1182// Related to https://github.com/spf13/cobra/issues/521.1183func TestGlobalNormFuncPropagation(t *testing.T) {1184 normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1185 return pflag.NormalizedName(name)1186 }1187 rootCmd := &Command{Use: "root", Run: emptyRun}1188 childCmd := &Command{Use: "child", Run: emptyRun}1189 rootCmd.AddCommand(childCmd)1190 rootCmd.SetGlobalNormalizationFunc(normFunc)1191 if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {1192 t.Error("rootCmd seems to have a wrong normalization function")1193 }1194 if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(childCmd.GlobalNormalizationFunc()).Pointer() {1195 t.Error("childCmd should have had the normalization function of rootCmd")1196 }1197}1198// Related to https://github.com/spf13/cobra/issues/521.1199func TestNormPassedOnLocal(t *testing.T) {1200 toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1201 return pflag.NormalizedName(strings.ToUpper(name))1202 }1203 c := &Command{}1204 c.Flags().Bool("flagname", true, "this is a dummy flag")1205 c.SetGlobalNormalizationFunc(toUpper)1206 if c.LocalFlags().Lookup("flagname") != c.LocalFlags().Lookup("FLAGNAME") {1207 t.Error("Normalization function should be passed on to Local flag set")1208 }1209}1210// Related to https://github.com/spf13/cobra/issues/521.1211func TestNormPassedOnInherited(t *testing.T) {1212 toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1213 return pflag.NormalizedName(strings.ToUpper(name))1214 }1215 c := &Command{}1216 c.SetGlobalNormalizationFunc(toUpper)1217 child1 := &Command{}1218 c.AddCommand(child1)1219 c.PersistentFlags().Bool("flagname", true, "")1220 child2 := &Command{}1221 c.AddCommand(child2)1222 inherited := child1.InheritedFlags()1223 if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") {1224 t.Error("Normalization function should be passed on to inherited flag set in command added before flag")1225 }1226 inherited = child2.InheritedFlags()1227 if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") {1228 t.Error("Normalization function should be passed on to inherited flag set in command added after flag")1229 }1230}1231// Related to https://github.com/spf13/cobra/issues/521.1232func TestConsistentNormalizedName(t *testing.T) {1233 toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1234 return pflag.NormalizedName(strings.ToUpper(name))1235 }1236 n := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1237 return pflag.NormalizedName(name)1238 }1239 c := &Command{}1240 c.Flags().Bool("flagname", true, "")1241 c.SetGlobalNormalizationFunc(toUpper)1242 c.SetGlobalNormalizationFunc(n)1243 if c.LocalFlags().Lookup("flagname") == c.LocalFlags().Lookup("FLAGNAME") {1244 t.Error("Normalizing flag names should not result in duplicate flags")1245 }1246}1247func TestFlagOnPflagCommandLine(t *testing.T) {1248 flagName := "flagOnCommandLine"1249 pflag.String(flagName, "", "about my flag")1250 c := &Command{Use: "c", Run: emptyRun}1251 c.AddCommand(&Command{Use: "child", Run: emptyRun})1252 output, _ := executeCommand(c, "--help")1253 checkStringContains(t, output, flagName)1254 resetCommandLineFlagSet()1255}1256// TestHiddenCommandExecutes checks,1257// if hidden commands run as intended.1258func TestHiddenCommandExecutes(t *testing.T) {1259 executed := false1260 c := &Command{1261 Use: "c",1262 Hidden: true,1263 Run: func(*Command, []string) { executed = true },1264 }1265 output, err := executeCommand(c)1266 if output != "" {1267 t.Errorf("Unexpected output: %v", output)1268 }1269 if err != nil {1270 t.Errorf("Unexpected error: %v", err)1271 }1272 if !executed {1273 t.Error("Hidden command should have been executed")1274 }1275}1276// test to ensure hidden commands do not show up in usage/help text1277func TestHiddenCommandIsHidden(t *testing.T) {1278 c := &Command{Use: "c", Hidden: true, Run: emptyRun}1279 if c.IsAvailableCommand() {1280 t.Errorf("Hidden command should be unavailable")1281 }1282}1283func TestCommandsAreSorted(t *testing.T) {1284 EnableCommandSorting = true1285 originalNames := []string{"middle", "zlast", "afirst"}1286 expectedNames := []string{"afirst", "middle", "zlast"}1287 var rootCmd = &Command{Use: "root"}1288 for _, name := range originalNames {1289 rootCmd.AddCommand(&Command{Use: name})1290 }1291 for i, c := range rootCmd.Commands() {1292 got := c.Name()1293 if expectedNames[i] != got {1294 t.Errorf("Expected: %s, got: %s", expectedNames[i], got)1295 }1296 }1297 EnableCommandSorting = true1298}1299func TestEnableCommandSortingIsDisabled(t *testing.T) {1300 EnableCommandSorting = false1301 originalNames := []string{"middle", "zlast", "afirst"}1302 var rootCmd = &Command{Use: "root"}1303 for _, name := range originalNames {1304 rootCmd.AddCommand(&Command{Use: name})1305 }1306 for i, c := range rootCmd.Commands() {1307 got := c.Name()1308 if originalNames[i] != got {1309 t.Errorf("expected: %s, got: %s", originalNames[i], got)1310 }1311 }1312 EnableCommandSorting = true1313}1314func TestSetOutput(t *testing.T) {1315 c := &Command{}1316 c.SetOutput(nil)1317 if out := c.OutOrStdout(); out != os.Stdout {1318 t.Errorf("Expected setting output to nil to revert back to stdout")1319 }1320}1321func TestSetOut(t *testing.T) {1322 c := &Command{}1323 c.SetOut(nil)1324 if out := c.OutOrStdout(); out != os.Stdout {1325 t.Errorf("Expected setting output to nil to revert back to stdout")1326 }1327}1328func TestSetErr(t *testing.T) {1329 c := &Command{}1330 c.SetErr(nil)1331 if out := c.ErrOrStderr(); out != os.Stderr {1332 t.Errorf("Expected setting error to nil to revert back to stderr")1333 }1334}1335func TestSetIn(t *testing.T) {1336 c := &Command{}1337 c.SetIn(nil)1338 if out := c.InOrStdin(); out != os.Stdin {1339 t.Errorf("Expected setting input to nil to revert back to stdin")1340 }1341}1342func TestUsageStringRedirected(t *testing.T) {1343 c := &Command{}1344 c.usageFunc = func(cmd *Command) error {1345 cmd.Print("[stdout1]")1346 cmd.PrintErr("[stderr2]")1347 cmd.Print("[stdout3]")1348 return nil1349 }1350 expected := "[stdout1][stderr2][stdout3]"1351 if got := c.UsageString(); got != expected {1352 t.Errorf("Expected usage string to consider both stdout and stderr")1353 }1354}1355func TestCommandPrintRedirection(t *testing.T) {1356 errBuff, outBuff := bytes.NewBuffer(nil), bytes.NewBuffer(nil)1357 root := &Command{1358 Run: func(cmd *Command, args []string) {1359 cmd.PrintErr("PrintErr")1360 cmd.PrintErrln("PrintErr", "line")1361 cmd.PrintErrf("PrintEr%s", "r")1362 cmd.Print("Print")1363 cmd.Println("Print", "line")1364 cmd.Printf("Prin%s", "t")1365 },1366 }1367 root.SetErr(errBuff)1368 root.SetOut(outBuff)1369 if err := root.Execute(); err != nil {1370 t.Error(err)1371 }1372 gotErrBytes, err := ioutil.ReadAll(errBuff)1373 if err != nil {1374 t.Error(err)1375 }1376 gotOutBytes, err := ioutil.ReadAll(outBuff)1377 if err != nil {1378 t.Error(err)1379 }1380 if wantErr := []byte("PrintErrPrintErr line\nPrintErr"); !bytes.Equal(gotErrBytes, wantErr) {1381 t.Errorf("got: '%s' want: '%s'", gotErrBytes, wantErr)1382 }1383 if wantOut := []byte("PrintPrint line\nPrint"); !bytes.Equal(gotOutBytes, wantOut) {1384 t.Errorf("got: '%s' want: '%s'", gotOutBytes, wantOut)1385 }1386}1387func TestFlagErrorFunc(t *testing.T) {1388 c := &Command{Use: "c", Run: emptyRun}1389 expectedFmt := "This is expected: %v"1390 c.SetFlagErrorFunc(func(_ *Command, err error) error {1391 return fmt.Errorf(expectedFmt, err)1392 })1393 _, err := executeCommand(c, "--unknown-flag")1394 got := err.Error()1395 expected := fmt.Sprintf(expectedFmt, "unknown flag: --unknown-flag")1396 if got != expected {1397 t.Errorf("Expected %v, got %v", expected, got)1398 }1399}1400// TestSortedFlags checks,1401// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.1402// Related to https://github.com/spf13/cobra/issues/404.1403func TestSortedFlags(t *testing.T) {1404 c := &Command{}1405 c.Flags().SortFlags = false1406 names := []string{"C", "B", "A", "D"}1407 for _, name := range names {1408 c.Flags().Bool(name, false, "")1409 }1410 i := 01411 c.LocalFlags().VisitAll(func(f *pflag.Flag) {1412 if i == len(names) {1413 return1414 }1415 if stringInSlice(f.Name, names) {1416 if names[i] != f.Name {1417 t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name)1418 }1419 i++1420 }1421 })1422}1423// TestMergeCommandLineToFlags checks,1424// if pflag.CommandLine is correctly merged to c.Flags() after first call1425// of c.mergePersistentFlags.1426// Related to https://github.com/spf13/cobra/issues/443.1427func TestMergeCommandLineToFlags(t *testing.T) {1428 pflag.Bool("boolflag", false, "")1429 c := &Command{Use: "c", Run: emptyRun}1430 c.mergePersistentFlags()1431 if c.Flags().Lookup("boolflag") == nil {1432 t.Fatal("Expecting to have flag from CommandLine in c.Flags()")1433 }1434 resetCommandLineFlagSet()1435}1436// TestUseDeprecatedFlags checks,1437// if cobra.Execute() prints a message, if a deprecated flag is used.1438// Related to https://github.com/spf13/cobra/issues/463.1439func TestUseDeprecatedFlags(t *testing.T) {1440 c := &Command{Use: "c", Run: emptyRun}1441 c.Flags().BoolP("deprecated", "d", false, "deprecated flag")1442 assertNoErr(t, c.Flags().MarkDeprecated("deprecated", "This flag is deprecated"))1443 output, err := executeCommand(c, "c", "-d")1444 if err != nil {1445 t.Error("Unexpected error:", err)1446 }1447 checkStringContains(t, output, "This flag is deprecated")1448}1449func TestTraverseWithParentFlags(t *testing.T) {1450 rootCmd := &Command{Use: "root", TraverseChildren: true}1451 rootCmd.Flags().String("str", "", "")1452 rootCmd.Flags().BoolP("bool", "b", false, "")1453 childCmd := &Command{Use: "child"}1454 childCmd.Flags().Int("int", -1, "")1455 rootCmd.AddCommand(childCmd)1456 c, args, err := rootCmd.Traverse([]string{"-b", "--str", "ok", "child", "--int"})1457 if err != nil {1458 t.Errorf("Unexpected error: %v", err)1459 }1460 if len(args) != 1 && args[0] != "--add" {1461 t.Errorf("Wrong args: %v", args)1462 }1463 if c.Name() != childCmd.Name() {1464 t.Errorf("Expected command: %q, got: %q", childCmd.Name(), c.Name())1465 }1466}1467func TestTraverseNoParentFlags(t *testing.T) {1468 rootCmd := &Command{Use: "root", TraverseChildren: true}1469 rootCmd.Flags().String("foo", "", "foo things")1470 childCmd := &Command{Use: "child"}1471 childCmd.Flags().String("str", "", "")1472 rootCmd.AddCommand(childCmd)1473 c, args, err := rootCmd.Traverse([]string{"child"})1474 if err != nil {1475 t.Errorf("Unexpected error: %v", err)1476 }1477 if len(args) != 0 {1478 t.Errorf("Wrong args %v", args)1479 }1480 if c.Name() != childCmd.Name() {1481 t.Errorf("Expected command: %q, got: %q", childCmd.Name(), c.Name())1482 }1483}1484func TestTraverseWithBadParentFlags(t *testing.T) {1485 rootCmd := &Command{Use: "root", TraverseChildren: true}1486 childCmd := &Command{Use: "child"}1487 childCmd.Flags().String("str", "", "")1488 rootCmd.AddCommand(childCmd)1489 expected := "unknown flag: --str"1490 c, _, err := rootCmd.Traverse([]string{"--str", "ok", "child"})1491 if err == nil || !strings.Contains(err.Error(), expected) {1492 t.Errorf("Expected error, %q, got %q", expected, err)1493 }1494 if c != nil {1495 t.Errorf("Expected nil command")1496 }1497}1498func TestTraverseWithBadChildFlag(t *testing.T) {1499 rootCmd := &Command{Use: "root", TraverseChildren: true}1500 rootCmd.Flags().String("str", "", "")1501 childCmd := &Command{Use: "child"}1502 rootCmd.AddCommand(childCmd)1503 // Expect no error because the last commands args shouldn't be parsed in1504 // Traverse.1505 c, args, err := rootCmd.Traverse([]string{"child", "--str"})1506 if err != nil {1507 t.Errorf("Unexpected error: %v", err)1508 }1509 if len(args) != 1 && args[0] != "--str" {1510 t.Errorf("Wrong args: %v", args)1511 }1512 if c.Name() != childCmd.Name() {1513 t.Errorf("Expected command %q, got: %q", childCmd.Name(), c.Name())1514 }1515}1516func TestTraverseWithTwoSubcommands(t *testing.T) {1517 rootCmd := &Command{Use: "root", TraverseChildren: true}1518 subCmd := &Command{Use: "sub", TraverseChildren: true}1519 rootCmd.AddCommand(subCmd)1520 subsubCmd := &Command{1521 Use: "subsub",1522 }1523 subCmd.AddCommand(subsubCmd)1524 c, _, err := rootCmd.Traverse([]string{"sub", "subsub"})1525 if err != nil {1526 t.Fatalf("Unexpected error: %v", err)1527 }1528 if c.Name() != subsubCmd.Name() {1529 t.Fatalf("Expected command: %q, got %q", subsubCmd.Name(), c.Name())1530 }1531}1532// TestUpdateName checks if c.Name() updates on changed c.Use.1533// Related to https://github.com/spf13/cobra/pull/422#discussion_r143918343.1534func TestUpdateName(t *testing.T) {1535 c := &Command{Use: "name xyz"}1536 originalName := c.Name()1537 c.Use = "changedName abc"1538 if originalName == c.Name() || c.Name() != "changedName" {1539 t.Error("c.Name() should be updated on changed c.Use")1540 }1541}1542type calledAsTestcase struct {1543 args []string1544 call string1545 want string1546 epm bool1547}1548func (tc *calledAsTestcase) test(t *testing.T) {1549 defer func(ov bool) { EnablePrefixMatching = ov }(EnablePrefixMatching)1550 EnablePrefixMatching = tc.epm1551 var called *Command1552 run := func(c *Command, _ []string) { t.Logf("called: %q", c.Name()); called = c }1553 parent := &Command{Use: "parent", Run: run}1554 child1 := &Command{Use: "child1", Run: run, Aliases: []string{"this"}}1555 child2 := &Command{Use: "child2", Run: run, Aliases: []string{"that"}}1556 parent.AddCommand(child1)1557 parent.AddCommand(child2)1558 parent.SetArgs(tc.args)1559 output := new(bytes.Buffer)1560 parent.SetOut(output)1561 parent.SetErr(output)1562 _ = parent.Execute()1563 if called == nil {1564 if tc.call != "" {1565 t.Errorf("missing expected call to command: %s", tc.call)1566 }1567 return1568 }1569 if called.Name() != tc.call {1570 t.Errorf("called command == %q; Wanted %q", called.Name(), tc.call)1571 } else if got := called.CalledAs(); got != tc.want {1572 t.Errorf("%s.CalledAs() == %q; Wanted: %q", tc.call, got, tc.want)1573 }1574}1575func TestCalledAs(t *testing.T) {1576 tests := map[string]calledAsTestcase{1577 "find/no-args": {nil, "parent", "parent", false},1578 "find/real-name": {[]string{"child1"}, "child1", "child1", false},1579 "find/full-alias": {[]string{"that"}, "child2", "that", false},1580 "find/part-no-prefix": {[]string{"thi"}, "", "", false},1581 "find/part-alias": {[]string{"thi"}, "child1", "this", true},1582 "find/conflict": {[]string{"th"}, "", "", true},1583 "traverse/no-args": {nil, "parent", "parent", false},1584 "traverse/real-name": {[]string{"child1"}, "child1", "child1", false},1585 "traverse/full-alias": {[]string{"that"}, "child2", "that", false},1586 "traverse/part-no-prefix": {[]string{"thi"}, "", "", false},1587 "traverse/part-alias": {[]string{"thi"}, "child1", "this", true},1588 "traverse/conflict": {[]string{"th"}, "", "", true},1589 }1590 for name, tc := range tests {1591 t.Run(name, tc.test)1592 }1593}1594func TestFParseErrWhitelistBackwardCompatibility(t *testing.T) {1595 c := &Command{Use: "c", Run: emptyRun}1596 c.Flags().BoolP("boola", "a", false, "a boolean flag")1597 output, err := executeCommand(c, "c", "-a", "--unknown", "flag")1598 if err == nil {1599 t.Error("expected unknown flag error")1600 }1601 checkStringContains(t, output, "unknown flag: --unknown")1602}1603func TestFParseErrWhitelistSameCommand(t *testing.T) {1604 c := &Command{1605 Use: "c",1606 Run: emptyRun,1607 FParseErrWhitelist: FParseErrWhitelist{1608 UnknownFlags: true,1609 },1610 }1611 c.Flags().BoolP("boola", "a", false, "a boolean flag")1612 _, err := executeCommand(c, "c", "-a", "--unknown", "flag")1613 if err != nil {1614 t.Error("unexpected error: ", err)1615 }1616}1617func TestFParseErrWhitelistParentCommand(t *testing.T) {1618 root := &Command{1619 Use: "root",1620 Run: emptyRun,1621 FParseErrWhitelist: FParseErrWhitelist{1622 UnknownFlags: true,1623 },1624 }1625 c := &Command{1626 Use: "child",1627 Run: emptyRun,1628 }1629 c.Flags().BoolP("boola", "a", false, "a boolean flag")1630 root.AddCommand(c)1631 output, err := executeCommand(root, "child", "-a", "--unknown", "flag")1632 if err == nil {1633 t.Error("expected unknown flag error")1634 }1635 checkStringContains(t, output, "unknown flag: --unknown")1636}1637func TestFParseErrWhitelistChildCommand(t *testing.T) {1638 root := &Command{1639 Use: "root",1640 Run: emptyRun,1641 }1642 c := &Command{1643 Use: "child",1644 Run: emptyRun,1645 FParseErrWhitelist: FParseErrWhitelist{1646 UnknownFlags: true,1647 },1648 }1649 c.Flags().BoolP("boola", "a", false, "a boolean flag")1650 root.AddCommand(c)1651 _, err := executeCommand(root, "child", "-a", "--unknown", "flag")1652 if err != nil {1653 t.Error("unexpected error: ", err.Error())1654 }1655}1656func TestFParseErrWhitelistSiblingCommand(t *testing.T) {1657 root := &Command{1658 Use: "root",1659 Run: emptyRun,1660 }1661 c := &Command{1662 Use: "child",1663 Run: emptyRun,1664 FParseErrWhitelist: FParseErrWhitelist{1665 UnknownFlags: true,1666 },1667 }1668 c.Flags().BoolP("boola", "a", false, "a boolean flag")1669 s := &Command{1670 Use: "sibling",1671 Run: emptyRun,1672 }1673 s.Flags().BoolP("boolb", "b", false, "a boolean flag")1674 root.AddCommand(c)1675 root.AddCommand(s)1676 output, err := executeCommand(root, "sibling", "-b", "--unknown", "flag")1677 if err == nil {1678 t.Error("expected unknown flag error")1679 }1680 checkStringContains(t, output, "unknown flag: --unknown")1681}...
ae_test.go
Source:ae_test.go
...22 {1000, 4},23 {10000, 8},24 }25 for _, tt := range tests {26 t.Run(fmt.Sprintf("%d nodes", tt.nodes), func(t *testing.T) {27 if got, want := scaleFactor(tt.nodes), tt.scale; got != want {28 t.Fatalf("got scale factor %d want %d", got, want)29 }30 })31 }32}33func TestAE_Pause_nestedPauseResume(t *testing.T) {34 t.Parallel()35 l := NewStateSyncer(nil, 0, nil, nil)36 if l.Paused() != false {37 t.Fatal("syncer should be unPaused after init")38 }39 l.Pause()40 if l.Paused() != true {41 t.Fatal("syncer should be Paused after first call to Pause()")42 }43 l.Pause()44 if l.Paused() != true {45 t.Fatal("syncer should STILL be Paused after second call to Pause()")46 }47 gotR := l.Resume()48 if l.Paused() != true {49 t.Fatal("syncer should STILL be Paused after FIRST call to Resume()")50 }51 assert.False(t, gotR)52 gotR = l.Resume()53 if l.Paused() != false {54 t.Fatal("syncer should NOT be Paused after SECOND call to Resume()")55 }56 assert.True(t, gotR)57 defer func() {58 err := recover()59 if err == nil {60 t.Fatal("unbalanced Resume() should panic")61 }62 }()63 l.Resume()64}65func TestAE_Pause_ResumeTriggersSyncChanges(t *testing.T) {66 l := NewStateSyncer(nil, 0, nil, nil)67 l.Pause()68 l.Resume()69 select {70 case <-l.SyncChanges.Notif():71 // expected72 case <-l.SyncFull.Notif():73 t.Fatal("resume triggered SyncFull instead of SyncChanges")74 default:75 t.Fatal("resume did not trigger SyncFull")76 }77}78func TestAE_staggerDependsOnClusterSize(t *testing.T) {79 libRandomStagger = func(d time.Duration) time.Duration { return d }80 defer func() { libRandomStagger = lib.RandomStagger }()81 l := testSyncer(t)82 if got, want := l.staggerFn(10*time.Millisecond), 10*time.Millisecond; got != want {83 t.Fatalf("got %v want %v", got, want)84 }85 l.ClusterSize = func() int { return 256 }86 if got, want := l.staggerFn(10*time.Millisecond), 20*time.Millisecond; got != want {87 t.Fatalf("got %v want %v", got, want)88 }89}90func TestAE_Run_SyncFullBeforeChanges(t *testing.T) {91 shutdownCh := make(chan struct{})92 state := &mock{93 syncChanges: func() error {94 close(shutdownCh)95 return nil96 },97 }98 // indicate that we have partial changes before starting Run99 l := testSyncer(t)100 l.State = state101 l.ShutdownCh = shutdownCh102 l.SyncChanges.Trigger()103 var wg sync.WaitGroup104 wg.Add(1)105 go func() {106 defer wg.Done()107 l.Run()108 }()109 wg.Wait()110 if got, want := state.seq, []string{"full", "changes"}; !reflect.DeepEqual(got, want) {111 t.Fatalf("got call sequence %v want %v", got, want)112 }113}114func TestAE_Run_Quit(t *testing.T) {115 t.Run("Run panics without ClusterSize", func(t *testing.T) {116 defer func() {117 err := recover()118 if err == nil {119 t.Fatal("Run should panic")120 }121 }()122 l := testSyncer(t)123 l.ClusterSize = nil124 l.Run()125 })126 t.Run("runFSM quits", func(t *testing.T) {127 // start timer which explodes if runFSM does not quit128 tm := time.AfterFunc(time.Second, func() { panic("timeout") })129 l := testSyncer(t)130 l.runFSM(fullSyncState, func(fsmState) fsmState { return doneState })131 // should just quit132 tm.Stop()133 })134}135func TestAE_FSM(t *testing.T) {136 t.Run("fullSyncState", func(t *testing.T) {137 t.Run("Paused -> retryFullSyncState", func(t *testing.T) {138 l := testSyncer(t)139 l.Pause()140 fs := l.nextFSMState(fullSyncState)141 if got, want := fs, retryFullSyncState; got != want {142 t.Fatalf("got state %v want %v", got, want)143 }144 })145 t.Run("SyncFull() error -> retryFullSyncState", func(t *testing.T) {146 l := testSyncer(t)147 l.State = &mock{syncFull: func() error { return errors.New("boom") }}148 fs := l.nextFSMState(fullSyncState)149 if got, want := fs, retryFullSyncState; got != want {150 t.Fatalf("got state %v want %v", got, want)151 }152 })153 t.Run("SyncFull() OK -> partialSyncState", func(t *testing.T) {154 l := testSyncer(t)155 l.State = &mock{}156 fs := l.nextFSMState(fullSyncState)157 if got, want := fs, partialSyncState; got != want {158 t.Fatalf("got state %v want %v", got, want)159 }160 })161 })162 t.Run("retryFullSyncState", func(t *testing.T) {163 // helper for testing state transitions from retrySyncFullState164 test := func(ev event, to fsmState) {165 l := testSyncer(t)166 l.retrySyncFullEvent = func() event { return ev }167 fs := l.nextFSMState(retryFullSyncState)168 if got, want := fs, to; got != want {169 t.Fatalf("got state %v want %v", got, want)170 }171 }172 t.Run("shutdownEvent -> doneState", func(t *testing.T) {173 test(shutdownEvent, doneState)174 })175 t.Run("syncFullNotifEvent -> fullSyncState", func(t *testing.T) {176 test(syncFullNotifEvent, fullSyncState)177 })178 t.Run("syncFullTimerEvent -> fullSyncState", func(t *testing.T) {179 test(syncFullTimerEvent, fullSyncState)180 })181 t.Run("invalid event -> panic ", func(t *testing.T) {182 defer func() {183 err := recover()184 if err == nil {185 t.Fatal("invalid event should panic")186 }187 }()188 test(event("invalid"), fsmState(""))189 })190 })191 t.Run("partialSyncState", func(t *testing.T) {192 // helper for testing state transitions from partialSyncState193 test := func(ev event, to fsmState) {194 l := testSyncer(t)195 l.syncChangesEvent = func() event { return ev }196 fs := l.nextFSMState(partialSyncState)197 if got, want := fs, to; got != want {198 t.Fatalf("got state %v want %v", got, want)199 }200 }201 t.Run("shutdownEvent -> doneState", func(t *testing.T) {202 test(shutdownEvent, doneState)203 })204 t.Run("syncFullNotifEvent -> fullSyncState", func(t *testing.T) {205 test(syncFullNotifEvent, fullSyncState)206 })207 t.Run("syncFullTimerEvent -> fullSyncState", func(t *testing.T) {208 test(syncFullTimerEvent, fullSyncState)209 })210 t.Run("syncChangesEvent+Paused -> partialSyncState", func(t *testing.T) {211 l := testSyncer(t)212 l.Pause()213 l.syncChangesEvent = func() event { return syncChangesNotifEvent }214 fs := l.nextFSMState(partialSyncState)215 if got, want := fs, partialSyncState; got != want {216 t.Fatalf("got state %v want %v", got, want)217 }218 })219 t.Run("syncChangesEvent+SyncChanges() error -> partialSyncState", func(t *testing.T) {220 l := testSyncer(t)221 l.State = &mock{syncChanges: func() error { return errors.New("boom") }}222 l.syncChangesEvent = func() event { return syncChangesNotifEvent }223 fs := l.nextFSMState(partialSyncState)224 if got, want := fs, partialSyncState; got != want {225 t.Fatalf("got state %v want %v", got, want)226 }227 })228 t.Run("syncChangesEvent+SyncChanges() OK -> partialSyncState", func(t *testing.T) {229 l := testSyncer(t)230 l.State = &mock{}231 l.syncChangesEvent = func() event { return syncChangesNotifEvent }232 fs := l.nextFSMState(partialSyncState)233 if got, want := fs, partialSyncState; got != want {234 t.Fatalf("got state %v want %v", got, want)235 }236 })237 t.Run("invalid event -> panic ", func(t *testing.T) {238 defer func() {239 err := recover()240 if err == nil {241 t.Fatal("invalid event should panic")242 }243 }()244 test(event("invalid"), fsmState(""))245 })246 })247 t.Run("invalid state -> panic ", func(t *testing.T) {248 defer func() {249 err := recover()250 if err == nil {251 t.Fatal("invalid state should panic")252 }253 }()254 l := testSyncer(t)255 l.nextFSMState(fsmState("invalid"))256 })257}258func TestAE_RetrySyncFullEvent(t *testing.T) {259 t.Run("trigger shutdownEvent", func(t *testing.T) {260 l := testSyncer(t)261 l.ShutdownCh = make(chan struct{})262 evch := make(chan event)263 go func() { evch <- l.retrySyncFullEvent() }()264 close(l.ShutdownCh)265 if got, want := <-evch, shutdownEvent; got != want {266 t.Fatalf("got event %q want %q", got, want)267 }268 })269 t.Run("trigger shutdownEvent during FullNotif", func(t *testing.T) {270 l := testSyncer(t)271 l.ShutdownCh = make(chan struct{})272 evch := make(chan event)273 go func() { evch <- l.retrySyncFullEvent() }()274 l.SyncFull.Trigger()275 time.Sleep(100 * time.Millisecond)276 close(l.ShutdownCh)277 if got, want := <-evch, shutdownEvent; got != want {278 t.Fatalf("got event %q want %q", got, want)279 }280 })281 t.Run("trigger syncFullNotifEvent", func(t *testing.T) {282 l := testSyncer(t)283 l.serverUpInterval = 10 * time.Millisecond284 evch := make(chan event)285 go func() { evch <- l.retrySyncFullEvent() }()286 l.SyncFull.Trigger()287 if got, want := <-evch, syncFullNotifEvent; got != want {288 t.Fatalf("got event %q want %q", got, want)289 }290 })291 t.Run("trigger syncFullTimerEvent", func(t *testing.T) {292 l := testSyncer(t)293 l.retryFailInterval = 10 * time.Millisecond294 evch := make(chan event)295 go func() { evch <- l.retrySyncFullEvent() }()296 if got, want := <-evch, syncFullTimerEvent; got != want {297 t.Fatalf("got event %q want %q", got, want)298 }299 })300}301func TestAE_SyncChangesEvent(t *testing.T) {302 t.Run("trigger shutdownEvent", func(t *testing.T) {303 l := testSyncer(t)304 l.ShutdownCh = make(chan struct{})305 evch := make(chan event)306 go func() { evch <- l.syncChangesEvent() }()307 close(l.ShutdownCh)308 if got, want := <-evch, shutdownEvent; got != want {309 t.Fatalf("got event %q want %q", got, want)310 }311 })312 t.Run("trigger shutdownEvent during FullNotif", func(t *testing.T) {313 l := testSyncer(t)314 l.ShutdownCh = make(chan struct{})315 evch := make(chan event)316 go func() { evch <- l.syncChangesEvent() }()317 l.SyncFull.Trigger()318 time.Sleep(100 * time.Millisecond)319 close(l.ShutdownCh)320 if got, want := <-evch, shutdownEvent; got != want {321 t.Fatalf("got event %q want %q", got, want)322 }323 })324 t.Run("trigger syncFullNotifEvent", func(t *testing.T) {325 l := testSyncer(t)326 l.serverUpInterval = 10 * time.Millisecond327 evch := make(chan event)328 go func() { evch <- l.syncChangesEvent() }()329 l.SyncFull.Trigger()330 if got, want := <-evch, syncFullNotifEvent; got != want {331 t.Fatalf("got event %q want %q", got, want)332 }333 })334 t.Run("trigger syncFullTimerEvent", func(t *testing.T) {335 l := testSyncer(t)336 l.Interval = 10 * time.Millisecond337 evch := make(chan event)338 go func() { evch <- l.syncChangesEvent() }()339 if got, want := <-evch, syncFullTimerEvent; got != want {340 t.Fatalf("got event %q want %q", got, want)341 }342 })343 t.Run("trigger syncChangesNotifEvent", func(t *testing.T) {344 l := testSyncer(t)345 evch := make(chan event)346 go func() { evch <- l.syncChangesEvent() }()347 l.SyncChanges.Trigger()348 if got, want := <-evch, syncChangesNotifEvent; got != want {349 t.Fatalf("got event %q want %q", got, want)350 }351 })352}353type mock struct {354 seq []string355 syncFull, syncChanges func() error356}357func (m *mock) SyncFull() error {...
args_test.go
Source:args_test.go
...3 "strings"4 "testing"5)6func TestNoArgs(t *testing.T) {7 c := &Command{Use: "c", Args: NoArgs, Run: emptyRun}8 output, err := executeCommand(c)9 if output != "" {10 t.Errorf("Unexpected string: %v", output)11 }12 if err != nil {13 t.Fatalf("Unexpected error: %v", err)14 }15}16func TestNoArgsWithArgs(t *testing.T) {17 c := &Command{Use: "c", Args: NoArgs, Run: emptyRun}18 _, err := executeCommand(c, "illegal")19 if err == nil {20 t.Fatal("Expected an error")21 }22 got := err.Error()23 expected := `unknown command "illegal" for "c"`24 if got != expected {25 t.Errorf("Expected: %q, got: %q", expected, got)26 }27}28func TestOnlyValidArgs(t *testing.T) {29 c := &Command{30 Use: "c",31 Args: OnlyValidArgs,32 ValidArgs: []string{"one", "two"},33 Run: emptyRun,34 }35 output, err := executeCommand(c, "one", "two")36 if output != "" {37 t.Errorf("Unexpected output: %v", output)38 }39 if err != nil {40 t.Fatalf("Unexpected error: %v", err)41 }42}43func TestOnlyValidArgsWithInvalidArgs(t *testing.T) {44 c := &Command{45 Use: "c",46 Args: OnlyValidArgs,47 ValidArgs: []string{"one", "two"},48 Run: emptyRun,49 }50 _, err := executeCommand(c, "three")51 if err == nil {52 t.Fatal("Expected an error")53 }54 got := err.Error()55 expected := `invalid argument "three" for "c"`56 if got != expected {57 t.Errorf("Expected: %q, got: %q", expected, got)58 }59}60func TestArbitraryArgs(t *testing.T) {61 c := &Command{Use: "c", Args: ArbitraryArgs, Run: emptyRun}62 output, err := executeCommand(c, "a", "b")63 if output != "" {64 t.Errorf("Unexpected output: %v", output)65 }66 if err != nil {67 t.Errorf("Unexpected error: %v", err)68 }69}70func TestMinimumNArgs(t *testing.T) {71 c := &Command{Use: "c", Args: MinimumNArgs(2), Run: emptyRun}72 output, err := executeCommand(c, "a", "b", "c")73 if output != "" {74 t.Errorf("Unexpected output: %v", output)75 }76 if err != nil {77 t.Errorf("Unexpected error: %v", err)78 }79}80func TestMinimumNArgsWithLessArgs(t *testing.T) {81 c := &Command{Use: "c", Args: MinimumNArgs(2), Run: emptyRun}82 _, err := executeCommand(c, "a")83 if err == nil {84 t.Fatal("Expected an error")85 }86 got := err.Error()87 expected := "requires at least 2 arg(s), only received 1"88 if got != expected {89 t.Fatalf("Expected %q, got %q", expected, got)90 }91}92func TestMaximumNArgs(t *testing.T) {93 c := &Command{Use: "c", Args: MaximumNArgs(3), Run: emptyRun}94 output, err := executeCommand(c, "a", "b")95 if output != "" {96 t.Errorf("Unexpected output: %v", output)97 }98 if err != nil {99 t.Errorf("Unexpected error: %v", err)100 }101}102func TestMaximumNArgsWithMoreArgs(t *testing.T) {103 c := &Command{Use: "c", Args: MaximumNArgs(2), Run: emptyRun}104 _, err := executeCommand(c, "a", "b", "c")105 if err == nil {106 t.Fatal("Expected an error")107 }108 got := err.Error()109 expected := "accepts at most 2 arg(s), received 3"110 if got != expected {111 t.Fatalf("Expected %q, got %q", expected, got)112 }113}114func TestExactArgs(t *testing.T) {115 c := &Command{Use: "c", Args: ExactArgs(3), Run: emptyRun}116 output, err := executeCommand(c, "a", "b", "c")117 if output != "" {118 t.Errorf("Unexpected output: %v", output)119 }120 if err != nil {121 t.Errorf("Unexpected error: %v", err)122 }123}124func TestExactArgsWithInvalidCount(t *testing.T) {125 c := &Command{Use: "c", Args: ExactArgs(2), Run: emptyRun}126 _, err := executeCommand(c, "a", "b", "c")127 if err == nil {128 t.Fatal("Expected an error")129 }130 got := err.Error()131 expected := "accepts 2 arg(s), received 3"132 if got != expected {133 t.Fatalf("Expected %q, got %q", expected, got)134 }135}136func TestExactValidArgs(t *testing.T) {137 c := &Command{Use: "c", Args: ExactValidArgs(3), ValidArgs: []string{"a", "b", "c"}, Run: emptyRun}138 output, err := executeCommand(c, "a", "b", "c")139 if output != "" {140 t.Errorf("Unexpected output: %v", output)141 }142 if err != nil {143 t.Errorf("Unexpected error: %v", err)144 }145}146func TestExactValidArgsWithInvalidCount(t *testing.T) {147 c := &Command{Use: "c", Args: ExactValidArgs(2), Run: emptyRun}148 _, err := executeCommand(c, "a", "b", "c")149 if err == nil {150 t.Fatal("Expected an error")151 }152 got := err.Error()153 expected := "accepts 2 arg(s), received 3"154 if got != expected {155 t.Fatalf("Expected %q, got %q", expected, got)156 }157}158func TestExactValidArgsWithInvalidArgs(t *testing.T) {159 c := &Command{160 Use: "c",161 Args: ExactValidArgs(1),162 ValidArgs: []string{"one", "two"},163 Run: emptyRun,164 }165 _, err := executeCommand(c, "three")166 if err == nil {167 t.Fatal("Expected an error")168 }169 got := err.Error()170 expected := `invalid argument "three" for "c"`171 if got != expected {172 t.Errorf("Expected: %q, got: %q", expected, got)173 }174}175func TestRangeArgs(t *testing.T) {176 c := &Command{Use: "c", Args: RangeArgs(2, 4), Run: emptyRun}177 output, err := executeCommand(c, "a", "b", "c")178 if output != "" {179 t.Errorf("Unexpected output: %v", output)180 }181 if err != nil {182 t.Errorf("Unexpected error: %v", err)183 }184}185func TestRangeArgsWithInvalidCount(t *testing.T) {186 c := &Command{Use: "c", Args: RangeArgs(2, 4), Run: emptyRun}187 _, err := executeCommand(c, "a")188 if err == nil {189 t.Fatal("Expected an error")190 }191 got := err.Error()192 expected := "accepts between 2 and 4 arg(s), received 1"193 if got != expected {194 t.Fatalf("Expected %q, got %q", expected, got)195 }196}197func TestRootTakesNoArgs(t *testing.T) {198 rootCmd := &Command{Use: "root", Run: emptyRun}199 childCmd := &Command{Use: "child", Run: emptyRun}200 rootCmd.AddCommand(childCmd)201 _, err := executeCommand(rootCmd, "illegal", "args")202 if err == nil {203 t.Fatal("Expected an error")204 }205 got := err.Error()206 expected := `unknown command "illegal" for "root"`207 if !strings.Contains(got, expected) {208 t.Errorf("expected %q, got %q", expected, got)209 }210}211func TestRootTakesArgs(t *testing.T) {212 rootCmd := &Command{Use: "root", Args: ArbitraryArgs, Run: emptyRun}213 childCmd := &Command{Use: "child", Run: emptyRun}214 rootCmd.AddCommand(childCmd)215 _, err := executeCommand(rootCmd, "legal", "args")216 if err != nil {217 t.Errorf("Unexpected error: %v", err)218 }219}220func TestChildTakesNoArgs(t *testing.T) {221 rootCmd := &Command{Use: "root", Run: emptyRun}222 childCmd := &Command{Use: "child", Args: NoArgs, Run: emptyRun}223 rootCmd.AddCommand(childCmd)224 _, err := executeCommand(rootCmd, "child", "illegal", "args")225 if err == nil {226 t.Fatal("Expected an error")227 }228 got := err.Error()229 expected := `unknown command "illegal" for "root child"`230 if !strings.Contains(got, expected) {231 t.Errorf("expected %q, got %q", expected, got)232 }233}234func TestChildTakesArgs(t *testing.T) {235 rootCmd := &Command{Use: "root", Run: emptyRun}236 childCmd := &Command{Use: "child", Args: ArbitraryArgs, Run: emptyRun}237 rootCmd.AddCommand(childCmd)238 _, err := executeCommand(rootCmd, "child", "legal", "args")239 if err != nil {240 t.Fatalf("Unexpected error: %v", err)241 }242}...
Run
Using AI Code Generation
1import (2func main() {3 got := new(Got)4 got.Run()5}6import (7func main() {8 got := new(Got)9 got.Run()10}11import (12func main() {13 got := new(Got)14 got.Run()15}16import (17func main() {18 got := new(Got)19 got.Run()20}21import (22func main() {23 got := new(Got)24 got.Run()25}26import (27func main() {28 got := new(Got)29 got.Run()30}31import (32func main() {33 got := new(Got)34 got.Run()35}36import (37func main() {38 got := new(Got)39 got.Run()40}41import (42func main() {43 got := new(Got)44 got.Run()45}46import (47func main() {48 got := new(Got)49 got.Run()50}51import (52func main() {53 got := new(Got)54 got.Run()55}56import (57func main() {58 got := new(Got)59 got.Run()
Run
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World")4 got.Run()5}6import (7func main() {8 fmt.Println("Hello World")9 got.Run()10}11import (12func main() {13 fmt.Println("Hello World")14 got.Run()15}16import (17func main() {18 fmt.Println("Hello World")19 got.Run()20}21import (22func main() {23 fmt.Println("Hello World")24 got.Run()25}26import (27func main() {28 fmt.Println("Hello World")29 got.Run()30}31import (32func main() {33 fmt.Println("Hello World")34 got.Run()35}36import (37func main() {38 fmt.Println("Hello World")39 got.Run()40}41import (42func main() {43 fmt.Println("Hello World")44 got.Run()45}46import (47func main() {48 fmt.Println("Hello World")49 got.Run()50}
Run
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, playground")4 got := new(Got)5 got.Run()6}7import "fmt"8type Got struct {9}10func (g *Got) Run() {11 fmt.Println("Running")12}
Run
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World")4 g := got.NewGot()5 g.Run()6}7import (8type Got struct {9}10func NewGot() *Got {11 return &Got{}12}13func (g *Got) Run() {14 fmt.Println("Run method invoked")15}
Run
Using AI Code Generation
1func main() {2 got := new(Got)3 got.Run()4}5func main() {6 got := new(Got)7 got.Run()8}9func main() {10 got := new(Got)11 got.Run()12}13func main() {14 got := new(Got)15 got.Run()16}17func main() {18 got := new(Got)19 got.Run()20}21func main() {22 got := new(Got)23 got.Run()24}25func main() {26 got := new(Got)27 got.Run()28}29func main() {30 got := new(Got)31 got.Run()32}33func main() {34 got := new(Got)35 got.Run()36}37func main() {38 got := new(Got)39 got.Run()40}41func main() {
Run
Using AI Code Generation
1import (2func main() {3 g.Run()4 fmt.Println("GOT is awesome")5}6import "fmt"7type Got struct {8}9func (g *Got) Run() {10 fmt.Println("GOT is running")11}
Run
Using AI Code Generation
1import (2func main() {3 got.Run()4 fmt.Println("hello")5}6./1.go:5: imported and not used: "got"7./2.go:5: imported and not used: "got"8./3.go:5: imported and not used: "got"9./1.go:5: imported and not used: "got"10./2.go:5: imported and not used: "got"11./3.go:5: imported and not used: "got"12You can also use the Run method of got package in the main package without importing it. Here is the code:13func main() {14 Run()15}
Run
Using AI Code Generation
1import (2type got struct {3}4func (g *got) Run(){5 for i:=0;i<10;i++{6 time.Sleep(time.Duration(g.time)*time.Second)7 g.score+=rand.Intn(10)8 }9}10func main(){11 g1:=got{"Jon Snow",0,1}12 g2:=got{"Daenerys Targaryen",0,2}13 g3:=got{"Arya Stark",0,3}14 g4:=got{"Tyrion Lannister",0,4}15 g5:=got{"Cersei Lannister",0,5}16 go g1.Run()17 go g2.Run()18 go g3.Run()19 go g4.Run()20 go g5.Run()21 time.Sleep(time.Duration(10)*time.Second)22 fmt.Println(g1)23 fmt.Println(g2)24 fmt.Println(g3)25 fmt.Println(g4)26 fmt.Println(g5)27}28{Jon Snow 37 1}29{Daenerys Targaryen 35 2}30{Arya Stark 38 3}31{Tyrion Lannister 36 4}32{Cersei Lannister 37 5}33{Jon Snow 37 1}34{Daenerys Targaryen 35 2}35{Arya Stark 38 3}36{Tyrion Lannister 36 4}37{Cersei Lannister 37 5}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!