kubectl version should fail when given extra arguments

Kubernetes-commit: 969cc463efcfacac728bac218534d0a027d448ee
This commit is contained in:
jlsong01 2022-02-05 22:29:08 +08:00 committed by Kubernetes Publisher
parent 8428013c0a
commit 4b64056435
2 changed files with 10 additions and 3 deletions

View File

@ -75,7 +75,7 @@ func NewCmdVersion(f cmdutil.Factory, ioStreams genericclioptions.IOStreams) *co
Example: versionExample,
Run: func(cmd *cobra.Command, args []string) {
cmdutil.CheckErr(o.Complete(f, cmd))
cmdutil.CheckErr(o.Validate())
cmdutil.CheckErr(o.Validate(args))
cmdutil.CheckErr(o.Run())
},
}
@ -101,7 +101,11 @@ func (o *Options) Complete(f cmdutil.Factory, cmd *cobra.Command) error {
}
// Validate validates the provided options
func (o *Options) Validate() error {
func (o *Options) Validate(args []string) error {
if len(args) != 0 {
return errors.New(fmt.Sprintf("extra arguments: %v", args))
}
if o.Output != "" && o.Output != "yaml" && o.Output != "json" {
return errors.New(`--output must be 'yaml' or 'json'`)
}

View File

@ -34,9 +34,12 @@ func TestNewCmdVersionClientVersion(t *testing.T) {
if err := o.Complete(tf, &cobra.Command{}); err != nil {
t.Errorf("Unexpected error: %v", err)
}
if err := o.Validate(); err != nil {
if err := o.Validate(nil); err != nil {
t.Errorf("Unexpected error: %v", err)
}
if err := o.Validate([]string{"extraParameter0"}); !strings.Contains(err.Error(), "extra arguments") {
t.Errorf("Unexpected error: should fail to validate the args length greater than 0")
}
if err := o.Run(); err != nil {
t.Errorf("Cannot execute version command: %v", err)
}