Skip to content
Myr

command_test.go

This file

Path

command_test.go

2,954 lines · 78.2 KiB · Go

Last changed by

chore(golangci-lint): upgrade to v2Ville Skyttäbefore adoption75790e4

History of this file

Take it

1// Copyright 2013-2023 The Cobra Authors2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415package cobra1617import (18	"bytes"19	"context"20	"fmt"21	"io"22	"os"23	"reflect"24	"strings"25	"testing"2627	"github.com/spf13/pflag"28)2930func emptyRun(*Command, []string) {}3132func executeCommand(root *Command, args ...string) (output string, err error) {33	_, output, err = executeCommandC(root, args...)34	return output, err35}3637func executeCommandWithContext(ctx context.Context, root *Command, args ...string) (output string, err error) {38	buf := new(bytes.Buffer)39	root.SetOut(buf)40	root.SetErr(buf)41	root.SetArgs(args)4243	err = root.ExecuteContext(ctx)4445	return buf.String(), err46}4748func executeCommandC(root *Command, args ...string) (c *Command, output string, err error) {49	buf := new(bytes.Buffer)50	root.SetOut(buf)51	root.SetErr(buf)52	root.SetArgs(args)5354	c, err = root.ExecuteC()5556	return c, buf.String(), err57}5859func executeCommandWithContextC(ctx context.Context, root *Command, args ...string) (c *Command, output string, err error) {60	buf := new(bytes.Buffer)61	root.SetOut(buf)62	root.SetErr(buf)63	root.SetArgs(args)6465	c, err = root.ExecuteContextC(ctx)6667	return c, buf.String(), err68}6970func resetCommandLineFlagSet() {71	pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)72}7374func checkStringContains(t *testing.T, got, expected string) {75	if !strings.Contains(got, expected) {76		t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got)77	}78}7980func checkStringOmits(t *testing.T, got, expected string) {81	if strings.Contains(got, expected) {82		t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got)83	}84}8586const onetwo = "one two"8788func TestSingleCommand(t *testing.T) {89	var rootCmdArgs []string90	rootCmd := &Command{91		Use:  "root",92		Args: ExactArgs(2),93		Run:  func(_ *Command, args []string) { rootCmdArgs = args },94	}95	aCmd := &Command{Use: "a", Args: NoArgs, Run: emptyRun}96	bCmd := &Command{Use: "b", Args: NoArgs, Run: emptyRun}97	rootCmd.AddCommand(aCmd, bCmd)9899	output, err := executeCommand(rootCmd, "one", "two")100	if output != "" {101		t.Errorf("Unexpected output: %v", output)102	}103	if err != nil {104		t.Errorf("Unexpected error: %v", err)105	}106107	got := strings.Join(rootCmdArgs, " ")108	if got != onetwo {109		t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)110	}111}112113func TestChildCommand(t *testing.T) {114	var child1CmdArgs []string115	rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}116	child1Cmd := &Command{117		Use:  "child1",118		Args: ExactArgs(2),119		Run:  func(_ *Command, args []string) { child1CmdArgs = args },120	}121	child2Cmd := &Command{Use: "child2", Args: NoArgs, Run: emptyRun}122	rootCmd.AddCommand(child1Cmd, child2Cmd)123124	output, err := executeCommand(rootCmd, "child1", "one", "two")125	if output != "" {126		t.Errorf("Unexpected output: %v", output)127	}128	if err != nil {129		t.Errorf("Unexpected error: %v", err)130	}131132	got := strings.Join(child1CmdArgs, " ")133	if got != onetwo {134		t.Errorf("child1CmdArgs expected: %q, got: %q", onetwo, got)135	}136}137138func TestCallCommandWithoutSubcommands(t *testing.T) {139	rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}140	_, err := executeCommand(rootCmd)141	if err != nil {142		t.Errorf("Calling command without subcommands should not have error: %v", err)143	}144}145146func TestRootExecuteUnknownCommand(t *testing.T) {147	rootCmd := &Command{Use: "root", Run: emptyRun}148	rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})149150	output, _ := executeCommand(rootCmd, "unknown")151152	expected := "Error: unknown command \"unknown\" for \"root\"\nRun 'root --help' for usage.\n"153154	if output != expected {155		t.Errorf("Expected:\n %q\nGot:\n %q\n", expected, output)156	}157}158159func TestSubcommandExecuteC(t *testing.T) {160	rootCmd := &Command{Use: "root", Run: emptyRun}161	childCmd := &Command{Use: "child", Run: emptyRun}162	rootCmd.AddCommand(childCmd)163164	c, output, err := executeCommandC(rootCmd, "child")165	if output != "" {166		t.Errorf("Unexpected output: %v", output)167	}168	if err != nil {169		t.Errorf("Unexpected error: %v", err)170	}171172	if c.Name() != "child" {173		t.Errorf(`invalid command returned from ExecuteC: expected "child"', got: %q`, c.Name())174	}175}176177func TestExecuteContext(t *testing.T) {178	ctx := context.TODO()179180	ctxRun := func(cmd *Command, args []string) {181		if cmd.Context() != ctx {182			t.Errorf("Command %q must have context when called with ExecuteContext", cmd.Use)183		}184	}185186	rootCmd := &Command{Use: "root", Run: ctxRun, PreRun: ctxRun}187	childCmd := &Command{Use: "child", Run: ctxRun, PreRun: ctxRun}188	granchildCmd := &Command{Use: "grandchild", Run: ctxRun, PreRun: ctxRun}189190	childCmd.AddCommand(granchildCmd)191	rootCmd.AddCommand(childCmd)192193	if _, err := executeCommandWithContext(ctx, rootCmd, ""); err != nil {194		t.Errorf("Root command must not fail: %+v", err)195	}196197	if _, err := executeCommandWithContext(ctx, rootCmd, "child"); err != nil {198		t.Errorf("Subcommand must not fail: %+v", err)199	}200201	if _, err := executeCommandWithContext(ctx, rootCmd, "child", "grandchild"); err != nil {202		t.Errorf("Command child must not fail: %+v", err)203	}204}205206func TestExecuteContextC(t *testing.T) {207	ctx := context.TODO()208209	ctxRun := func(cmd *Command, args []string) {210		if cmd.Context() != ctx {211			t.Errorf("Command %q must have context when called with ExecuteContext", cmd.Use)212		}213	}214215	rootCmd := &Command{Use: "root", Run: ctxRun, PreRun: ctxRun}216	childCmd := &Command{Use: "child", Run: ctxRun, PreRun: ctxRun}217	granchildCmd := &Command{Use: "grandchild", Run: ctxRun, PreRun: ctxRun}218219	childCmd.AddCommand(granchildCmd)220	rootCmd.AddCommand(childCmd)221222	if _, _, err := executeCommandWithContextC(ctx, rootCmd, ""); err != nil {223		t.Errorf("Root command must not fail: %+v", err)224	}225226	if _, _, err := executeCommandWithContextC(ctx, rootCmd, "child"); err != nil {227		t.Errorf("Subcommand must not fail: %+v", err)228	}229230	if _, _, err := executeCommandWithContextC(ctx, rootCmd, "child", "grandchild"); err != nil {231		t.Errorf("Command child must not fail: %+v", err)232	}233}234235func TestExecute_NoContext(t *testing.T) {236	run := func(cmd *Command, args []string) {237		if cmd.Context() != context.Background() {238			t.Errorf("Command %s must have background context", cmd.Use)239		}240	}241242	rootCmd := &Command{Use: "root", Run: run, PreRun: run}243	childCmd := &Command{Use: "child", Run: run, PreRun: run}244	granchildCmd := &Command{Use: "grandchild", Run: run, PreRun: run}245246	childCmd.AddCommand(granchildCmd)247	rootCmd.AddCommand(childCmd)248249	if _, err := executeCommand(rootCmd, ""); err != nil {250		t.Errorf("Root command must not fail: %+v", err)251	}252253	if _, err := executeCommand(rootCmd, "child"); err != nil {254		t.Errorf("Subcommand must not fail: %+v", err)255	}256257	if _, err := executeCommand(rootCmd, "child", "grandchild"); err != nil {258		t.Errorf("Command child must not fail: %+v", err)259	}260}261262func TestRootUnknownCommandSilenced(t *testing.T) {263	rootCmd := &Command{Use: "root", Run: emptyRun}264	rootCmd.SilenceErrors = true265	rootCmd.SilenceUsage = true266	rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})267268	output, _ := executeCommand(rootCmd, "unknown")269	if output != "" {270		t.Errorf("Expected blank output, because of silenced usage.\nGot:\n %q\n", output)271	}272}273274func TestCommandAlias(t *testing.T) {275	var timesCmdArgs []string276	rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}277	echoCmd := &Command{278		Use:     "echo",279		Aliases: []string{"say", "tell"},280		Args:    NoArgs,281		Run:     emptyRun,282	}283	timesCmd := &Command{284		Use:  "times",285		Args: ExactArgs(2),286		Run:  func(_ *Command, args []string) { timesCmdArgs = args },287	}288	echoCmd.AddCommand(timesCmd)289	rootCmd.AddCommand(echoCmd)290291	output, err := executeCommand(rootCmd, "tell", "times", "one", "two")292	if output != "" {293		t.Errorf("Unexpected output: %v", output)294	}295	if err != nil {296		t.Errorf("Unexpected error: %v", err)297	}298299	got := strings.Join(timesCmdArgs, " ")300	if got != onetwo {301		t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got)302	}303}304305func TestEnablePrefixMatching(t *testing.T) {306	EnablePrefixMatching = true307308	var aCmdArgs []string309	rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}310	aCmd := &Command{311		Use:  "aCmd",312		Args: ExactArgs(2),313		Run:  func(_ *Command, args []string) { aCmdArgs = args },314	}315	bCmd := &Command{Use: "bCmd", Args: NoArgs, Run: emptyRun}316	rootCmd.AddCommand(aCmd, bCmd)317318	output, err := executeCommand(rootCmd, "a", "one", "two")319	if output != "" {320		t.Errorf("Unexpected output: %v", output)321	}322	if err != nil {323		t.Errorf("Unexpected error: %v", err)324	}325326	got := strings.Join(aCmdArgs, " ")327	if got != onetwo {328		t.Errorf("aCmdArgs expected: %q, got: %q", onetwo, got)329	}330331	EnablePrefixMatching = defaultPrefixMatching332}333334func TestAliasPrefixMatching(t *testing.T) {335	EnablePrefixMatching = true336337	var timesCmdArgs []string338	rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}339	echoCmd := &Command{340		Use:     "echo",341		Aliases: []string{"say", "tell"},342		Args:    NoArgs,343		Run:     emptyRun,344	}345	timesCmd := &Command{346		Use:  "times",347		Args: ExactArgs(2),348		Run:  func(_ *Command, args []string) { timesCmdArgs = args },349	}350	echoCmd.AddCommand(timesCmd)351	rootCmd.AddCommand(echoCmd)352353	output, err := executeCommand(rootCmd, "sa", "times", "one", "two")354	if output != "" {355		t.Errorf("Unexpected output: %v", output)356	}357	if err != nil {358		t.Errorf("Unexpected error: %v", err)359	}360361	got := strings.Join(timesCmdArgs, " ")362	if got != onetwo {363		t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got)364	}365366	EnablePrefixMatching = defaultPrefixMatching367}368369// TestPlugin checks usage as plugin for another command such as kubectl.  The370// executable is `kubectl-plugin`, but we run it as `kubectl plugin`. The help371// text should reflect the way we run the command.372func TestPlugin(t *testing.T) {373	cmd := &Command{374		Use:     "kubectl-plugin",375		Version: "1.0.0",376		Args:    NoArgs,377		Annotations: map[string]string{378			CommandDisplayNameAnnotation: "kubectl plugin",379		},380		Run: emptyRun,381	}382383	cmdHelp, err := executeCommand(cmd, "-h")384	if err != nil {385		t.Errorf("Unexpected error: %v", err)386	}387388	checkStringContains(t, cmdHelp, "kubectl plugin [flags]")389	checkStringContains(t, cmdHelp, "help for kubectl plugin")390	checkStringContains(t, cmdHelp, "version for kubectl plugin")391}392393// TestPluginWithSubCommands checks usage as plugin with sub commands.394func TestPluginWithSubCommands(t *testing.T) {395	rootCmd := &Command{396		Use:     "kubectl-plugin",397		Version: "1.0.0",398		Args:    NoArgs,399		Annotations: map[string]string{400			CommandDisplayNameAnnotation: "kubectl plugin",401		},402	}403404	subCmd := &Command{Use: "sub [flags]", Args: NoArgs, Run: emptyRun}405	rootCmd.AddCommand(subCmd)406407	rootHelp, err := executeCommand(rootCmd, "-h")408	if err != nil {409		t.Errorf("Unexpected error: %v", err)410	}411412	checkStringContains(t, rootHelp, "kubectl plugin [command]")413	checkStringContains(t, rootHelp, "help for kubectl plugin")414	checkStringContains(t, rootHelp, "version for kubectl plugin")415	checkStringContains(t, rootHelp, "kubectl plugin [command] --help")416417	childHelp, err := executeCommand(rootCmd, "sub", "-h")418	if err != nil {419		t.Errorf("Unexpected error: %v", err)420	}421422	checkStringContains(t, childHelp, "kubectl plugin sub [flags]")423	checkStringContains(t, childHelp, "help for sub")424425	helpHelp, err := executeCommand(rootCmd, "help", "-h")426	if err != nil {427		t.Errorf("Unexpected error: %v", err)428	}429430	checkStringContains(t, helpHelp, "kubectl plugin help [path to command]")431	checkStringContains(t, helpHelp, "kubectl plugin help [command]")432}433434// TestChildSameName checks the correct behaviour of cobra in cases,435// when an application with name "foo" and with subcommand "foo"436// is executed with args "foo foo".437func TestChildSameName(t *testing.T) {438	var fooCmdArgs []string439	rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}440	fooCmd := &Command{441		Use:  "foo",442		Args: ExactArgs(2),443		Run:  func(_ *Command, args []string) { fooCmdArgs = args },444	}445	barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}446	rootCmd.AddCommand(fooCmd, barCmd)447448	output, err := executeCommand(rootCmd, "foo", "one", "two")449	if output != "" {450		t.Errorf("Unexpected output: %v", output)451	}452	if err != nil {453		t.Errorf("Unexpected error: %v", err)454	}455456	got := strings.Join(fooCmdArgs, " ")457	if got != onetwo {458		t.Errorf("fooCmdArgs expected: %v, got: %v", onetwo, got)459	}460}461462// TestGrandChildSameName checks the correct behaviour of cobra in cases,463// when user has a root command and a grand child464// with the same name.465func TestGrandChildSameName(t *testing.T) {466	var fooCmdArgs []string467	rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}468	barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}469	fooCmd := &Command{470		Use:  "foo",471		Args: ExactArgs(2),472		Run:  func(_ *Command, args []string) { fooCmdArgs = args },473	}474	barCmd.AddCommand(fooCmd)475	rootCmd.AddCommand(barCmd)476477	output, err := executeCommand(rootCmd, "bar", "foo", "one", "two")478	if output != "" {479		t.Errorf("Unexpected output: %v", output)480	}481	if err != nil {482		t.Errorf("Unexpected error: %v", err)483	}484485	got := strings.Join(fooCmdArgs, " ")486	if got != onetwo {487		t.Errorf("fooCmdArgs expected: %v, got: %v", onetwo, got)488	}489}490491func TestFlagLong(t *testing.T) {492	var cArgs []string493	c := &Command{494		Use:  "c",495		Args: ArbitraryArgs,496		Run:  func(_ *Command, args []string) { cArgs = args },497	}498499	var intFlagValue int500	var stringFlagValue string501	c.Flags().IntVar(&intFlagValue, "intf", -1, "")502	c.Flags().StringVar(&stringFlagValue, "sf", "", "")503504	output, err := executeCommand(c, "--intf=7", "--sf=abc", "one", "--", "two")505	if output != "" {506		t.Errorf("Unexpected output: %v", output)507	}508	if err != nil {509		t.Errorf("Unexpected error: %v", err)510	}511512	if c.ArgsLenAtDash() != 1 {513		t.Errorf("Expected ArgsLenAtDash: %v but got %v", 1, c.ArgsLenAtDash())514	}515	if intFlagValue != 7 {516		t.Errorf("Expected intFlagValue: %v, got %v", 7, intFlagValue)517	}518	if stringFlagValue != "abc" {519		t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)520	}521522	got := strings.Join(cArgs, " ")523	if got != onetwo {524		t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)525	}526}527528func TestFlagShort(t *testing.T) {529	var cArgs []string530	c := &Command{531		Use:  "c",532		Args: ArbitraryArgs,533		Run:  func(_ *Command, args []string) { cArgs = args },534	}535536	var intFlagValue int537	var stringFlagValue string538	c.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")539	c.Flags().StringVarP(&stringFlagValue, "sf", "s", "", "")540541	output, err := executeCommand(c, "-i", "7", "-sabc", "one", "two")542	if output != "" {543		t.Errorf("Unexpected output: %v", output)544	}545	if err != nil {546		t.Errorf("Unexpected error: %v", err)547	}548549	if intFlagValue != 7 {550		t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)551	}552	if stringFlagValue != "abc" {553		t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)554	}555556	got := strings.Join(cArgs, " ")557	if got != onetwo {558		t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)559	}560}561562func TestChildFlag(t *testing.T) {563	rootCmd := &Command{Use: "root", Run: emptyRun}564	childCmd := &Command{Use: "child", Run: emptyRun}565	rootCmd.AddCommand(childCmd)566567	var intFlagValue int568	childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")569570	output, err := executeCommand(rootCmd, "child", "-i7")571	if output != "" {572		t.Errorf("Unexpected output: %v", output)573	}574	if err != nil {575		t.Errorf("Unexpected error: %v", err)576	}577578	if intFlagValue != 7 {579		t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)580	}581}582583func TestChildFlagWithParentLocalFlag(t *testing.T) {584	rootCmd := &Command{Use: "root", Run: emptyRun}585	childCmd := &Command{Use: "child", Run: emptyRun}586	rootCmd.AddCommand(childCmd)587588	var intFlagValue int589	rootCmd.Flags().StringP("sf", "s", "", "")590	childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")591592	_, err := executeCommand(rootCmd, "child", "-i7", "-sabc")593	if err == nil {594		t.Errorf("Invalid flag should generate error")595	}596597	checkStringContains(t, err.Error(), "unknown shorthand")598599	if intFlagValue != 7 {600		t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)601	}602}603604func TestFlagInvalidInput(t *testing.T) {605	rootCmd := &Command{Use: "root", Run: emptyRun}606	rootCmd.Flags().IntP("intf", "i", -1, "")607608	_, err := executeCommand(rootCmd, "-iabc")609	if err == nil {610		t.Errorf("Invalid flag value should generate error")611	}612613	checkStringContains(t, err.Error(), "invalid syntax")614}615616func TestFlagBeforeCommand(t *testing.T) {617	rootCmd := &Command{Use: "root", Run: emptyRun}618	childCmd := &Command{Use: "child", Run: emptyRun}619	rootCmd.AddCommand(childCmd)620621	var flagValue int622	childCmd.Flags().IntVarP(&flagValue, "intf", "i", -1, "")623624	// With short flag.625	_, err := executeCommand(rootCmd, "-i7", "child")626	if err != nil {627		t.Errorf("Unexpected error: %v", err)628	}629	if flagValue != 7 {630		t.Errorf("Expected flag value: %v, got %v", 7, flagValue)631	}632633	// With long flag.634	_, err = executeCommand(rootCmd, "--intf=8", "child")635	if err != nil {636		t.Errorf("Unexpected error: %v", err)637	}638	if flagValue != 8 {639		t.Errorf("Expected flag value: %v, got %v", 9, flagValue)640	}641}642643func TestStripFlags(t *testing.T) {644	tests := []struct {645		input  []string646		output []string647	}{648		{649			[]string{"foo", "bar"},650			[]string{"foo", "bar"},651		},652		{653			[]string{"foo", "--str", "-s"},654			[]string{"foo"},655		},656		{657			[]string{"-s", "foo", "--str", "bar"},658			[]string{},659		},660		{661			[]string{"-i10", "echo"},662			[]string{"echo"},663		},664		{665			[]string{"-i=10", "echo"},666			[]string{"echo"},667		},668		{669			[]string{"--int=100", "echo"},670			[]string{"echo"},671		},672		{673			[]string{"-ib", "echo", "-sfoo", "baz"},674			[]string{"echo", "baz"},675		},676		{677			[]string{"-i=baz", "bar", "-i", "foo", "blah"},678			[]string{"bar", "blah"},679		},680		{681			[]string{"--int=baz", "-sbar", "-i", "foo", "blah"},682			[]string{"blah"},683		},684		{685			[]string{"--bool", "bar", "-i", "foo", "blah"},686			[]string{"bar", "blah"},687		},688		{689			[]string{"-b", "bar", "-i", "foo", "blah"},690			[]string{"bar", "blah"},691		},692		{693			[]string{"--persist", "bar"},694			[]string{"bar"},695		},696		{697			[]string{"-p", "bar"},698			[]string{"bar"},699		},700	}701702	c := &Command{Use: "c", Run: emptyRun}703	c.PersistentFlags().BoolP("persist", "p", false, "")704	c.Flags().IntP("int", "i", -1, "")705	c.Flags().StringP("str", "s", "", "")706	c.Flags().BoolP("bool", "b", false, "")707708	for i, test := range tests {709		got := stripFlags(test.input, c)710		if !reflect.DeepEqual(test.output, got) {711			t.Errorf("(%v) Expected: %v, got: %v", i, test.output, got)712		}713	}714}715716func TestDisableFlagParsing(t *testing.T) {717	var cArgs []string718	c := &Command{719		Use:                "c",720		DisableFlagParsing: true,721		Run: func(_ *Command, args []string) {722			cArgs = args723		},724	}725726	args := []string{"cmd", "-v", "-race", "-file", "foo.go"}727	output, err := executeCommand(c, args...)728	if output != "" {729		t.Errorf("Unexpected output: %v", output)730	}731	if err != nil {732		t.Errorf("Unexpected error: %v", err)733	}734735	if !reflect.DeepEqual(args, cArgs) {736		t.Errorf("Expected: %v, got: %v", args, cArgs)737	}738}739740func TestPersistentFlagsOnSameCommand(t *testing.T) {741	var rootCmdArgs []string742	rootCmd := &Command{743		Use:  "root",744		Args: ArbitraryArgs,745		Run:  func(_ *Command, args []string) { rootCmdArgs = args },746	}747748	var flagValue int749	rootCmd.PersistentFlags().IntVarP(&flagValue, "intf", "i", -1, "")750751	output, err := executeCommand(rootCmd, "-i7", "one", "two")752	if output != "" {753		t.Errorf("Unexpected output: %v", output)754	}755	if err != nil {756		t.Errorf("Unexpected error: %v", err)757	}758759	got := strings.Join(rootCmdArgs, " ")760	if got != onetwo {761		t.Errorf("rootCmdArgs expected: %q, got %q", onetwo, got)762	}763	if flagValue != 7 {764		t.Errorf("flagValue expected: %v, got %v", 7, flagValue)765	}766}767768// TestEmptyInputs checks,769// if flags correctly parsed with blank strings in args.770func TestEmptyInputs(t *testing.T) {771	c := &Command{Use: "c", Run: emptyRun}772773	var flagValue int774	c.Flags().IntVarP(&flagValue, "intf", "i", -1, "")775776	output, err := executeCommand(c, "", "-i7", "")777	if output != "" {778		t.Errorf("Unexpected output: %v", output)779	}780	if err != nil {781		t.Errorf("Unexpected error: %v", err)782	}783784	if flagValue != 7 {785		t.Errorf("flagValue expected: %v, got %v", 7, flagValue)786	}787}788789func TestChildFlagShadowsParentPersistentFlag(t *testing.T) {790	parent := &Command{Use: "parent", Run: emptyRun}791	child := &Command{Use: "child", Run: emptyRun}792793	parent.PersistentFlags().Bool("boolf", false, "")794	parent.PersistentFlags().Int("intf", -1, "")795	child.Flags().String("strf", "", "")796	child.Flags().Int("intf", -1, "")797798	parent.AddCommand(child)799800	childInherited := child.InheritedFlags()801	childLocal := child.LocalFlags()802803	if childLocal.Lookup("strf") == nil {804		t.Error(`LocalFlags expected to contain "strf", got "nil"`)805	}806	if childInherited.Lookup("boolf") == nil {807		t.Error(`InheritedFlags expected to contain "boolf", got "nil"`)808	}809810	if childInherited.Lookup("intf") != nil {811		t.Errorf(`InheritedFlags should not contain shadowed flag "intf"`)812	}813	if childLocal.Lookup("intf") == nil {814		t.Error(`LocalFlags expected to contain "intf", got "nil"`)815	}816}817818func TestPersistentFlagsOnChild(t *testing.T) {819	var childCmdArgs []string820	rootCmd := &Command{Use: "root", Run: emptyRun}821	childCmd := &Command{822		Use:  "child",823		Args: ArbitraryArgs,824		Run:  func(_ *Command, args []string) { childCmdArgs = args },825	}826	rootCmd.AddCommand(childCmd)827828	var parentFlagValue int829	var childFlagValue int830	rootCmd.PersistentFlags().IntVarP(&parentFlagValue, "parentf", "p", -1, "")831	childCmd.Flags().IntVarP(&childFlagValue, "childf", "c", -1, "")832833	output, err := executeCommand(rootCmd, "child", "-c7", "-p8", "one", "two")834	if output != "" {835		t.Errorf("Unexpected output: %v", output)836	}837	if err != nil {838		t.Errorf("Unexpected error: %v", err)839	}840841	got := strings.Join(childCmdArgs, " ")842	if got != onetwo {843		t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)844	}845	if parentFlagValue != 8 {846		t.Errorf("parentFlagValue expected: %v, got %v", 8, parentFlagValue)847	}848	if childFlagValue != 7 {849		t.Errorf("childFlagValue expected: %v, got %v", 7, childFlagValue)850	}851}852853func TestRequiredFlags(t *testing.T) {854	c := &Command{Use: "c", Run: emptyRun}855	c.Flags().String("foo1", "", "")856	assertNoErr(t, c.MarkFlagRequired("foo1"))857	c.Flags().String("foo2", "", "")858	assertNoErr(t, c.MarkFlagRequired("foo2"))859	c.Flags().String("bar", "", "")860861	expected := fmt.Sprintf("required flag(s) %q, %q not set", "foo1", "foo2")862863	_, err := executeCommand(c)864	got := err.Error()865866	if got != expected {867		t.Errorf("Expected error: %q, got: %q", expected, got)868	}869}870871func TestPersistentRequiredFlags(t *testing.T) {872	parent := &Command{Use: "parent", Run: emptyRun}873	parent.PersistentFlags().String("foo1", "", "")874	assertNoErr(t, parent.MarkPersistentFlagRequired("foo1"))875	parent.PersistentFlags().String("foo2", "", "")876	assertNoErr(t, parent.MarkPersistentFlagRequired("foo2"))877	parent.Flags().String("foo3", "", "")878879	child := &Command{Use: "child", Run: emptyRun}880	child.Flags().String("bar1", "", "")881	assertNoErr(t, child.MarkFlagRequired("bar1"))882	child.Flags().String("bar2", "", "")883	assertNoErr(t, child.MarkFlagRequired("bar2"))884	child.Flags().String("bar3", "", "")885886	parent.AddCommand(child)887888	expected := fmt.Sprintf("required flag(s) %q, %q, %q, %q not set", "bar1", "bar2", "foo1", "foo2")889890	_, err := executeCommand(parent, "child")891	if err.Error() != expected {892		t.Errorf("Expected %q, got %q", expected, err.Error())893	}894}895896func TestPersistentRequiredFlagsWithDisableFlagParsing(t *testing.T) {897	// Make sure a required persistent flag does not break898	// commands that disable flag parsing899900	parent := &Command{Use: "parent", Run: emptyRun}901	parent.PersistentFlags().Bool("foo", false, "")902	flag := parent.PersistentFlags().Lookup("foo")903	assertNoErr(t, parent.MarkPersistentFlagRequired("foo"))904905	child := &Command{Use: "child", Run: emptyRun}906	child.DisableFlagParsing = true907908	parent.AddCommand(child)909910	if _, err := executeCommand(parent, "--foo", "child"); err != nil {911		t.Errorf("Unexpected error: %v", err)912	}913914	// Reset the flag or else it will remember the state from the previous command915	flag.Changed = false916	if _, err := executeCommand(parent, "child", "--foo"); err != nil {917		t.Errorf("Unexpected error: %v", err)918	}919920	// Reset the flag or else it will remember the state from the previous command921	flag.Changed = false922	if _, err := executeCommand(parent, "child"); err != nil {923		t.Errorf("Unexpected error: %v", err)924	}925}926927func TestInitHelpFlagMergesFlags(t *testing.T) {928	usage := "custom flag"929	rootCmd := &Command{Use: "root"}930	rootCmd.PersistentFlags().Bool("help", false, "custom flag")931	childCmd := &Command{Use: "child"}932	rootCmd.AddCommand(childCmd)933934	childCmd.InitDefaultHelpFlag()935	got := childCmd.Flags().Lookup("help").Usage936	if got != usage {937		t.Errorf("Expected the help flag from the root command with usage: %v\nGot the default with usage: %v", usage, got)938	}939}940941func TestHelpCommandExecuted(t *testing.T) {942	rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}943	rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})944945	output, err := executeCommand(rootCmd, "help")946	if err != nil {947		t.Errorf("Unexpected error: %v", err)948	}949950	checkStringContains(t, output, rootCmd.Long)951}952953func TestHelpCommandExecutedOnChild(t *testing.T) {954	rootCmd := &Command{Use: "root", Run: emptyRun}955	childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}956	rootCmd.AddCommand(childCmd)957958	output, err := executeCommand(rootCmd, "help", "child")959	if err != nil {960		t.Errorf("Unexpected error: %v", err)961	}962963	checkStringContains(t, output, childCmd.Long)964}965966func TestHelpCommandExecutedOnChildWithFlagThatShadowsParentFlag(t *testing.T) {967	parent := &Command{Use: "parent", Run: emptyRun}968	child := &Command{Use: "child", Run: emptyRun}969	parent.AddCommand(child)970971	parent.PersistentFlags().Bool("foo", false, "parent foo usage")972	parent.PersistentFlags().Bool("bar", false, "parent bar usage")973	child.Flags().Bool("foo", false, "child foo usage") // This shadows parent's foo flag974	child.Flags().Bool("baz", false, "child baz usage")975976	got, err := executeCommand(parent, "help", "child")977	if err != nil {978		t.Errorf("Unexpected error: %v", err)979	}980981	expected := `Usage:982  parent child [flags]983984Flags:985      --baz    child baz usage986      --foo    child foo usage987  -h, --help   help for child988989Global Flags:990      --bar   parent bar usage991`992993	if got != expected {994		t.Errorf("Help text mismatch.\nExpected:\n%s\n\nGot:\n%s\n", expected, got)995	}996}997998func TestSetHelpCommand(t *testing.T) {999	c := &Command{Use: "c", Run: emptyRun}1000	c.AddCommand(&Command{Use: "empty", Run: emptyRun})10011002	expected := "WORKS"1003	c.SetHelpCommand(&Command{1004		Use:   "help [command]",1005		Short: "Help about any command",1006		Long: `Help provides help for any command in the application.1007	Simply type ` + c.Name() + ` help [path to command] for full details.`,1008		Run: func(c *Command, _ []string) { c.Print(expected) },1009	})10101011	got, err := executeCommand(c, "help")1012	if err != nil {1013		t.Errorf("Unexpected error: %v", err)1014	}10151016	if got != expected {1017		t.Errorf("Expected to contain %q, got %q", expected, got)1018	}1019}10201021func TestSetHelpTemplate(t *testing.T) {1022	rootCmd := &Command{Use: "root", Run: emptyRun}1023	childCmd := &Command{Use: "child", Run: emptyRun}1024	rootCmd.AddCommand(childCmd)10251026	rootCmd.SetHelpTemplate("WORKS {{.UseLine}}")10271028	// Call the help on the root command and check the new template is used1029	got, err := executeCommand(rootCmd, "--help")1030	if err != nil {1031		t.Errorf("Unexpected error: %v", err)1032	}10331034	expected := "WORKS " + rootCmd.UseLine()1035	if got != expected {1036		t.Errorf("Expected %q, got %q", expected, got)1037	}10381039	// Call the help on the child command and check1040	// the new template is inherited from the parent1041	got, err = executeCommand(rootCmd, "child", "--help")1042	if err != nil {1043		t.Errorf("Unexpected error: %v", err)1044	}10451046	expected = "WORKS " + childCmd.UseLine()1047	if got != expected {1048		t.Errorf("Expected %q, got %q", expected, got)1049	}10501051	// Reset the root command help template and make sure1052	// it falls back to the default1053	rootCmd.SetHelpTemplate("")1054	got, err = executeCommand(rootCmd, "--help")1055	if err != nil {1056		t.Errorf("Unexpected error: %v", err)1057	}10581059	if !strings.Contains(got, "Usage:") {1060		t.Errorf("Expected to contain %q, got %q", "Usage:", got)1061	}1062}10631064func TestHelpFlagExecuted(t *testing.T) {1065	rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}10661067	output, err := executeCommand(rootCmd, "--help")1068	if err != nil {1069		t.Errorf("Unexpected error: %v", err)1070	}10711072	checkStringContains(t, output, rootCmd.Long)1073}10741075func TestHelpFlagExecutedOnChild(t *testing.T) {1076	rootCmd := &Command{Use: "root", Run: emptyRun}1077	childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}1078	rootCmd.AddCommand(childCmd)10791080	output, err := executeCommand(rootCmd, "child", "--help")1081	if err != nil {1082		t.Errorf("Unexpected error: %v", err)1083	}10841085	checkStringContains(t, output, childCmd.Long)1086}10871088// TestHelpFlagInHelp checks,1089// if '--help' flag is shown in help for child (executing `parent help child`),1090// that has no other flags.1091// Related to https://github.com/spf13/cobra/issues/302.1092func TestHelpFlagInHelp(t *testing.T) {1093	parentCmd := &Command{Use: "parent", Run: func(*Command, []string) {}}10941095	childCmd := &Command{Use: "child", Run: func(*Command, []string) {}}1096	parentCmd.AddCommand(childCmd)10971098	output, err := executeCommand(parentCmd, "help", "child")1099	if err != nil {1100		t.Errorf("Unexpected error: %v", err)1101	}11021103	checkStringContains(t, output, "[flags]")1104}11051106func TestFlagsInUsage(t *testing.T) {1107	rootCmd := &Command{Use: "root", Args: NoArgs, Run: func(*Command, []string) {}}1108	output, err := executeCommand(rootCmd, "--help")1109	if err != nil {1110		t.Errorf("Unexpected error: %v", err)1111	}11121113	checkStringContains(t, output, "[flags]")1114}11151116func TestHelpExecutedOnNonRunnableChild(t *testing.T) {1117	rootCmd := &Command{Use: "root", Run: emptyRun}1118	childCmd := &Command{Use: "child", Long: "Long description"}1119	rootCmd.AddCommand(childCmd)11201121	output, err := executeCommand(rootCmd, "child")1122	if err != nil {1123		t.Errorf("Unexpected error: %v", err)1124	}11251126	checkStringContains(t, output, childCmd.Long)1127}11281129func TestSetUsageTemplate(t *testing.T) {1130	rootCmd := &Command{Use: "root", Run: emptyRun}1131	childCmd := &Command{Use: "child", Run: emptyRun}1132	rootCmd.AddCommand(childCmd)11331134	rootCmd.SetUsageTemplate("WORKS {{.UseLine}}")11351136	// Trigger the usage on the root command and check the new template is used1137	got, err := executeCommand(rootCmd, "--invalid")1138	if err == nil {1139		t.Errorf("Expected error but did not get one")1140	}11411142	expected := "WORKS " + rootCmd.UseLine()1143	checkStringContains(t, got, expected)11441145	// Trigger the usage on the child command and check1146	// the new template is inherited from the parent1147	got, err = executeCommand(rootCmd, "child", "--invalid")1148	if err == nil {1149		t.Errorf("Expected error but did not get one")1150	}11511152	expected = "WORKS " + childCmd.UseLine()1153	checkStringContains(t, got, expected)11541155	// Reset the root command usage template and make sure1156	// it falls back to the default1157	rootCmd.SetUsageTemplate("")1158	got, err = executeCommand(rootCmd, "--invalid")1159	if err == nil {1160		t.Errorf("Expected error but did not get one")1161	}11621163	if !strings.Contains(got, "Usage:") {1164		t.Errorf("Expected to contain %q, got %q", "Usage:", got)1165	}1166}11671168func TestVersionFlagExecuted(t *testing.T) {1169	rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}11701171	output, err := executeCommand(rootCmd, "--version", "arg1")1172	if err != nil {1173		t.Errorf("Unexpected error: %v", err)1174	}11751176	checkStringContains(t, output, "root version 1.0.0")1177}11781179func TestVersionFlagExecutedDiplayName(t *testing.T) {1180	rootCmd := &Command{1181		Use:     "kubectl-plugin",1182		Version: "1.0.0",1183		Annotations: map[string]string{1184			CommandDisplayNameAnnotation: "kubectl plugin",1185		},1186		Run: emptyRun,1187	}11881189	output, err := executeCommand(rootCmd, "--version", "arg1")1190	if err != nil {1191		t.Errorf("Unexpected error: %v", err)1192	}11931194	checkStringContains(t, output, "kubectl plugin version 1.0.0")1195}11961197func TestVersionFlagExecutedWithNoName(t *testing.T) {1198	rootCmd := &Command{Version: "1.0.0", Run: emptyRun}11991200	output, err := executeCommand(rootCmd, "--version", "arg1")1201	if err != nil {1202		t.Errorf("Unexpected error: %v", err)1203	}12041205	checkStringContains(t, output, "version 1.0.0")1206}12071208func TestShortAndLongVersionFlagInHelp(t *testing.T) {1209	rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}12101211	output, err := executeCommand(rootCmd, "--help")1212	if err != nil {1213		t.Errorf("Unexpected error: %v", err)1214	}12151216	checkStringContains(t, output, "-v, --version")1217}12181219func TestLongVersionFlagOnlyInHelpWhenShortPredefined(t *testing.T) {1220	rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}1221	rootCmd.Flags().StringP("foo", "v", "", "not a version flag")12221223	output, err := executeCommand(rootCmd, "--help")1224	if err != nil {1225		t.Errorf("Unexpected error: %v", err)1226	}12271228	checkStringOmits(t, output, "-v, --version")1229	checkStringContains(t, output, "--version")1230}12311232func TestShorthandVersionFlagExecuted(t *testing.T) {1233	rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}12341235	output, err := executeCommand(rootCmd, "-v", "arg1")1236	if err != nil {1237		t.Errorf("Unexpected error: %v", err)1238	}12391240	checkStringContains(t, output, "root version 1.0.0")1241}12421243func TestVersionTemplate(t *testing.T) {1244	rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}1245	rootCmd.SetVersionTemplate(`customized version: {{.Version}}`)12461247	output, err := executeCommand(rootCmd, "--version", "arg1")1248	if err != nil {1249		t.Errorf("Unexpected error: %v", err)1250	}12511252	checkStringContains(t, output, "customized version: 1.0.0")1253}12541255func TestShorthandVersionTemplate(t *testing.T) {1256	rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}1257	rootCmd.SetVersionTemplate(`customized version: {{.Version}}`)12581259	output, err := executeCommand(rootCmd, "-v", "arg1")1260	if err != nil {1261		t.Errorf("Unexpected error: %v", err)1262	}12631264	checkStringContains(t, output, "customized version: 1.0.0")1265}12661267func TestRootErrPrefixExecutedOnSubcommand(t *testing.T) {1268	rootCmd := &Command{Use: "root", Run: emptyRun}1269	rootCmd.SetErrPrefix("root error prefix:")1270	rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})12711272	output, err := executeCommand(rootCmd, "sub", "--unknown-flag")1273	if err == nil {1274		t.Errorf("Expected error")1275	}12761277	checkStringContains(t, output, "root error prefix: unknown flag: --unknown-flag")1278}12791280func TestRootAndSubErrPrefix(t *testing.T) {1281	rootCmd := &Command{Use: "root", Run: emptyRun}1282	subCmd := &Command{Use: "sub", Run: emptyRun}1283	rootCmd.AddCommand(subCmd)1284	rootCmd.SetErrPrefix("root error prefix:")1285	subCmd.SetErrPrefix("sub error prefix:")12861287	if output, err := executeCommand(rootCmd, "--unknown-root-flag"); err == nil {1288		t.Errorf("Expected error")1289	} else {1290		checkStringContains(t, output, "root error prefix: unknown flag: --unknown-root-flag")1291	}12921293	if output, err := executeCommand(rootCmd, "sub", "--unknown-sub-flag"); err == nil {1294		t.Errorf("Expected error")1295	} else {1296		checkStringContains(t, output, "sub error prefix: unknown flag: --unknown-sub-flag")1297	}1298}12991300func TestVersionFlagExecutedOnSubcommand(t *testing.T) {1301	rootCmd := &Command{Use: "root", Version: "1.0.0"}1302	rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})13031304	output, err := executeCommand(rootCmd, "--version", "sub")1305	if err != nil {1306		t.Errorf("Unexpected error: %v", err)1307	}13081309	checkStringContains(t, output, "root version 1.0.0")1310}13111312func TestShorthandVersionFlagExecutedOnSubcommand(t *testing.T) {1313	rootCmd := &Command{Use: "root", Version: "1.0.0"}1314	rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})13151316	output, err := executeCommand(rootCmd, "-v", "sub")1317	if err != nil {1318		t.Errorf("Unexpected error: %v", err)1319	}13201321	checkStringContains(t, output, "root version 1.0.0")1322}13231324func TestVersionFlagOnlyAddedToRoot(t *testing.T) {1325	rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}1326	rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})13271328	_, err := executeCommand(rootCmd, "sub", "--version")1329	if err == nil {1330		t.Errorf("Expected error")1331	}13321333	checkStringContains(t, err.Error(), "unknown flag: --version")1334}13351336func TestShortVersionFlagOnlyAddedToRoot(t *testing.T) {1337	rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}1338	rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})13391340	_, err := executeCommand(rootCmd, "sub", "-v")1341	if err == nil {1342		t.Errorf("Expected error")1343	}13441345	checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v")1346}13471348func TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {1349	rootCmd := &Command{Use: "root", Run: emptyRun}13501351	_, err := executeCommand(rootCmd, "--version")1352	if err == nil {1353		t.Errorf("Expected error")1354	}1355	checkStringContains(t, err.Error(), "unknown flag: --version")1356}13571358func TestShorthandVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {1359	rootCmd := &Command{Use: "root", Run: emptyRun}13601361	_, err := executeCommand(rootCmd, "-v")1362	if err == nil {1363		t.Errorf("Expected error")1364	}1365	checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v")1366}13671368func TestShorthandVersionFlagOnlyAddedIfShorthandNotDefined(t *testing.T) {1369	rootCmd := &Command{Use: "root", Run: emptyRun, Version: "1.2.3"}1370	rootCmd.Flags().StringP("notversion", "v", "", "not a version flag")13711372	_, err := executeCommand(rootCmd, "-v")1373	if err == nil {1374		t.Errorf("Expected error")1375	}1376	check(t, rootCmd.Flags().ShorthandLookup("v").Name, "notversion")1377	checkStringContains(t, err.Error(), "flag needs an argument: 'v' in -v")1378}13791380func TestShorthandVersionFlagOnlyAddedIfVersionNotDefined(t *testing.T) {1381	rootCmd := &Command{Use: "root", Run: emptyRun, Version: "1.2.3"}1382	rootCmd.Flags().Bool("version", false, "a different kind of version flag")13831384	_, err := executeCommand(rootCmd, "-v")1385	if err == nil {1386		t.Errorf("Expected error")1387	}1388	checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v")1389}13901391func TestUsageIsNotPrintedTwice(t *testing.T) {1392	var cmd = &Command{Use: "root"}1393	var sub = &Command{Use: "sub"}1394	cmd.AddCommand(sub)13951396	output, _ := executeCommand(cmd, "")1397	if strings.Count(output, "Usage:") != 1 {1398		t.Error("Usage output is not printed exactly once")1399	}1400}14011402func TestVisitParents(t *testing.T) {1403	c := &Command{Use: "app"}1404	sub := &Command{Use: "sub"}1405	dsub := &Command{Use: "dsub"}1406	sub.AddCommand(dsub)1407	c.AddCommand(sub)14081409	total := 01410	add := func(x *Command) {1411		total++1412	}1413	sub.VisitParents(add)1414	if total != 1 {1415		t.Errorf("Should have visited 1 parent but visited %d", total)1416	}14171418	total = 01419	dsub.VisitParents(add)1420	if total != 2 {1421		t.Errorf("Should have visited 2 parents but visited %d", total)1422	}14231424	total = 01425	c.VisitParents(add)1426	if total != 0 {1427		t.Errorf("Should have visited no parents but visited %d", total)1428	}1429}14301431func TestSuggestions(t *testing.T) {1432	rootCmd := &Command{Use: "root", Run: emptyRun}1433	timesCmd := &Command{1434		Use:        "times",1435		SuggestFor: []string{"counts"},1436		Run:        emptyRun,1437	}1438	rootCmd.AddCommand(timesCmd)14391440	templateWithSuggestions := "Error: unknown command \"%s\" for \"root\"\n\nDid you mean this?\n\t%s\n\nRun 'root --help' for usage.\n"1441	templateWithoutSuggestions := "Error: unknown command \"%s\" for \"root\"\nRun 'root --help' for usage.\n"14421443	tests := map[string]string{1444		"time":     "times",1445		"tiems":    "times",1446		"tims":     "times",1447		"timeS":    "times",1448		"rimes":    "times",1449		"ti":       "times",1450		"t":        "times",1451		"timely":   "times",1452		"ri":       "",1453		"timezone": "",1454		"foo":      "",1455		"counts":   "times",1456	}14571458	for typo, suggestion := range tests {1459		for _, suggestionsDisabled := range []bool{true, false} {1460			rootCmd.DisableSuggestions = suggestionsDisabled14611462			var expected string1463			output, _ := executeCommand(rootCmd, typo)14641465			if suggestion == "" || suggestionsDisabled {1466				expected = fmt.Sprintf(templateWithoutSuggestions, typo)1467			} else {1468				expected = fmt.Sprintf(templateWithSuggestions, typo, suggestion)1469			}14701471			if output != expected {1472				t.Errorf("Unexpected response.\nExpected:\n %q\nGot:\n %q\n", expected, output)1473			}1474		}1475	}1476}14771478func TestCaseInsensitive(t *testing.T) {1479	rootCmd := &Command{Use: "root", Run: emptyRun}1480	childCmd := &Command{Use: "child", Run: emptyRun, Aliases: []string{"alternative"}}1481	granchildCmd := &Command{Use: "GRANDCHILD", Run: emptyRun, Aliases: []string{"ALIAS"}}14821483	childCmd.AddCommand(granchildCmd)1484	rootCmd.AddCommand(childCmd)14851486	tests := []struct {1487		args                []string1488		failWithoutEnabling bool1489	}{1490		{1491			args:                []string{"child"},1492			failWithoutEnabling: false,1493		},1494		{1495			args:                []string{"CHILD"},1496			failWithoutEnabling: true,1497		},1498		{1499			args:                []string{"chILD"},1500			failWithoutEnabling: true,1501		},1502		{1503			args:                []string{"CHIld"},1504			failWithoutEnabling: true,1505		},1506		{1507			args:                []string{"alternative"},1508			failWithoutEnabling: false,1509		},1510		{1511			args:                []string{"ALTERNATIVE"},1512			failWithoutEnabling: true,1513		},1514		{1515			args:                []string{"ALTernatIVE"},1516			failWithoutEnabling: true,1517		},1518		{1519			args:                []string{"alternatiVE"},1520			failWithoutEnabling: true,1521		},1522		{1523			args:                []string{"child", "GRANDCHILD"},1524			failWithoutEnabling: false,1525		},1526		{1527			args:                []string{"child", "grandchild"},1528			failWithoutEnabling: true,1529		},1530		{1531			args:                []string{"CHIld", "GRANdchild"},1532			failWithoutEnabling: true,1533		},1534		{1535			args:                []string{"alternative", "ALIAS"},1536			failWithoutEnabling: false,1537		},1538		{1539			args:                []string{"alternative", "alias"},1540			failWithoutEnabling: true,1541		},1542		{1543			args:                []string{"CHILD", "alias"},1544			failWithoutEnabling: true,1545		},1546		{1547			args:                []string{"CHIld", "aliAS"},1548			failWithoutEnabling: true,1549		},1550	}15511552	for _, test := range tests {1553		for _, enableCaseInsensitivity := range []bool{true, false} {1554			EnableCaseInsensitive = enableCaseInsensitivity15551556			output, err := executeCommand(rootCmd, test.args...)1557			expectedFailure := test.failWithoutEnabling && !enableCaseInsensitivity15581559			if !expectedFailure && output != "" {1560				t.Errorf("Unexpected output: %v", output)1561			}1562			if !expectedFailure && err != nil {1563				t.Errorf("Unexpected error: %v", err)1564			}1565		}1566	}15671568	EnableCaseInsensitive = defaultCaseInsensitive1569}15701571// This test make sure we keep backwards-compatibility with respect1572// to command names case sensitivity behavior.1573func TestCaseSensitivityBackwardCompatibility(t *testing.T) {1574	rootCmd := &Command{Use: "root", Run: emptyRun}1575	childCmd := &Command{Use: "child", Run: emptyRun}15761577	rootCmd.AddCommand(childCmd)1578	_, err := executeCommand(rootCmd, strings.ToUpper(childCmd.Use))1579	if err == nil {1580		t.Error("Expected error on calling a command in upper case while command names are case sensitive. Got nil.")1581	}15821583}15841585func TestRemoveCommand(t *testing.T) {1586	rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1587	childCmd := &Command{Use: "child", Run: emptyRun}1588	rootCmd.AddCommand(childCmd)1589	rootCmd.RemoveCommand(childCmd)15901591	_, err := executeCommand(rootCmd, "child")1592	if err == nil {1593		t.Error("Expected error on calling removed command. Got nil.")1594	}1595}15961597func TestReplaceCommandWithRemove(t *testing.T) {1598	childUsed := 01599	rootCmd := &Command{Use: "root", Run: emptyRun}1600	child1Cmd := &Command{1601		Use: "child",1602		Run: func(*Command, []string) { childUsed = 1 },1603	}1604	child2Cmd := &Command{1605		Use: "child",1606		Run: func(*Command, []string) { childUsed = 2 },1607	}1608	rootCmd.AddCommand(child1Cmd)1609	rootCmd.RemoveCommand(child1Cmd)1610	rootCmd.AddCommand(child2Cmd)16111612	output, err := executeCommand(rootCmd, "child")1613	if output != "" {1614		t.Errorf("Unexpected output: %v", output)1615	}1616	if err != nil {1617		t.Errorf("Unexpected error: %v", err)1618	}16191620	if childUsed == 1 {1621		t.Error("Removed command shouldn't be called")1622	}1623	if childUsed != 2 {1624		t.Error("Replacing command should have been called but didn't")1625	}1626}16271628func TestDeprecatedCommand(t *testing.T) {1629	rootCmd := &Command{Use: "root", Run: emptyRun}1630	deprecatedCmd := &Command{1631		Use:        "deprecated",1632		Deprecated: "This command is deprecated",1633		Run:        emptyRun,1634	}1635	rootCmd.AddCommand(deprecatedCmd)16361637	output, err := executeCommand(rootCmd, "deprecated")1638	if err != nil {1639		t.Errorf("Unexpected error: %v", err)1640	}16411642	checkStringContains(t, output, deprecatedCmd.Deprecated)1643}16441645func TestHooks(t *testing.T) {1646	var (1647		persPreArgs  string1648		preArgs      string1649		runArgs      string1650		postArgs     string1651		persPostArgs string1652	)16531654	c := &Command{1655		Use: "c",1656		PersistentPreRun: func(_ *Command, args []string) {1657			persPreArgs = strings.Join(args, " ")1658		},1659		PreRun: func(_ *Command, args []string) {1660			preArgs = strings.Join(args, " ")1661		},1662		Run: func(_ *Command, args []string) {1663			runArgs = strings.Join(args, " ")1664		},1665		PostRun: func(_ *Command, args []string) {1666			postArgs = strings.Join(args, " ")1667		},1668		PersistentPostRun: func(_ *Command, args []string) {1669			persPostArgs = strings.Join(args, " ")1670		},1671	}16721673	output, err := executeCommand(c, "one", "two")1674	if output != "" {1675		t.Errorf("Unexpected output: %v", output)1676	}1677	if err != nil {1678		t.Errorf("Unexpected error: %v", err)1679	}16801681	for _, v := range []struct {1682		name string1683		got  string1684	}{1685		{"persPreArgs", persPreArgs},1686		{"preArgs", preArgs},1687		{"runArgs", runArgs},1688		{"postArgs", postArgs},1689		{"persPostArgs", persPostArgs},1690	} {1691		if v.got != onetwo {1692			t.Errorf("Expected %s %q, got %q", v.name, onetwo, v.got)1693		}1694	}1695}16961697func TestPersistentHooks(t *testing.T) {1698	EnableTraverseRunHooks = true1699	testPersistentHooks(t, []string{1700		"parent PersistentPreRun",1701		"child PersistentPreRun",1702		"child PreRun",1703		"child Run",1704		"child PostRun",1705		"child PersistentPostRun",1706		"parent PersistentPostRun",1707	})17081709	EnableTraverseRunHooks = false1710	testPersistentHooks(t, []string{1711		"child PersistentPreRun",1712		"child PreRun",1713		"child Run",1714		"child PostRun",1715		"child PersistentPostRun",1716	})1717}17181719func testPersistentHooks(t *testing.T, expectedHookRunOrder []string) {1720	var hookRunOrder []string17211722	validateHook := func(args []string, hookName string) {1723		hookRunOrder = append(hookRunOrder, hookName)1724		got := strings.Join(args, " ")1725		if onetwo != got {1726			t.Errorf("Expected %s %q, got %q", hookName, onetwo, got)1727		}1728	}17291730	parentCmd := &Command{1731		Use: "parent",1732		PersistentPreRun: func(_ *Command, args []string) {1733			validateHook(args, "parent PersistentPreRun")1734		},1735		PreRun: func(_ *Command, args []string) {1736			validateHook(args, "parent PreRun")1737		},1738		Run: func(_ *Command, args []string) {1739			validateHook(args, "parent Run")1740		},1741		PostRun: func(_ *Command, args []string) {1742			validateHook(args, "parent PostRun")1743		},1744		PersistentPostRun: func(_ *Command, args []string) {1745			validateHook(args, "parent PersistentPostRun")1746		},1747	}17481749	childCmd := &Command{1750		Use: "child",1751		PersistentPreRun: func(_ *Command, args []string) {1752			validateHook(args, "child PersistentPreRun")1753		},1754		PreRun: func(_ *Command, args []string) {1755			validateHook(args, "child PreRun")1756		},1757		Run: func(_ *Command, args []string) {1758			validateHook(args, "child Run")1759		},1760		PostRun: func(_ *Command, args []string) {1761			validateHook(args, "child PostRun")1762		},1763		PersistentPostRun: func(_ *Command, args []string) {1764			validateHook(args, "child PersistentPostRun")1765		},1766	}1767	parentCmd.AddCommand(childCmd)17681769	output, err := executeCommand(parentCmd, "child", "one", "two")1770	if output != "" {1771		t.Errorf("Unexpected output: %v", output)1772	}1773	if err != nil {1774		t.Errorf("Unexpected error: %v", err)1775	}17761777	for idx, exp := range expectedHookRunOrder {1778		if len(hookRunOrder) > idx {1779			if act := hookRunOrder[idx]; act != exp {1780				t.Errorf("Expected %q at %d, got %q", exp, idx, act)1781			}1782		} else {1783			t.Errorf("Expected %q at %d, got nothing", exp, idx)1784		}1785	}1786}17871788// Related to https://github.com/spf13/cobra/issues/521.1789func TestGlobalNormFuncPropagation(t *testing.T) {1790	normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1791		return pflag.NormalizedName(name)1792	}17931794	rootCmd := &Command{Use: "root", Run: emptyRun}1795	childCmd := &Command{Use: "child", Run: emptyRun}1796	rootCmd.AddCommand(childCmd)17971798	rootCmd.SetGlobalNormalizationFunc(normFunc)1799	if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {1800		t.Error("rootCmd seems to have a wrong normalization function")1801	}18021803	if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(childCmd.GlobalNormalizationFunc()).Pointer() {1804		t.Error("childCmd should have had the normalization function of rootCmd")1805	}1806}18071808// Related to https://github.com/spf13/cobra/issues/521.1809func TestNormPassedOnLocal(t *testing.T) {1810	toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1811		return pflag.NormalizedName(strings.ToUpper(name))1812	}18131814	c := &Command{}1815	c.Flags().Bool("flagname", true, "this is a dummy flag")1816	c.SetGlobalNormalizationFunc(toUpper)1817	if c.LocalFlags().Lookup("flagname") != c.LocalFlags().Lookup("FLAGNAME") {1818		t.Error("Normalization function should be passed on to Local flag set")1819	}1820}18211822// Related to https://github.com/spf13/cobra/issues/521.1823func TestNormPassedOnInherited(t *testing.T) {1824	toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1825		return pflag.NormalizedName(strings.ToUpper(name))1826	}18271828	c := &Command{}1829	c.SetGlobalNormalizationFunc(toUpper)18301831	child1 := &Command{}1832	c.AddCommand(child1)18331834	c.PersistentFlags().Bool("flagname", true, "")18351836	child2 := &Command{}1837	c.AddCommand(child2)18381839	inherited := child1.InheritedFlags()1840	if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") {1841		t.Error("Normalization function should be passed on to inherited flag set in command added before flag")1842	}18431844	inherited = child2.InheritedFlags()1845	if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") {1846		t.Error("Normalization function should be passed on to inherited flag set in command added after flag")1847	}1848}18491850// Related to https://github.com/spf13/cobra/issues/521.1851func TestConsistentNormalizedName(t *testing.T) {1852	toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1853		return pflag.NormalizedName(strings.ToUpper(name))1854	}1855	n := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1856		return pflag.NormalizedName(name)1857	}18581859	c := &Command{}1860	c.Flags().Bool("flagname", true, "")1861	c.SetGlobalNormalizationFunc(toUpper)1862	c.SetGlobalNormalizationFunc(n)18631864	if c.LocalFlags().Lookup("flagname") == c.LocalFlags().Lookup("FLAGNAME") {1865		t.Error("Normalizing flag names should not result in duplicate flags")1866	}1867}18681869func TestFlagOnPflagCommandLine(t *testing.T) {1870	flagName := "flagOnCommandLine"1871	pflag.String(flagName, "", "about my flag")18721873	c := &Command{Use: "c", Run: emptyRun}1874	c.AddCommand(&Command{Use: "child", Run: emptyRun})18751876	output, _ := executeCommand(c, "--help")1877	checkStringContains(t, output, flagName)18781879	resetCommandLineFlagSet()1880}18811882// TestHiddenCommandExecutes checks,1883// if hidden commands run as intended.1884func TestHiddenCommandExecutes(t *testing.T) {1885	executed := false1886	c := &Command{1887		Use:    "c",1888		Hidden: true,1889		Run:    func(*Command, []string) { executed = true },1890	}18911892	output, err := executeCommand(c)1893	if output != "" {1894		t.Errorf("Unexpected output: %v", output)1895	}1896	if err != nil {1897		t.Errorf("Unexpected error: %v", err)1898	}18991900	if !executed {1901		t.Error("Hidden command should have been executed")1902	}1903}19041905// test to ensure hidden commands do not show up in usage/help text1906func TestHiddenCommandIsHidden(t *testing.T) {1907	c := &Command{Use: "c", Hidden: true, Run: emptyRun}1908	if c.IsAvailableCommand() {1909		t.Errorf("Hidden command should be unavailable")1910	}1911}19121913func TestCommandsAreSorted(t *testing.T) {1914	EnableCommandSorting = true19151916	originalNames := []string{"middle", "zlast", "afirst"}1917	expectedNames := []string{"afirst", "middle", "zlast"}19181919	var rootCmd = &Command{Use: "root"}19201921	for _, name := range originalNames {1922		rootCmd.AddCommand(&Command{Use: name})1923	}19241925	for i, c := range rootCmd.Commands() {1926		got := c.Name()1927		if expectedNames[i] != got {1928			t.Errorf("Expected: %s, got: %s", expectedNames[i], got)1929		}1930	}19311932	EnableCommandSorting = defaultCommandSorting1933}19341935func TestEnableCommandSortingIsDisabled(t *testing.T) {1936	EnableCommandSorting = false19371938	originalNames := []string{"middle", "zlast", "afirst"}19391940	var rootCmd = &Command{Use: "root"}19411942	for _, name := range originalNames {1943		rootCmd.AddCommand(&Command{Use: name})1944	}19451946	for i, c := range rootCmd.Commands() {1947		got := c.Name()1948		if originalNames[i] != got {1949			t.Errorf("expected: %s, got: %s", originalNames[i], got)1950		}1951	}19521953	EnableCommandSorting = defaultCommandSorting1954}19551956func TestUsageWithGroup(t *testing.T) {1957	var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}1958	rootCmd.CompletionOptions.DisableDefaultCmd = true19591960	rootCmd.AddGroup(&Group{ID: "group1", Title: "group1"})1961	rootCmd.AddGroup(&Group{ID: "group2", Title: "group2"})19621963	rootCmd.AddCommand(&Command{Use: "cmd1", GroupID: "group1", Run: emptyRun})1964	rootCmd.AddCommand(&Command{Use: "cmd2", GroupID: "group2", Run: emptyRun})19651966	output, err := executeCommand(rootCmd, "--help")1967	if err != nil {1968		t.Errorf("Unexpected error: %v", err)1969	}19701971	// help should be ungrouped here1972	checkStringContains(t, output, "\nAdditional Commands:\n  help")1973	checkStringContains(t, output, "\ngroup1\n  cmd1")1974	checkStringContains(t, output, "\ngroup2\n  cmd2")1975}19761977func TestUsageHelpGroup(t *testing.T) {1978	var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}1979	rootCmd.CompletionOptions.DisableDefaultCmd = true19801981	rootCmd.AddGroup(&Group{ID: "group", Title: "group"})1982	rootCmd.AddCommand(&Command{Use: "xxx", GroupID: "group", Run: emptyRun})1983	rootCmd.SetHelpCommandGroupID("group")19841985	output, err := executeCommand(rootCmd, "--help")1986	if err != nil {1987		t.Errorf("Unexpected error: %v", err)1988	}19891990	// now help should be grouped under "group"1991	checkStringOmits(t, output, "\nAdditional Commands:\n  help")1992	checkStringContains(t, output, "\ngroup\n  help")1993}19941995func TestUsageCompletionGroup(t *testing.T) {1996	var rootCmd = &Command{Use: "root", Short: "test", Run: emptyRun}19971998	rootCmd.AddGroup(&Group{ID: "group", Title: "group"})1999	rootCmd.AddGroup(&Group{ID: "help", Title: "help"})2000

The first 2,000 of 2,954 lines.