Skip to content

Commit

Permalink
discovery: check for nil triton_sd_config (prometheus#7671)
Browse files Browse the repository at this point in the history
* discovery: check for nil triton_sd_config

Note: this was discovered thanks to the added test.
The test is pretty low-level but also effective.

Signed-off-by: Julien Pivotto <roidelapluie@inuits.eu>
  • Loading branch information
roidelapluie committed Jul 25, 2020
1 parent 9da59c8 commit e074152
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
5 changes: 5 additions & 0 deletions discovery/config/config.go
Expand Up @@ -138,5 +138,10 @@ func (c *ServiceDiscoveryConfig) Validate() error {
return errors.New("empty or null section in static_configs")
}
}
for _, cfg := range c.TritonSDConfigs {
if cfg == nil {
return errors.New("empty or null section in triton_sd_configs")
}
}
return nil
}
58 changes: 58 additions & 0 deletions discovery/config/config_test.go
@@ -0,0 +1,58 @@
// Copyright 2020 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 config

import (
"fmt"
"reflect"
"strings"
"testing"

"github.com/prometheus/prometheus/util/testutil"
"gopkg.in/yaml.v2"
)

func TestForNilSDConfig(t *testing.T) {
// Get all the yaml fields names of the ServiceDiscoveryConfig struct.
s := reflect.ValueOf(ServiceDiscoveryConfig{})
configType := s.Type()
n := s.NumField()
fieldsSlice := make([]string, n)
for i := 0; i < n; i++ {
field := configType.Field(i)
tag := field.Tag.Get("yaml")
tag = strings.Split(tag, ",")[0]
fieldsSlice = append(fieldsSlice, tag)
}

// Unmarshall all possible yaml keys and validate errors check upon nil
// SD config.
for _, f := range fieldsSlice {
if f == "" {
continue
}
t.Run(f, func(t *testing.T) {
c := &ServiceDiscoveryConfig{}
err := yaml.Unmarshal([]byte(fmt.Sprintf(`
---
%s:
-
`, f)), c)
testutil.Ok(t, err)
err = c.Validate()
testutil.NotOk(t, err)
testutil.Equals(t, fmt.Sprintf("empty or null section in %s", f), err.Error())
})
}
}

0 comments on commit e074152

Please sign in to comment.