Skip to content
Myr

flag_groups_test.go

This file

Path

flag_groups_test.go

151 lines · 6.3 KiB · Go

Last changed by

Add ability to mark flags as required or exclusive as a group (#1654)John Schnakebefore adoption68b6b24

History of this file

Take it

1// Copyright © 2022 Steve Francia <spf@spf13.com>.2//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// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.1314package cobra1516import (17	"strings"18	"testing"19)2021func TestValidateFlagGroups(t *testing.T) {22	getCmd := func() *Command {23		c := &Command{24			Use: "testcmd",25			Run: func(cmd *Command, args []string) {26			}}27		// Define lots of flags to utilize for testing.28		for _, v := range []string{"a", "b", "c", "d"} {29			c.Flags().String(v, "", "")30		}31		for _, v := range []string{"e", "f", "g"} {32			c.PersistentFlags().String(v, "", "")33		}34		subC := &Command{35			Use: "subcmd",36			Run: func(cmd *Command, args []string) {37			}}38		subC.Flags().String("subonly", "", "")39		c.AddCommand(subC)40		return c41	}4243	// Each test case uses a unique command from the function above.44	testcases := []struct {45		desc                      string46		flagGroupsRequired        []string47		flagGroupsExclusive       []string48		subCmdFlagGroupsRequired  []string49		subCmdFlagGroupsExclusive []string50		args                      []string51		expectErr                 string52	}{53		{54			desc: "No flags no problem",55		}, {56			desc:                "No flags no problem even with conflicting groups",57			flagGroupsRequired:  []string{"a b"},58			flagGroupsExclusive: []string{"a b"},59		}, {60			desc:               "Required flag group not satisfied",61			flagGroupsRequired: []string{"a b c"},62			args:               []string{"--a=foo"},63			expectErr:          "if any flags in the group [a b c] are set they must all be set; missing [b c]",64		}, {65			desc:                "Exclusive flag group not satisfied",66			flagGroupsExclusive: []string{"a b c"},67			args:                []string{"--a=foo", "--b=foo"},68			expectErr:           "if any flags in the group [a b c] are set none of the others can be; [a b] were all set",69		}, {70			desc:               "Multiple required flag group not satisfied returns first error",71			flagGroupsRequired: []string{"a b c", "a d"},72			args:               []string{"--c=foo", "--d=foo"},73			expectErr:          `if any flags in the group [a b c] are set they must all be set; missing [a b]`,74		}, {75			desc:                "Multiple exclusive flag group not satisfied returns first error",76			flagGroupsExclusive: []string{"a b c", "a d"},77			args:                []string{"--a=foo", "--c=foo", "--d=foo"},78			expectErr:           `if any flags in the group [a b c] are set none of the others can be; [a c] were all set`,79		}, {80			desc:               "Validation of required groups occurs on groups in sorted order",81			flagGroupsRequired: []string{"a d", "a b", "a c"},82			args:               []string{"--a=foo"},83			expectErr:          `if any flags in the group [a b] are set they must all be set; missing [b]`,84		}, {85			desc:                "Validation of exclusive groups occurs on groups in sorted order",86			flagGroupsExclusive: []string{"a d", "a b", "a c"},87			args:                []string{"--a=foo", "--b=foo", "--c=foo"},88			expectErr:           `if any flags in the group [a b] are set none of the others can be; [a b] were all set`,89		}, {90			desc:                "Persistent flags utilize both features and can fail required groups",91			flagGroupsRequired:  []string{"a e", "e f"},92			flagGroupsExclusive: []string{"f g"},93			args:                []string{"--a=foo", "--f=foo", "--g=foo"},94			expectErr:           `if any flags in the group [a e] are set they must all be set; missing [e]`,95		}, {96			desc:                "Persistent flags utilize both features and can fail mutually exclusive groups",97			flagGroupsRequired:  []string{"a e", "e f"},98			flagGroupsExclusive: []string{"f g"},99			args:                []string{"--a=foo", "--e=foo", "--f=foo", "--g=foo"},100			expectErr:           `if any flags in the group [f g] are set none of the others can be; [f g] were all set`,101		}, {102			desc:                "Persistent flags utilize both features and can pass",103			flagGroupsRequired:  []string{"a e", "e f"},104			flagGroupsExclusive: []string{"f g"},105			args:                []string{"--a=foo", "--e=foo", "--f=foo"},106		}, {107			desc:                     "Subcmds can use required groups using inherited flags",108			subCmdFlagGroupsRequired: []string{"e subonly"},109			args:                     []string{"subcmd", "--e=foo", "--subonly=foo"},110		}, {111			desc:                      "Subcmds can use exclusive groups using inherited flags",112			subCmdFlagGroupsExclusive: []string{"e subonly"},113			args:                      []string{"subcmd", "--e=foo", "--subonly=foo"},114			expectErr:                 "if any flags in the group [e subonly] are set none of the others can be; [e subonly] were all set",115		}, {116			desc:                      "Subcmds can use exclusive groups using inherited flags and pass",117			subCmdFlagGroupsExclusive: []string{"e subonly"},118			args:                      []string{"subcmd", "--e=foo"},119		}, {120			desc:                     "Flag groups not applied if not found on invoked command",121			subCmdFlagGroupsRequired: []string{"e subonly"},122			args:                     []string{"--e=foo"},123		},124	}125	for _, tc := range testcases {126		t.Run(tc.desc, func(t *testing.T) {127			c := getCmd()128			sub := c.Commands()[0]129			for _, flagGroup := range tc.flagGroupsRequired {130				c.MarkFlagsRequiredTogether(strings.Split(flagGroup, " ")...)131			}132			for _, flagGroup := range tc.flagGroupsExclusive {133				c.MarkFlagsMutuallyExclusive(strings.Split(flagGroup, " ")...)134			}135			for _, flagGroup := range tc.subCmdFlagGroupsRequired {136				sub.MarkFlagsRequiredTogether(strings.Split(flagGroup, " ")...)137			}138			for _, flagGroup := range tc.subCmdFlagGroupsExclusive {139				sub.MarkFlagsMutuallyExclusive(strings.Split(flagGroup, " ")...)140			}141			c.SetArgs(tc.args)142			err := c.Execute()143			switch {144			case err == nil && len(tc.expectErr) > 0:145				t.Errorf("Expected error %q but got nil", tc.expectErr)146			case err != nil && err.Error() != tc.expectErr:147				t.Errorf("Expected error %q but got %q", tc.expectErr, err)148			}149		})150	}151}