Skip to content

Commit

Permalink
Fix handling of invalid/empty json response (#209)
Browse files Browse the repository at this point in the history
Signed-off-by: Mikkel Oscar Lyderik Larsen <[email protected]>
  • Loading branch information
mikkeloscar authored Oct 2, 2020
1 parent b677e81 commit be7567e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pkg/collector/httpmetrics/json_path.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func (g *JSONPathMetricsGetter) GetMetric(metricsURL url.URL) (float64, error) {
return 0, err
}

if len(nodes) > 1 {
if len(nodes) != 1 {
return 0, fmt.Errorf("unexpected json: expected single numeric or array value")
}

Expand Down
19 changes: 19 additions & 0 deletions pkg/collector/httpmetrics/json_path_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package httpmetrics

import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
Expand All @@ -27,6 +28,7 @@ func TestJSONPathMetricsGetter(t *testing.T) {
jsonPath string
result float64
aggregator AggregatorFunc
err error
}{
{
name: "basic single value",
Expand All @@ -49,6 +51,18 @@ func TestJSONPathMetricsGetter(t *testing.T) {
result: 5,
aggregator: Average,
},
{
name: "json path not resulting in array or number should lead to error",
jsonResponse: []byte(`{"metric.value":5}`),
jsonPath: "$['invalid.metric.values']",
err: errors.New("unexpected json: expected single numeric or array value"),
},
{
name: "invalid json should error",
jsonResponse: []byte(`{`),
jsonPath: "$['invalid.metric.values']",
err: errors.New("unexpected end of file"),
},
} {
t.Run(tc.name, func(t *testing.T) {
server := makeTestHTTPServer(t, tc.jsonResponse)
Expand All @@ -58,6 +72,11 @@ func TestJSONPathMetricsGetter(t *testing.T) {
url, err := url.Parse(fmt.Sprintf("%s/metrics", server.URL))
require.NoError(t, err)
metric, err := getter.GetMetric(*url)
if tc.err != nil {
require.Error(t, err)
require.Equal(t, tc.err.Error(), err.Error())
return
}
require.NoError(t, err)
require.Equal(t, tc.result, metric)
})
Expand Down

0 comments on commit be7567e

Please sign in to comment.