From 969cc463efcfacac728bac218534d0a027d448ee Mon Sep 17 00:00:00 2001 From: jlsong01 Date: Sat, 5 Feb 2022 22:29:08 +0800 Subject: [PATCH] kubectl version should fail when given extra arguments --- staging/src/k8s.io/kubectl/pkg/cmd/version/version.go | 8 ++++++-- .../src/k8s.io/kubectl/pkg/cmd/version/version_test.go | 5 ++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/staging/src/k8s.io/kubectl/pkg/cmd/version/version.go b/staging/src/k8s.io/kubectl/pkg/cmd/version/version.go index ecc0d8d6bdf..5d6a7f7b2f2 100644 --- a/staging/src/k8s.io/kubectl/pkg/cmd/version/version.go +++ b/staging/src/k8s.io/kubectl/pkg/cmd/version/version.go @@ -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'`) } diff --git a/staging/src/k8s.io/kubectl/pkg/cmd/version/version_test.go b/staging/src/k8s.io/kubectl/pkg/cmd/version/version_test.go index 16b3827c9be..9a355592243 100644 --- a/staging/src/k8s.io/kubectl/pkg/cmd/version/version_test.go +++ b/staging/src/k8s.io/kubectl/pkg/cmd/version/version_test.go @@ -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) }