Skip to content

Commit

Permalink
Merge pull request #3494 from knabben/reporterror-test
Browse files Browse the repository at this point in the history
Adding more utils tests
  • Loading branch information
tstromberg authored Jan 16, 2019
2 parents 8bc8816 + 6762fb0 commit 303e26c
Showing 1 changed file with 46 additions and 7 deletions.
53 changes: 46 additions & 7 deletions cmd/util/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@ package util
import (
"bytes"
"fmt"
"k8s.io/client-go/tools/clientcmd"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"

Expand All @@ -31,6 +33,16 @@ import (
"github.com/spf13/viper"
)

func startTestHTTPServer(returnError bool, response string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if returnError {
http.Error(w, response, 400)
} else {
fmt.Fprintf(w, response)
}
}))
}

func TestFormatError(t *testing.T) {
var testErr error
if _, err := FormatError(testErr); err == nil {
Expand Down Expand Up @@ -70,22 +82,26 @@ func TestUploadError(t *testing.T) {
errMsg, _ := FormatError(testErr)
jsonErrMsg, _ := MarshallError(errMsg, "default", version.GetVersion())

server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
}))

server := startTestHTTPServer(false, "http test")
if err := UploadError(jsonErrMsg, server.URL); err != nil {
t.Fatalf("Unexpected error: %v", err)
}

server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "failed to write report", 400)
}))
server = startTestHTTPServer(true, "failed to write report")
if err := UploadError(jsonErrMsg, server.URL); err == nil {
t.Fatalf("UploadError should have errored from a 400 response")
}
}

func TestReportError(t *testing.T) {
testErr := errors.New("TestError 1")

server := startTestHTTPServer(false, "http test")
if err := ReportError(testErr, server.URL); err != nil {
t.Fatalf("ReportError")
}
}

func revertLookPath(l LookPath) {
lookPath = l
}
Expand Down Expand Up @@ -163,3 +179,26 @@ func TestKubectlDownloadMsg(t *testing.T) {
})
}
}

func TestGetKubeConfigPath(t *testing.T) {
var tests = []struct {
input string
want string
}{
{
input: "/home/fake/.kube/.kubeconfig",
want: "/home/fake/.kube/.kubeconfig",
},
{
input: "/home/fake/.kube/.kubeconfig:/home/fake2/.kubeconfig",
want: "/home/fake/.kube/.kubeconfig",
},
}

for _, test := range tests {
os.Setenv(clientcmd.RecommendedConfigPathEnvVar, test.input)
if result := GetKubeConfigPath(); result != test.want {
t.Errorf("Expected first splitted chunk, got: %s", result)
}
}
}

0 comments on commit 303e26c

Please sign in to comment.