Skip to content

Commit

Permalink
adding tests for the cobra function
Browse files Browse the repository at this point in the history
Signed-off-by: Christopher Hein <me@chrishein.com>
  • Loading branch information
christopherhein committed Aug 13, 2019
1 parent 228057b commit 7f7626f
Show file tree
Hide file tree
Showing 7 changed files with 107 additions and 55 deletions.
9 changes: 9 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,14 @@ go:
env:
- GO111MODULE=on

branches:
only:
- master

before_install:
- go get -u golang.org/x/lint/golint

script:
- make test-fmt
- make lint
- make test
9 changes: 8 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
.PHONY: all
all: build-example test

.PHONY: lint
lint:
@golint -set_exit_status ./...

test-fmt:
./hack/test-fmt.sh

.PHONY: test
test:
go test -v ./...
@go test -v -race ./...

.PHONY: build-example
build-example:
Expand Down
95 changes: 45 additions & 50 deletions example/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,82 +16,77 @@ limitations under the License.
package main

import (
"fmt"
"os"
"github.com/spf13/cobra"
"fmt"
"os"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
"github.com/spf13/cobra"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
)


var cfgFile string


// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "example",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
Use: "example",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

func init() {
cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
cobra.OnInitialize(initConfig)

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.example.yaml)")
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.example.yaml)")

// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}


// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}

// Search config in home directory with name ".example" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".example")
}

viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}

// Search config in home directory with name ".example" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".example")
}

viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}

4 changes: 3 additions & 1 deletion example/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ limitations under the License.
package main

import (
"os"

"github.com/spf13/cobra"
goVersion "go.hein.dev/go-version"
)
Expand All @@ -29,7 +31,7 @@ var (
Use: "version",
Short: "Version will output the current build information",
Long: ``,
Run: goVersion.Func(shortened, version, commit, date),
Run: goVersion.Func(os.Stdout, shortened, version, commit, date),
}
)

Expand Down
3 changes: 3 additions & 0 deletions hack/test-fmt.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/bash

test -z $(gofmt -l .)
5 changes: 3 additions & 2 deletions version.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package version // import "go.hein.dev/go-version"
import (
"encoding/json"
"fmt"
"io"
"strings"

"github.com/spf13/cobra"
Expand All @@ -25,7 +26,7 @@ func New(version string, commit string, date string) *Info {
}

// Func will add the versioning code
func Func(shortened bool, version, commit, date string) func(*cobra.Command, []string) {
func Func(out io.Writer, shortened bool, version, commit, date string) func(*cobra.Command, []string) {
return func(_ *cobra.Command, _ []string) {
var response string
versionOutput := New(version, commit, date)
Expand All @@ -35,7 +36,7 @@ func Func(shortened bool, version, commit, date string) func(*cobra.Command, []s
} else {
response = versionOutput.ToJSON()
}
fmt.Printf("%+v", response)
fmt.Fprintf(out, "%+v", response)
return
}
}
Expand Down
37 changes: 36 additions & 1 deletion version_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package version

import "testing"
import (
"bytes"
"testing"

"github.com/spf13/cobra"
)

func TestToJSON(t *testing.T) {
v := New("dev", "fee8dd1f7c24da23508e26347694be0acce5631b", "Fri Jun 21 10:50:15 PDT 2019")
Expand All @@ -25,3 +30,33 @@ Date: Fri Jun 21 10:50:15 PDT 2019
t.Errorf("Expected shortened %s to equal %s", short, expected)
}
}

type testcase struct {
expected string
shortened bool
}

func TestFunc(t *testing.T) {
cases := []testcase{
testcase{
expected: "{\"Version\":\"dev\",\"Commit\":\"fee8dd1f7c24da23508e26347694be0acce5631b\",\"Date\":\"Fri Jun 21 10:50:15 PDT 2019\"}\n",
shortened: false,
},
testcase{
expected: `Version: dev
Commit: fee8dd1f7c24da23508e26347694be0acce5631b
Date: Fri Jun 21 10:50:15 PDT 2019
`,
shortened: true,
},
}

for _, c := range cases {
buffer := &bytes.Buffer{}
Func(buffer, c.shortened, "dev", "fee8dd1f7c24da23508e26347694be0acce5631b", "Fri Jun 21 10:50:15 PDT 2019")(&cobra.Command{}, []string{})
resp := buffer.String()
if resp != c.expected {
t.Errorf("got %q want %q", resp, c.expected)
}
}
}

0 comments on commit 7f7626f

Please sign in to comment.