Allow filtering tested metrics

This allows to only verify metrics with specified names to test
a subset of exposed metrics.
This commit is contained in:
Fabian Reinartz 2016-09-09 10:11:20 +02:00
parent 5fbb042931
commit a7da0baf45
2 changed files with 25 additions and 4 deletions

View File

@ -100,7 +100,7 @@ func TestDeploymentCollector(t *testing.T) {
f: func() ([]extensions.Deployment, error) { return c.depls, nil },
},
}
if err := gatherAndCompare(dc, c.want); err != nil {
if err := gatherAndCompare(dc, c.want, nil); err != nil {
t.Errorf("unexpected collecting result:\n%s", err)
}
}
@ -108,7 +108,8 @@ func TestDeploymentCollector(t *testing.T) {
// gatherAndCompare retrieves all metrics exposed by a collector and compares it
// to an expected output in the Prometheus text exposition format.
func gatherAndCompare(c prometheus.Collector, expected string) error {
// metricNames allows only comparing the given metrics. All are compared if it's nil.
func gatherAndCompare(c prometheus.Collector, expected string, metricNames []string) error {
expected = removeUnusedWhitespace(expected)
reg := prometheus.NewPedanticRegistry()
@ -119,6 +120,9 @@ func gatherAndCompare(c prometheus.Collector, expected string) error {
if err != nil {
return fmt.Errorf("gathering metrics failed: %s", err)
}
if metricNames != nil {
metrics = filterMetrics(metrics, metricNames)
}
var tp expfmt.TextParser
expectedMetrics, err := tp.TextToMetricFamilies(bytes.NewReader([]byte(expected)))
if err != nil {
@ -157,11 +161,28 @@ got:
return nil
}
func filterMetrics(metrics []*dto.MetricFamily, names []string) []*dto.MetricFamily {
var filtered []*dto.MetricFamily
for _, m := range metrics {
drop := true
for _, name := range names {
if m.GetName() == name {
drop = false
break
}
}
if !drop {
filtered = append(filtered, m)
}
}
return filtered
}
func removeUnusedWhitespace(s string) string {
var (
trimmedLine string
trimmedLines []string
lines []string = strings.Split(s, "\n")
lines = strings.Split(s, "\n")
)
for _, l := range lines {

View File

@ -89,7 +89,7 @@ func TestPodCollector(t *testing.T) {
f: func() ([]*api.Pod, error) { return c.pods, nil },
},
}
if err := gatherAndCompare(pc, c.want); err != nil {
if err := gatherAndCompare(pc, c.want, nil); err != nil {
t.Errorf("unexpected collecting result:\n%s", err)
}
}