Skip to content
Myr

command_test.go

This file

Path

command_test.go

300 lines · 7.1 KiB · Go

Last changed by

Fix incorrect merge of pflag.CommandLine to cmd.Flags()Albert Nigmatzianovbefore adoption7d22e77

History of this file

Take it

1package cobra23import (4	"bytes"5	"fmt"6	"os"7	"reflect"8	"strings"9	"testing"1011	"github.com/spf13/pflag"12)1314// test to ensure hidden commands run as intended15func TestHiddenCommandExecutes(t *testing.T) {1617	// ensure that outs does not already equal what the command will be setting it18	// to, if it did this test would not actually be testing anything...19	if outs == "hidden" {20		t.Errorf("outs should NOT EQUAL hidden")21	}2223	cmdHidden.Execute()2425	// upon running the command, the value of outs should now be 'hidden'26	if outs != "hidden" {27		t.Errorf("Hidden command failed to run!")28	}29}3031// test to ensure hidden commands do not show up in usage/help text32func TestHiddenCommandIsHidden(t *testing.T) {33	if cmdHidden.IsAvailableCommand() {34		t.Errorf("Hidden command found!")35	}36}3738func TestStripFlags(t *testing.T) {39	tests := []struct {40		input  []string41		output []string42	}{43		{44			[]string{"foo", "bar"},45			[]string{"foo", "bar"},46		},47		{48			[]string{"foo", "--bar", "-b"},49			[]string{"foo"},50		},51		{52			[]string{"-b", "foo", "--bar", "bar"},53			[]string{},54		},55		{56			[]string{"-i10", "echo"},57			[]string{"echo"},58		},59		{60			[]string{"-i=10", "echo"},61			[]string{"echo"},62		},63		{64			[]string{"--int=100", "echo"},65			[]string{"echo"},66		},67		{68			[]string{"-ib", "echo", "-bfoo", "baz"},69			[]string{"echo", "baz"},70		},71		{72			[]string{"-i=baz", "bar", "-i", "foo", "blah"},73			[]string{"bar", "blah"},74		},75		{76			[]string{"--int=baz", "-bbar", "-i", "foo", "blah"},77			[]string{"blah"},78		},79		{80			[]string{"--cat", "bar", "-i", "foo", "blah"},81			[]string{"bar", "blah"},82		},83		{84			[]string{"-c", "bar", "-i", "foo", "blah"},85			[]string{"bar", "blah"},86		},87		{88			[]string{"--persist", "bar"},89			[]string{"bar"},90		},91		{92			[]string{"-p", "bar"},93			[]string{"bar"},94		},95	}9697	cmdPrint := &Command{98		Use:   "print [string to print]",99		Short: "Print anything to the screen",100		Long:  `an utterly useless command for testing.`,101		Run: func(cmd *Command, args []string) {102			tp = args103		},104	}105106	var flagi int107	var flagstr string108	var flagbool bool109	cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one")110	cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int")111	cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string")112	cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool")113114	for _, test := range tests {115		output := stripFlags(test.input, cmdPrint)116		if !reflect.DeepEqual(test.output, output) {117			t.Errorf("expected: %v, got: %v", test.output, output)118		}119	}120}121122func TestDisableFlagParsing(t *testing.T) {123	as := []string{"-v", "-race", "-file", "foo.go"}124	targs := []string{}125	cmdPrint := &Command{126		DisableFlagParsing: true,127		Run: func(cmd *Command, args []string) {128			targs = args129		},130	}131	osargs := []string{"cmd"}132	os.Args = append(osargs, as...)133	err := cmdPrint.Execute()134	if err != nil {135		t.Error(err)136	}137	if !reflect.DeepEqual(as, targs) {138		t.Errorf("expected: %v, got: %v", as, targs)139	}140}141142func TestInitHelpFlagMergesFlags(t *testing.T) {143	usage := "custom flag"144	baseCmd := Command{Use: "testcmd"}145	baseCmd.PersistentFlags().Bool("help", false, usage)146	cmd := Command{Use: "do"}147	baseCmd.AddCommand(&cmd)148149	cmd.InitDefaultHelpFlag()150	actual := cmd.Flags().Lookup("help").Usage151	if actual != usage {152		t.Fatalf("Expected the help flag from the base command with usage '%s', but got the default with usage '%s'", usage, actual)153	}154}155156func TestCommandsAreSorted(t *testing.T) {157	EnableCommandSorting = true158159	originalNames := []string{"middle", "zlast", "afirst"}160	expectedNames := []string{"afirst", "middle", "zlast"}161162	var tmpCommand = &Command{Use: "tmp"}163164	for _, name := range originalNames {165		tmpCommand.AddCommand(&Command{Use: name})166	}167168	for i, c := range tmpCommand.Commands() {169		if expectedNames[i] != c.Name() {170			t.Errorf("expected: %s, got: %s", expectedNames[i], c.Name())171		}172	}173174	EnableCommandSorting = true175}176177func TestEnableCommandSortingIsDisabled(t *testing.T) {178	EnableCommandSorting = false179180	originalNames := []string{"middle", "zlast", "afirst"}181182	var tmpCommand = &Command{Use: "tmp"}183184	for _, name := range originalNames {185		tmpCommand.AddCommand(&Command{Use: name})186	}187188	for i, c := range tmpCommand.Commands() {189		if originalNames[i] != c.Name() {190			t.Errorf("expected: %s, got: %s", originalNames[i], c.Name())191		}192	}193194	EnableCommandSorting = true195}196197func TestSetOutput(t *testing.T) {198	cmd := &Command{}199	cmd.SetOutput(nil)200	if out := cmd.OutOrStdout(); out != os.Stdout {201		t.Fatalf("expected setting output to nil to revert back to stdout, got %v", out)202	}203}204205func TestFlagErrorFunc(t *testing.T) {206	cmd := &Command{207		Use: "print",208		RunE: func(cmd *Command, args []string) error {209			return nil210		},211	}212	expectedFmt := "This is expected: %s"213214	cmd.SetFlagErrorFunc(func(c *Command, err error) error {215		return fmt.Errorf(expectedFmt, err)216	})217	cmd.SetArgs([]string{"--bogus-flag"})218	cmd.SetOutput(new(bytes.Buffer))219220	err := cmd.Execute()221222	expected := fmt.Sprintf(expectedFmt, "unknown flag: --bogus-flag")223	if err.Error() != expected {224		t.Errorf("expected %v, got %v", expected, err.Error())225	}226}227228// TestSortedFlags checks,229// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.230// Related to https://github.com/spf13/cobra/issues/404.231func TestSortedFlags(t *testing.T) {232	cmd := &Command{}233	cmd.Flags().SortFlags = false234	names := []string{"C", "B", "A", "D"}235	for _, name := range names {236		cmd.Flags().Bool(name, false, "")237	}238239	i := 0240	cmd.LocalFlags().VisitAll(func(f *pflag.Flag) {241		if i == len(names) {242			return243		}244		if isStringInStringSlice(f.Name, names) {245			if names[i] != f.Name {246				t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name)247			}248			i++249		}250	})251}252253// contains checks, if s is in ss.254func isStringInStringSlice(s string, ss []string) bool {255	for _, v := range ss {256		if v == s {257			return true258		}259	}260	return false261}262263// TestHelpFlagInHelp checks,264// if '--help' flag is shown in help for child (executing `parent help child`),265// that has no other flags.266// Related to https://github.com/spf13/cobra/issues/302.267func TestHelpFlagInHelp(t *testing.T) {268	output := new(bytes.Buffer)269	parent := &Command{Use: "parent", Run: func(*Command, []string) {}}270	parent.SetOutput(output)271272	child := &Command{Use: "child", Run: func(*Command, []string) {}}273	parent.AddCommand(child)274275	parent.SetArgs([]string{"help", "child"})276	err := parent.Execute()277	if err != nil {278		t.Fatal(err)279	}280281	if !strings.Contains(output.String(), "[flags]") {282		t.Errorf("\nExpecting to contain: %v\nGot: %v", "[flags]", output.String())283	}284}285286// TestMergeCommandLineToFlags checks,287// if pflag.CommandLine is correctly merged to c.Flags() after first call288// of c.mergePersistentFlags.289// Related to https://github.com/spf13/cobra/issues/443.290func TestMergeCommandLineToFlags(t *testing.T) {291	pflag.Bool("boolflag", false, "")292	c := &Command{Use: "c", Run: func(*Command, []string) {}}293	c.mergePersistentFlags()294	if c.Flags().Lookup("boolflag") == nil {295		t.Fatal("Expecting to have flag from CommandLine in c.Flags()")296	}297298	// Reset pflag.CommandLine flagset.299	pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)300}