Skip to content
Snippets Groups Projects
Commit 16df830f authored by bryanl's avatar bryanl
Browse files

don't fail fetching api spec when json is invalid


If server returned a malformed json response, GetAPISpec panics

Signed-off-by: default avatarbryanl <bryanliles@gmail.com>
parent e3806408
No related branches found
No related tags found
No related merge requests found
......@@ -36,6 +36,10 @@ import (
"k8s.io/client-go/tools/clientcmd"
)
const (
defaultVersion = "version:v1.7.0"
)
// Config is a wrapper around client-go's ClientConfig
type Config struct {
Overrides *clientcmd.ConfigOverrides
......@@ -72,10 +76,6 @@ func InitClient(env string) (dynamic.ClientPool, discovery.DiscoveryInterface, s
// If no swagger is found, or we are unable to authenticate to the server, we
// will default to version:v1.7.0.
func (c *Config) GetAPISpec(server string) string {
const (
defaultVersion = "version:v1.7.0"
)
type Info struct {
Version string `json:"version"`
}
......@@ -111,8 +111,8 @@ func (c *Config) GetAPISpec(server string) string {
}
spec := Spec{}
jsonErr := json.Unmarshal(body, &spec)
if jsonErr != nil {
err = json.Unmarshal(body, &spec)
if err != nil {
log.Debugf("Failed to parse swagger at %s\n%s", url, err.Error())
return defaultVersion
}
......
package client
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
)
func TestConfig_GetAPISpec(t *testing.T) {
b, err := ioutil.ReadFile("testdata/swagger.json")
require.NoError(t, err)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, string(b))
}))
defer ts.Close()
cases := []struct {
name string
serverURL string
expected string
}{
{
name: "invalid server URL",
serverURL: "http://+++",
expected: defaultVersion,
},
{
name: "with a server",
serverURL: ts.URL,
expected: "version:v1.9.3",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c := Config{}
got := c.GetAPISpec(tc.serverURL)
require.Equal(t, tc.expected, got)
})
}
}
{
"info": {
"version": "v1.9.3"
}
}
\ No newline at end of file
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment