Skip to content

Commit

Permalink
Merge pull request #1835 from dgageot/basic-cobra-test
Browse files Browse the repository at this point in the history
Basic unit test to go through all the cobra related code
  • Loading branch information
dgageot authored Mar 20, 2019
2 parents 8418c9e + c48c484 commit 2e4c4a9
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 42 deletions.
39 changes: 21 additions & 18 deletions cmd/skaffold/app/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,29 +38,36 @@ var (
v string
defaultColor int
overwrite bool

updateMsg = make(chan string)
)

var rootCmd = &cobra.Command{
Use: "skaffold",
Short: "A tool that facilitates continuous development for Kubernetes applications.",
}

func NewSkaffoldCommand(out, err io.Writer) *cobra.Command {
updateMsg := make(chan string)

rootCmd := &cobra.Command{
Use: "skaffold",
Short: "A tool that facilitates continuous development for Kubernetes applications.",
SilenceErrors: true,
}

rootCmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
if err := SetUpLogs(err, v); err != nil {
return err
}

rootCmd.SilenceUsage = true
logrus.Infof("Skaffold %+v", version.Get())
go func() {
if err := updateCheck(updateMsg); err != nil {
logrus.Infof("update check failed: %s", err)
}
}()

color.OverwriteDefault(color.Color(defaultColor))

if quietFlag {
logrus.Debugf("Update check is disabled because of quiet mode")
} else {
go func() {
if err := updateCheck(updateMsg); err != nil {
logrus.Infof("update check failed: %s", err)
}
}()
}

return nil
}

Expand All @@ -72,7 +79,7 @@ func NewSkaffoldCommand(out, err io.Writer) *cobra.Command {
}
}

rootCmd.SilenceErrors = true
rootCmd.SetOutput(out)
rootCmd.AddCommand(NewCmdCompletion(out))
rootCmd.AddCommand(NewCmdVersion(out))
rootCmd.AddCommand(NewCmdRun(out))
Expand All @@ -94,10 +101,6 @@ func NewSkaffoldCommand(out, err io.Writer) *cobra.Command {
}

func updateCheck(ch chan string) error {
if quietFlag {
logrus.Debugf("Update check is disabled because of quiet mode")
return nil
}
if !update.IsUpdateCheckEnabled() {
logrus.Debugf("Update check not enabled, skipping.")
return nil
Expand Down
46 changes: 26 additions & 20 deletions cmd/skaffold/app/cmd/completion.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,38 +218,44 @@ _complete skaffold 2>/dev/null
`
)

var completionCmd = &cobra.Command{
Use: "completion SHELL",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("requires 1 arg, found %d", len(args))
}
return cobra.OnlyValidArgs(cmd, args)
},
ValidArgs: []string{"bash", "zsh"},
Short: "Output shell completion for the given shell (bash or zsh)",
Long: longDescription,
Run: completion,
}

func completion(_cmd *cobra.Command, args []string) {
func completion(cmd *cobra.Command, args []string) {
switch args[0] {
case "bash":
rootCmd.GenBashCompletion(os.Stdout)
rootCmd(cmd).GenBashCompletion(os.Stdout)
case "zsh":
runCompletionZsh(os.Stdout)
runCompletionZsh(cmd, os.Stdout)
}
}

// NewCmdCompletion returns the cobra command that outputs shell completion code
func NewCmdCompletion(out io.Writer) *cobra.Command {
return completionCmd
return &cobra.Command{
Use: "completion SHELL",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("requires 1 arg, found %d", len(args))
}
return cobra.OnlyValidArgs(cmd, args)
},
ValidArgs: []string{"bash", "zsh"},
Short: "Output shell completion for the given shell (bash or zsh)",
Long: longDescription,
Run: completion,
}
}

func runCompletionZsh(out io.Writer) {
func runCompletionZsh(cmd *cobra.Command, out io.Writer) {
io.WriteString(out, zshInitialization)
buf := new(bytes.Buffer)
rootCmd.GenBashCompletion(buf)
rootCmd(cmd).GenBashCompletion(buf)
out.Write(buf.Bytes())
io.WriteString(out, zshTail)
}

func rootCmd(cmd *cobra.Command) *cobra.Command {
parent := cmd
for parent.HasParent() {
parent = parent.Parent()
}
return parent
}
6 changes: 3 additions & 3 deletions cmd/skaffold/app/skaffold.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ limitations under the License.
package app

import (
"os"
"io"

"github.com/GoogleContainerTools/skaffold/cmd/skaffold/app/cmd"
"github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/plugin"
)

func Run() error {
func Run(out, err io.Writer) error {
if plugin.ShouldExecuteCorePlugin() {
return plugin.Execute()
}

c := cmd.NewSkaffoldCommand(os.Stdout, os.Stderr)
c := cmd.NewSkaffoldCommand(out, err)
return c.Execute()
}
51 changes: 51 additions & 0 deletions cmd/skaffold/app/skaffold_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
Copyright 2019 The Skaffold Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package app

import (
"bytes"
"io/ioutil"
"os"
"testing"

"github.com/GoogleContainerTools/skaffold/testutil"
)

func TestMainHelp(t *testing.T) {
var (
output bytes.Buffer
errOutput bytes.Buffer
)

defer func(args []string) { os.Args = args }(os.Args)
os.Args = []string{"skaffold", "help"}

err := Run(&output, &errOutput)

testutil.CheckError(t, false, err)
testutil.CheckContains(t, "Available Commands", output.String())
testutil.CheckDeepEqual(t, "", errOutput.String())
}

func TestMainUnknownCommand(t *testing.T) {
defer func(args []string) { os.Args = args }(os.Args)
os.Args = []string{"skaffold", "unknown"}

err := Run(ioutil.Discard, ioutil.Discard)

testutil.CheckError(t, true, err)
}
3 changes: 2 additions & 1 deletion cmd/skaffold/skaffold.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package main

import (
"context"
"os"

"github.com/pkg/errors"
"github.com/sirupsen/logrus"
Expand All @@ -26,7 +27,7 @@ import (
)

func main() {
if err := app.Run(); err != nil {
if err := app.Run(os.Stdout, os.Stderr); err != nil {
if errors.Cause(err) == context.Canceled {
logrus.Debugln(errors.Wrap(err, "ignore error since context is cancelled"))
} else {
Expand Down

0 comments on commit 2e4c4a9

Please sign in to comment.