Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix 04 add tests #15

Merged
merged 8 commits into from
May 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/golang-ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ on:
pull_request:
branches:
- master
schedule:
- cron: '0 8 * * *'

jobs:
lint:
Expand Down
Empty file removed cmd/.gitkeep
Empty file.
4 changes: 1 addition & 3 deletions cmd/aws_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
package cmd

import (
"fmt"

"github.com/jedib0t/go-pretty/table"
"github.com/jedib0t/go-pretty/text"
"github.com/mateimicu/kdiscover/internal"
Expand Down Expand Up @@ -59,7 +57,7 @@ func newListCommand() *cobra.Command {
remoteEKSClusters := internal.GetEKSClusters(awsRegions)
log.Info(remoteEKSClusters)

fmt.Println(getTable(remoteEKSClusters))
cmd.Println(getTable(remoteEKSClusters))
return nil
},
}
Expand Down
10 changes: 0 additions & 10 deletions cmd/aws_list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,6 @@ import (
"github.com/mateimicu/kdiscover/internal"
)

//import (
//"fmt"
//"io/ioutil"
//"strings"
//"testing"

//log "github.com/sirupsen/logrus"
//"github.com/zenizh/go-capturer"
//)

func getMockClusters(c int) []internal.Cluster {
d := make([]internal.Cluster, 0, c)
for i := 0; i < c; i++ {
Expand Down
43 changes: 28 additions & 15 deletions cmd/aws_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,36 +20,49 @@ var (
alias string
)

func backupKubeConfig(kubeconfigPath string) (string, error) {
bName, err := generateBackupName(kubeconfigPath)
if err != nil {
log.WithFields(log.Fields{
"kubeconfig-path": kubeconfigPath,
"err": err.Error(),
}).Info("Can't generate backup file name ")
}
err = copy(kubeconfigPath, bName)
if err != nil {
return "", err
}
return bName, nil
}

func newUpdateCommand() *cobra.Command {
updateCommand := &cobra.Command{
Use: "update",
Short: "Update all EKS Clusters",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(cmd.Short)
RunE: func(cmd *cobra.Command, args []string) error {
cmd.Println(cmd.Short)

remoteEKSClusters := internal.GetEKSClusters(awsRegions)
log.Info(remoteEKSClusters)
fmt.Printf("Found %v clusters remote\n", len(remoteEKSClusters))

cmd.Printf("Found %v clusters remote\n", len(remoteEKSClusters))

if backupKubeconfig && fileExists(kubeconfigPath) {
bName, err := generateBackupName(kubeconfigPath)
bName, err := backupKubeConfig(kubeconfigPath)
if err != nil {
log.WithFields(log.Fields{
"kubeconfig-path": kubeconfigPath,
}).Info("Can't generate backup file name ")
}
fmt.Printf("Backup kubeconfig to %v\n", bName)
err = copy(kubeconfigPath, bName)
if err != nil {
fmt.Println(err.Error())
return
return err
}
cmd.Printf("Backup kubeconfig to %v\n", bName)
}

err := internal.UpdateKubeconfig(remoteEKSClusters, kubeconfigPath, contextName{templateValue: alias})
if err != nil {
fmt.Println(err.Error())
return
return err
}
return nil
},
}

updateCommand.Flags().BoolVar(&backupKubeconfig, "backup-kubeconfig", true, "Backup cubeconfig before update")
updateCommand.Flags().StringVar(
&alias,
Expand Down
78 changes: 78 additions & 0 deletions cmd/aws_update_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Package cmd offers CLI functionality
package cmd

import (
"io/ioutil"
"os"
"path/filepath"
"testing"
)

func Test_generateBackupNameNoConflict(t *testing.T) {
dir, err := ioutil.TempDir("", ".kube")
if err != nil {
t.Error(err.Error())
}
defer os.RemoveAll(dir)

kubeconfigPath := filepath.Join(dir, "kubeconfig")
backupKubeconfigPath := filepath.Join(dir, "kubeconfig.bak")

if err := ioutil.WriteFile(kubeconfigPath, []byte("..."), 0666); err != nil {
t.Error(err.Error())
}

bName, err := backupKubeConfig(kubeconfigPath)
if err != nil {
t.Error(err.Error())
}

if !fileExists(backupKubeconfigPath) {
t.Errorf("Expecing %v to exist as backup of %v", backupKubeconfigPath, kubeconfigPath)
}

if bName != backupKubeconfigPath {
t.Errorf("Backup name is %v, expected %v", bName, backupKubeconfigPath)
}
}

func Test_fileExistsDir(t *testing.T) {
dir, err := ioutil.TempDir("", "dir")
if err != nil {
t.Error(err.Error())
}
defer os.RemoveAll(dir)
if fileExists(dir) {
t.Errorf("Return true on dir %v", dir)
}
}

func Test_fileExistsMissing(t *testing.T) {
dir, err := ioutil.TempDir("", "dir")
if err != nil {
t.Error(err.Error())
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "missing")
if fileExists(dir) {
t.Errorf("Return true on missing file %v", path)
}
}

func Test_fileExistsFile(t *testing.T) {
dir, err := ioutil.TempDir("", "dir")
if err != nil {
t.Error(err.Error())
}
defer os.RemoveAll(dir)

path := filepath.Join(dir, "kubeconfig")

if err := ioutil.WriteFile(path, []byte("...\n"), 0666); err != nil {
t.Error(err.Error())
}

if !fileExists(path) {
t.Errorf("Return false on file %v", path)
}
}
37 changes: 28 additions & 9 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ package cmd
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"testing"

log "github.com/sirupsen/logrus"
"github.com/zenizh/go-capturer"
)

var basicCommands []struct{ cmd []string } = []struct {
Expand All @@ -24,22 +25,30 @@ var basicCommands []struct{ cmd []string } = []struct {
// with all the possible combination of commands in order to check that the logging hack worsk
// An issue about this https://github.com/spf13/cobra/issues/252
func Test_CascadingPersistPreRunEHackWithLoggingLevels(t *testing.T) {
t.Parallel()
for _, tt := range basicCommands {
for k, exp := range loggingLevels {

testname := fmt.Sprintf("command %v and logging lvl %v", tt.cmd, k)
t.Run(testname, func(t *testing.T) {
dir, err := ioutil.TempDir("", ".kube")
if err != nil {
t.Error(err.Error())
}
defer os.RemoveAll(dir)

kubeconfigPath := filepath.Join(dir, "kubeconfig")
cmd := NewRootCommand()
cmd.SetOut(ioutil.Discard)
cmd.SetErr(ioutil.Discard)

completCmd := append(tt.cmd, "--log-level")
completCmd = append(completCmd, k)
completCmd = append(completCmd, "--kubeconfig-path")
completCmd = append(completCmd, kubeconfigPath)

cmd.SetArgs(completCmd)
capturer.CaptureOutput(func() {
cmd.Execute()
})
cmd.Execute()

// none logging level is a special case
if k == "none" {
Expand All @@ -64,16 +73,26 @@ func Test_HelpFunction(t *testing.T) {
t.Run(testname, func(t *testing.T) {
cmd := NewRootCommand()

buf := new(strings.Builder)
cmd.SetOut(buf)
cmd.SetErr(buf)

completCmd := append(tt.cmd, "--help")

cmd.SetArgs(completCmd)
out := capturer.CaptureOutput(func() {
cmd.Execute()
})
cmd.Execute()

if !strings.Contains(string(out), expected) {
t.Errorf("Running %v we were expecting %v in the ouput but got: %v", completCmd, expected, out)
if !strings.Contains(string(buf.String()), expected) {
t.Errorf("Running %v we were expecting %v in the ouput but got: %v", completCmd, expected, buf.String())
}
})
}
}

func Test_getAllLogglingLevels(t *testing.T) {
for _, lvl := range getAllLogglingLevels() {
if _, ok := loggingLevels[lvl]; !ok {
t.Errorf("Loging level %v not found in map", lvl)
}
}
}
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ require (
github.com/mattn/go-runewidth v0.0.9 // indirect
github.com/sirupsen/logrus v1.2.0
github.com/spf13/cobra v0.0.6
github.com/zenizh/go-capturer v0.0.0-20171211120116-e492ea43421d
k8s.io/client-go v0.18.2
k8s.io/utils v0.0.0-20200414100711-2df71ebbae66 // indirect
)
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,6 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
github.com/zenizh/go-capturer v0.0.0-20171211120116-e492ea43421d h1:M8CW/74zqSPEbwvgnSSgaFII8K7jypGu0cxfNbJnlEQ=
github.com/zenizh/go-capturer v0.0.0-20171211120116-e492ea43421d/go.mod h1:x4ese4FurWTpd2QSFKWYzWhTihHvmUXtv/9TEgl091Q=
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.mongodb.org/mongo-driver v1.0.3 h1:GKoji1ld3tw2aC+GX1wbr/J2fX13yNacEYoJ8Nhr0yU=
go.mongodb.org/mongo-driver v1.0.3/go.mod h1:u7ryQJ+DOzQmeO7zB6MHyr8jkEQvC8vH7qLUO4lqsUM=
Expand Down
Empty file removed internal/.gitkeep
Empty file.
39 changes: 39 additions & 0 deletions internal/regions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ package internal

import (
"fmt"
"reflect"
"sort"
"testing"
)

func TestContains(t *testing.T) {
t.Parallel()
tts := []struct {
key string
list []string
Expand All @@ -26,3 +29,39 @@ func TestContains(t *testing.T) {
})
}
}

func TestGetRegions(t *testing.T) {
t.Parallel()
tts := []struct {
partitions []string
}{
{[]string{}},
{[]string{"aws", "aws-cn", "aws-us-gov", "aws-iso", "aws-iso-b"}},
{[]string{"aws", "aws-cn", "aws-iso-b"}},
{[]string{"aws-iso", "aws-iso-b"}},
}

for _, tt := range tts {
testname := fmt.Sprintf("Partitions %v", tt.partitions)
t.Run(testname, func(t *testing.T) {
totalResult := GetRegions(tt.partitions)

// compute partial result
partialResult := make([]string, 0)
for _, partition := range tt.partitions {
for _, v := range GetRegions([]string{partition}) {
partialResult = append(partialResult, v)
}
}

sort.Strings(totalResult)
sort.Strings(partialResult)
if len(partialResult) == 0 && len(totalResult) == 0 {
return
}
if !reflect.DeepEqual(partialResult, totalResult) {
t.Errorf("Step by Stept we got %v but asking for all we got %v", partialResult, totalResult)
}
})
}
}