Validate json parse for TargetGroup Unmarshal (#3614)

Using DisallowUnknownFields in golang 1.10 to forbid unknown fields in targetGroups
added the license header for the targetGroup test
This commit is contained in:
Krasi Georgiev 2018-02-27 14:33:27 +02:00 committed by Brian Brazil
parent e392b9a18b
commit 6b0e9ef183
2 changed files with 53 additions and 1 deletions

View File

@ -14,6 +14,7 @@
package targetgroup package targetgroup
import ( import (
"bytes"
"encoding/json" "encoding/json"
"github.com/prometheus/common/model" "github.com/prometheus/common/model"
@ -77,7 +78,10 @@ func (tg *Group) UnmarshalJSON(b []byte) error {
Targets []string `json:"targets"` Targets []string `json:"targets"`
Labels model.LabelSet `json:"labels"` Labels model.LabelSet `json:"labels"`
}{} }{}
if err := json.Unmarshal(b, &g); err != nil {
dec := json.NewDecoder(bytes.NewReader(b))
dec.DisallowUnknownFields()
if err := dec.Decode(&g); err != nil {
return err return err
} }
tg.Targets = make([]model.LabelSet, 0, len(g.Targets)) tg.Targets = make([]model.LabelSet, 0, len(g.Targets))

View File

@ -0,0 +1,48 @@
// Copyright 2018 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package targetgroup
import (
"errors"
"testing"
"github.com/prometheus/prometheus/util/testutil"
)
func TestTargetGroupStrictJsonUnmarshal(t *testing.T) {
tests := []struct {
json string
expectedReply error
}{
{
json: ` {"labels": {},"targets": []}`,
expectedReply: nil,
},
{
json: ` {"label": {},"targets": []}`,
expectedReply: errors.New("json: unknown field \"label\""),
},
{
json: ` {"labels": {},"target": []}`,
expectedReply: errors.New("json: unknown field \"target\""),
},
}
tg := Group{}
for _, test := range tests {
actual := tg.UnmarshalJSON([]byte(test.json))
testutil.Equals(t, test.expectedReply, actual)
}
}