Deprecate ExactValidArgs() and test combinations of args validators (#1643)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* deprecate ExactValidArgs in favour of MatchAll(OnlyValidArgs, ...) * test combinations of args validators * adjust docs
authored by Unai Martinez-Corral · committed by GitHub · parent 2e8ba6f · Browse files · 3 files·+270 added−52 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+270 added−52 removed
- other:+270 added−52 removed
Provenance
- Commit
70e53f6- Tree
6677bf4- Author
Unai Martinez-Corral <38422348+umarcor@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
2e8ba6f
3 files changed+270 added−52 removed
modified:args_test.go+226 added-22 removed
25 unmodified lines26 t.Fatalf("Unexpected error: %v", err)27 }28 }29 30-func validWithInvalidArgs(err error, t *testing.T) {30+func validOnlyWithInvalidArgs(err error, t *testing.T) {31 if err == nil {32 t.Fatal("Expected an error")33 }34 got := err.Error()2 unmodified lines37 t.Errorf("Expected: %q, got: %q", expected, got)38 }39 }40 41-func noArgsWithArgs(err error, t *testing.T) {41+func noArgsWithArgs(err error, t *testing.T, arg string) {42 if err == nil {43 t.Fatal("Expected an error")44 }45 got := err.Error()46- expected := `unknown command "illegal" for "c"`46+ expected := `unknown command "` + arg + `" for "c"`47 if got != expected {48 t.Errorf("Expected: %q, got: %q", expected, got)49 }50 }41 unmodified lines92 t.Fatalf("Expected %q, got %q", expected, got)93 }94 }95 96+// NoArgs97+98 func TestNoArgs(t *testing.T) {99 c := getCommand(NoArgs, false)100 output, err := executeCommand(c)101 expectSuccess(output, err, t)102 }103 102-func TestNoArgsWithArgs(t *testing.T) {104+func TestNoArgs_WithArgs(t *testing.T) {105 c := getCommand(NoArgs, false)104- _, err := executeCommand(c, "illegal")105- noArgsWithArgs(err, t)106+ _, err := executeCommand(c, "one")107+ noArgsWithArgs(err, t, "one")108 }109 110+func TestNoArgs_WithValid_WithArgs(t *testing.T) {111+ c := getCommand(NoArgs, true)112+ _, err := executeCommand(c, "one")113+ noArgsWithArgs(err, t, "one")114+}115+116+func TestNoArgs_WithValid_WithInvalidArgs(t *testing.T) {117+ c := getCommand(NoArgs, true)118+ _, err := executeCommand(c, "a")119+ noArgsWithArgs(err, t, "a")120+}121+122+func TestNoArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {123+ c := getCommand(MatchAll(OnlyValidArgs, NoArgs), true)124+ _, err := executeCommand(c, "a")125+ validOnlyWithInvalidArgs(err, t)126+}127+128+// OnlyValidArgs129+130 func TestOnlyValidArgs(t *testing.T) {131 c := getCommand(OnlyValidArgs, true)132 output, err := executeCommand(c, "one", "two")133 expectSuccess(output, err, t)134 }135 114-func TestOnlyValidArgsWithInvalidArgs(t *testing.T) {136+func TestOnlyValidArgs_WithInvalidArgs(t *testing.T) {137 c := getCommand(OnlyValidArgs, true)138 _, err := executeCommand(c, "a")117- validWithInvalidArgs(err, t)139+ validOnlyWithInvalidArgs(err, t)140 }141 142+// ArbitraryArgs143+144 func TestArbitraryArgs(t *testing.T) {145 c := getCommand(ArbitraryArgs, false)146 output, err := executeCommand(c, "a", "b")147 expectSuccess(output, err, t)148 }149 150+func TestArbitraryArgs_WithValid(t *testing.T) {151+ c := getCommand(ArbitraryArgs, true)152+ output, err := executeCommand(c, "one", "two")153+ expectSuccess(output, err, t)154+}155+156+func TestArbitraryArgs_WithValid_WithInvalidArgs(t *testing.T) {157+ c := getCommand(ArbitraryArgs, true)158+ output, err := executeCommand(c, "a")159+ expectSuccess(output, err, t)160+}161+162+func TestArbitraryArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {163+ c := getCommand(MatchAll(OnlyValidArgs, ArbitraryArgs), true)164+ _, err := executeCommand(c, "a")165+ validOnlyWithInvalidArgs(err, t)166+}167+168+// MinimumNArgs169+170 func TestMinimumNArgs(t *testing.T) {171 c := getCommand(MinimumNArgs(2), false)172 output, err := executeCommand(c, "a", "b", "c")173 expectSuccess(output, err, t)174 }175 132-func TestMinimumNArgsWithLessArgs(t *testing.T) {176+func TestMinimumNArgs_WithValid(t *testing.T) {177+ c := getCommand(MinimumNArgs(2), true)178+ output, err := executeCommand(c, "one", "three")179+ expectSuccess(output, err, t)180+}181+182+func TestMinimumNArgs_WithValid__WithInvalidArgs(t *testing.T) {183+ c := getCommand(MinimumNArgs(2), true)184+ output, err := executeCommand(c, "a", "b")185+ expectSuccess(output, err, t)186+}187+188+func TestMinimumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {189+ c := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true)190+ _, err := executeCommand(c, "a", "b")191+ validOnlyWithInvalidArgs(err, t)192+}193+194+func TestMinimumNArgs_WithLessArgs(t *testing.T) {195 c := getCommand(MinimumNArgs(2), false)196 _, err := executeCommand(c, "a")197 minimumNArgsWithLessArgs(err, t)198 }199 200+func TestMinimumNArgs_WithLessArgs_WithValid(t *testing.T) {201+ c := getCommand(MinimumNArgs(2), true)202+ _, err := executeCommand(c, "one")203+ minimumNArgsWithLessArgs(err, t)204+}205+206+func TestMinimumNArgs_WithLessArgs_WithValid_WithInvalidArgs(t *testing.T) {207+ c := getCommand(MinimumNArgs(2), true)208+ _, err := executeCommand(c, "a")209+ minimumNArgsWithLessArgs(err, t)210+}211+212+func TestMinimumNArgs_WithLessArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {213+ c := getCommand(MatchAll(OnlyValidArgs, MinimumNArgs(2)), true)214+ _, err := executeCommand(c, "a")215+ validOnlyWithInvalidArgs(err, t)216+}217+218+// MaximumNArgs219+220 func TestMaximumNArgs(t *testing.T) {221 c := getCommand(MaximumNArgs(3), false)222 output, err := executeCommand(c, "a", "b")223 expectSuccess(output, err, t)224 }225 144-func TestMaximumNArgsWithMoreArgs(t *testing.T) {226+func TestMaximumNArgs_WithValid(t *testing.T) {227+ c := getCommand(MaximumNArgs(2), true)228+ output, err := executeCommand(c, "one", "three")229+ expectSuccess(output, err, t)230+}231+232+func TestMaximumNArgs_WithValid_WithInvalidArgs(t *testing.T) {233+ c := getCommand(MaximumNArgs(2), true)234+ output, err := executeCommand(c, "a", "b")235+ expectSuccess(output, err, t)236+}237+238+func TestMaximumNArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {239+ c := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true)240+ _, err := executeCommand(c, "a", "b")241+ validOnlyWithInvalidArgs(err, t)242+}243+244+func TestMaximumNArgs_WithMoreArgs(t *testing.T) {245 c := getCommand(MaximumNArgs(2), false)246 _, err := executeCommand(c, "a", "b", "c")247 maximumNArgsWithMoreArgs(err, t)248 }249 250+func TestMaximumNArgs_WithMoreArgs_WithValid(t *testing.T) {251+ c := getCommand(MaximumNArgs(2), true)252+ _, err := executeCommand(c, "one", "three", "two")253+ maximumNArgsWithMoreArgs(err, t)254+}255+256+func TestMaximumNArgs_WithMoreArgs_WithValid_WithInvalidArgs(t *testing.T) {257+ c := getCommand(MaximumNArgs(2), true)258+ _, err := executeCommand(c, "a", "b", "c")259+ maximumNArgsWithMoreArgs(err, t)260+}261+262+func TestMaximumNArgs_WithMoreArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {263+ c := getCommand(MatchAll(OnlyValidArgs, MaximumNArgs(2)), true)264+ _, err := executeCommand(c, "a", "b", "c")265+ validOnlyWithInvalidArgs(err, t)266+}267+268+// ExactArgs269+270 func TestExactArgs(t *testing.T) {271 c := getCommand(ExactArgs(3), false)272 output, err := executeCommand(c, "a", "b", "c")273 expectSuccess(output, err, t)274 }275 156-func TestExactArgsWithInvalidCount(t *testing.T) {276+func TestExactArgs_WithValid(t *testing.T) {277+ c := getCommand(ExactArgs(3), true)278+ output, err := executeCommand(c, "three", "one", "two")279+ expectSuccess(output, err, t)280+}281+282+func TestExactArgs_WithValid_WithInvalidArgs(t *testing.T) {283+ c := getCommand(ExactArgs(3), true)284+ output, err := executeCommand(c, "three", "a", "two")285+ expectSuccess(output, err, t)286+}287+288+func TestExactArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {289+ c := getCommand(MatchAll(OnlyValidArgs, ExactArgs(3)), true)290+ _, err := executeCommand(c, "three", "a", "two")291+ validOnlyWithInvalidArgs(err, t)292+}293+294+func TestExactArgs_WithInvalidCount(t *testing.T) {295 c := getCommand(ExactArgs(2), false)296 _, err := executeCommand(c, "a", "b", "c")297 exactArgsWithInvalidCount(err, t)298 }299 162-func TestExactValidArgs(t *testing.T) {163- c := getCommand(ExactValidArgs(3), true)164- output, err := executeCommand(c, "three", "one", "two")165- expectSuccess(output, err, t)300+func TestExactArgs_WithInvalidCount_WithValid(t *testing.T) {301+ c := getCommand(ExactArgs(2), true)302+ _, err := executeCommand(c, "three", "one", "two")303+ exactArgsWithInvalidCount(err, t)304 }305 168-func TestExactValidArgsWithInvalidCount(t *testing.T) {169- c := getCommand(ExactValidArgs(2), false)170- _, err := executeCommand(c, "three", "one", "two")306+func TestExactArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) {307+ c := getCommand(ExactArgs(2), true)308+ _, err := executeCommand(c, "three", "a", "two")309 exactArgsWithInvalidCount(err, t)310 }311 174-func TestExactValidArgsWithInvalidArgs(t *testing.T) {175- c := getCommand(ExactValidArgs(3), true)312+func TestExactArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) {313+ c := getCommand(MatchAll(OnlyValidArgs, ExactArgs(2)), true)314 _, err := executeCommand(c, "three", "a", "two")177- validWithInvalidArgs(err, t)315+ validOnlyWithInvalidArgs(err, t)316 }317 318+// RangeArgs319+320 func TestRangeArgs(t *testing.T) {321 c := getCommand(RangeArgs(2, 4), false)322 output, err := executeCommand(c, "a", "b", "c")323 expectSuccess(output, err, t)324 }325 186-func TestRangeArgsWithInvalidCount(t *testing.T) {326+func TestRangeArgs_WithValid(t *testing.T) {327+ c := getCommand(RangeArgs(2, 4), true)328+ output, err := executeCommand(c, "three", "one", "two")329+ expectSuccess(output, err, t)330+}331+332+func TestRangeArgs_WithValid_WithInvalidArgs(t *testing.T) {333+ c := getCommand(RangeArgs(2, 4), true)334+ output, err := executeCommand(c, "three", "a", "two")335+ expectSuccess(output, err, t)336+}337+338+func TestRangeArgs_WithValidOnly_WithInvalidArgs(t *testing.T) {339+ c := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true)340+ _, err := executeCommand(c, "three", "a", "two")341+ validOnlyWithInvalidArgs(err, t)342+}343+344+func TestRangeArgs_WithInvalidCount(t *testing.T) {345 c := getCommand(RangeArgs(2, 4), false)346 _, err := executeCommand(c, "a")347 rangeArgsWithInvalidCount(err, t)348 }349 350+func TestRangeArgs_WithInvalidCount_WithValid(t *testing.T) {351+ c := getCommand(RangeArgs(2, 4), true)352+ _, err := executeCommand(c, "two")353+ rangeArgsWithInvalidCount(err, t)354+}355+356+func TestRangeArgs_WithInvalidCount_WithValid_WithInvalidArgs(t *testing.T) {357+ c := getCommand(RangeArgs(2, 4), true)358+ _, err := executeCommand(c, "a")359+ rangeArgsWithInvalidCount(err, t)360+}361+362+func TestRangeArgs_WithInvalidCount_WithValidOnly_WithInvalidArgs(t *testing.T) {363+ c := getCommand(MatchAll(OnlyValidArgs, RangeArgs(2, 4)), true)364+ _, err := executeCommand(c, "a")365+ validOnlyWithInvalidArgs(err, t)366+}367+368+// Takes(No)Args369+370 func TestRootTakesNoArgs(t *testing.T) {371 rootCmd := &Command{Use: "root", Run: emptyRun}372 childCmd := &Command{Use: "child", Run: emptyRun}373 rootCmd.AddCommand(childCmd)96 unmodified lines470 })471 }472 }473 474+// DEPRECATED475+476+func TestExactValidArgs(t *testing.T) {477+ c := getCommand(ExactValidArgs(3), true)478+ output, err := executeCommand(c, "three", "one", "two")479+ expectSuccess(output, err, t)480+}481+482+func TestExactValidArgs_WithInvalidCount(t *testing.T) {483+ c := getCommand(ExactValidArgs(2), false)484+ _, err := executeCommand(c, "three", "one", "two")485+ exactArgsWithInvalidCount(err, t)486+}487+488+func TestExactValidArgs_WithInvalidCount_WithInvalidArgs(t *testing.T) {489+ c := getCommand(ExactValidArgs(2), true)490+ _, err := executeCommand(c, "three", "a", "two")491+ exactArgsWithInvalidCount(err, t)492+}493+494+func TestExactValidArgs_WithInvalidArgs(t *testing.T) {495+ c := getCommand(ExactValidArgs(2), true)496+ _, err := executeCommand(c, "three", "a")497+ validOnlyWithInvalidArgs(err, t)498+}499+500 // This test make sure we keep backwards-compatibility with respect501 // to the legacyArgs() function.502 // It makes sure the root command accepts arguments if it does not have503 // sub-commands.24 unmodified linesmodified:args.go+10 added-14 removed
30 unmodified lines31 }32 return nil33 }34 35-// OnlyValidArgs returns an error if any args are not in the list of ValidArgs.35+// OnlyValidArgs returns an error if there are any positional args that are not in36+// the `ValidArgs` field of `Command`37 func OnlyValidArgs(cmd *Command, args []string) error {38 if len(cmd.ValidArgs) > 0 {39 // Remove any description that may be included in ValidArgs.40 // A description is following a tab character.41 var validArgs []string42 for _, v := range cmd.ValidArgs {43 validArgs = append(validArgs, strings.Split(v, "\t")[0])44 }44-45 for _, v := range args {46 if !stringInSlice(v, validArgs) {47 return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))48 }36 unmodified lines85 return nil86 }87 }88 89-// ExactValidArgs returns an error if90-// there are not exactly N positional args OR91-// there are any positional args that are not in the `ValidArgs` field of `Command`92-func ExactValidArgs(n int) PositionalArgs {93- return func(cmd *Command, args []string) error {94- if err := ExactArgs(n)(cmd, args); err != nil {95- return err96- }97- return OnlyValidArgs(cmd, args)98- }99-}100-89 // RangeArgs returns an error if the number of args is not within the expected range.90 func RangeArgs(min int, max int) PositionalArgs {91 return func(cmd *Command, args []string) error {92 if len(args) < min || len(args) > max {13 unmodified lines106 }107 return nil108 }109 }110+111+// ExactValidArgs returns an error if there are not exactly N positional args OR112+// there are any positional args that are not in the `ValidArgs` field of `Command`113+//114+// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead115+func ExactValidArgs(n int) PositionalArgs {116+ return MatchAll(ExactArgs(n), OnlyValidArgs)117+}modified:user_guide.md+34 added-16 removed
300 unmodified lines301 ```302 303 ### Flag Groups304 305-If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then 305+If you have different flags that must be provided together (e.g. if they provide the `--username` flag they MUST provide the `--password` flag as well) then306 Cobra can enforce that requirement:307 ```go308 rootCmd.Flags().StringVarP(&u, "username", "u", "", "Username (required if password is set)")309 rootCmd.Flags().StringVarP(&pw, "password", "p", "", "Password (required if username is set)")310 rootCmd.MarkFlagsRequiredTogether("username", "password")311-``` 311+```312 313-You can also prevent different flags from being provided together if they represent mutually 313+You can also prevent different flags from being provided together if they represent mutually314 exclusive options such as specifying an output format as either `--json` or `--yaml` but never both:315 ```go316 rootCmd.Flags().BoolVar(&u, "json", false, "Output in JSON")317 rootCmd.Flags().BoolVar(&pw, "yaml", false, "Output in YAML")8 unmodified lines326 327 ## Positional and Custom Arguments328 329 Validation of positional arguments can be specified using the `Args` field of `Command`.330+The following validators are built in:331+332+- Number of arguments:333+ - `NoArgs` - report an error if there are any positional args.334+ - `ArbitraryArgs` - accept any number of args.335+ - `MinimumNArgs(int)` - report an error if less than N positional args are provided.336+ - `MaximumNArgs(int)` - report an error if more than N positional args are provided.337+ - `ExactArgs(int)` - report an error if there are not exactly N positional args.338+ - `RangeArgs(min, max)` - report an error if the number of args is not between `min` and `max`.339+- Content of the arguments:340+ - `OnlyValidArgs` - report an error if there are any positional args not specified in the `ValidArgs` field of `Command`, which can optionally be set to a list of valid values for positional args.341+342 If `Args` is undefined or `nil`, it defaults to `ArbitraryArgs`.343 332-The following validators are built in:344+Moreover, `MatchAll(pargs ...PositionalArgs)` enables combining existing checks with arbitrary other checks.345+For instance, if you want to report an error if there are not exactly N positional args OR if there are any positional346+args that are not in the `ValidArgs` field of `Command`, you can call `MatchAll` on `ExactArgs` and `OnlyValidArgs`, as347+shown below:348 334-- `NoArgs` - the command will report an error if there are any positional args.335-- `ArbitraryArgs` - the command will accept any args.336-- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`.337-- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args.338-- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args.339-- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args.340-- `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command`341-- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args.342-- `MatchAll(pargs ...PositionalArgs)` - enables combining existing checks with arbitrary other checks (e.g. you want to check the ExactArgs length along with other qualities).349+```go350+var cmd = &cobra.Command{351+ Short: "hello",352+ Args: MatchAll(ExactArgs(2), OnlyValidArgs),353+ Run: func(cmd *cobra.Command, args []string) {354+ fmt.Println("Hello, World!")355+ },356+}357+```358 344-An example of setting the custom validator:359+It is possible to set any custom validator that satisfies `func(cmd *cobra.Command, args []string) error`.360+For example:361 362 ```go363 var cmd = &cobra.Command{364 Short: "hello",365 Args: func(cmd *cobra.Command, args []string) error {350- if len(args) < 1 {351- return errors.New("requires a color argument")366+ // Optionally run one of the validators provided by cobra367+ if err := cobra.MinimumNArgs(1)(cmd, args); err != nil {368+ return err369 }370+ // Run the custom validation logic371 if myapp.IsValidColor(args[0]) {372 return nil373 }374 return fmt.Errorf("invalid color specified: %s", args[0])310 unmodified lines