Skip to content

Commit 80d3f0b

Browse files
authored
Normalize empty help values in CollectAndCompare (#1378)
Due to an inconsistency in the text protocol between encoding and decoding, it was not possible to use the testutil.CollectAndCompare function to test metrics with empty help values. To fix this, normalize empty help values from the expected/want side of the test so that they compare correctly with empty values on the actual/got side of the test. Signed-off-by: Billy Keyes <[email protected]>
1 parent 3f80cd1 commit 80d3f0b

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

prometheus/testutil/testutil.go

+15
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ import (
4747
"github.com/davecgh/go-spew/spew"
4848
dto "github.com/prometheus/client_model/go"
4949
"github.com/prometheus/common/expfmt"
50+
"google.golang.org/protobuf/proto"
5051

5152
"github.com/prometheus/client_golang/prometheus"
5253
"github.com/prometheus/client_golang/prometheus/internal"
@@ -230,6 +231,20 @@ func convertReaderToMetricFamily(reader io.Reader) ([]*dto.MetricFamily, error)
230231
return nil, fmt.Errorf("converting reader to metric families failed: %w", err)
231232
}
232233

234+
// The text protocol handles empty help fields inconsistently. When
235+
// encoding, any non-nil value, include the empty string, produces a
236+
// "# HELP" line. But when decoding, the help field is only set to a
237+
// non-nil value if the "# HELP" line contains a non-empty value.
238+
//
239+
// Because metrics in a registry always have non-nil help fields, populate
240+
// any nil help fields in the parsed metrics with the empty string so that
241+
// when we compare text encodings, the results are consistent.
242+
for _, metric := range notNormalized {
243+
if metric.Help == nil {
244+
metric.Help = proto.String("")
245+
}
246+
}
247+
233248
return internal.NormalizeMetricFamilies(notNormalized), nil
234249
}
235250

prometheus/testutil/testutil_test.go

+20
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,26 @@ func TestCollectAndCompareNoLabel(t *testing.T) {
168168
}
169169
}
170170

171+
func TestCollectAndCompareNoHelp(t *testing.T) {
172+
const metadata = `
173+
# TYPE some_total counter
174+
`
175+
176+
c := prometheus.NewCounter(prometheus.CounterOpts{
177+
Name: "some_total",
178+
})
179+
c.Inc()
180+
181+
expected := `
182+
183+
some_total 1
184+
`
185+
186+
if err := CollectAndCompare(c, strings.NewReader(metadata+expected), "some_total"); err != nil {
187+
t.Errorf("unexpected collecting result:\n%s", err)
188+
}
189+
}
190+
171191
func TestCollectAndCompareHistogram(t *testing.T) {
172192
inputs := []struct {
173193
name string

0 commit comments

Comments
 (0)