Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

testutil.CollectAndCompare fails for metrics with empty help string #1308

Closed
bluekeyes opened this issue Jul 5, 2023 · 2 comments · Fixed by #1378
Closed

testutil.CollectAndCompare fails for metrics with empty help string #1308

bluekeyes opened this issue Jul 5, 2023 · 2 comments · Fixed by #1378

Comments

@bluekeyes
Copy link
Contributor

Version: 1.16.0

While trying to write a test for a custom collector, I discovered that the testutil.CollectAndCompare function does not work with metrics that have an empty help string. The issue appears to be a discrepancy between the encoding and decoding of the text format:

  1. When encoding metrics from a registry (i.e. the "got" side), the registry always sets Help to a non-nil value.
  2. If the Help field is non-nil, the text encoding writes a HELP line
  3. When parsing metrics from text (i.e. the "want" side), the text encoding does not populate the Help field if the line only contains whitespace after the keyword.

This example program shows how the comparison fails regardless of whether the HELP comment appears in the expected text:

Example
package main

import (
	"fmt"
	"strings"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/testutil"
)

type Collector struct{}

func (c Collector) Describe(ch chan<- *prometheus.Desc) {}

func (c Collector) Collect(ch chan<- prometheus.Metric) {
	ch <- prometheus.MustNewConstMetric(
		prometheus.NewDesc("sample_metric", "", nil, nil),
		prometheus.GaugeValue,
		0,
	)
}

func main() {
	withHelp := `
# HELP sample_metric
# TYPE sample_metric gauge
sample_metric 0
`

	withoutHelp := `
# TYPE sample_metric gauge
sample_metric 0
`
	fmt.Println("--- With HELP ---")
	fmt.Print(testutil.CollectAndCompare(Collector{}, strings.NewReader(withHelp)))

	fmt.Println()
	fmt.Println("--- Without HELP ---")
	fmt.Print(testutil.CollectAndCompare(Collector{}, strings.NewReader(withoutHelp)))
}

My guess is that the test functions should normalize empty help fields before comparing metrics, rather than changing how encoding or decoding works. If that sounds reasonable, I can look at submitting a PR.

@RubanChristian
Copy link

JS

@bwplotka
Copy link
Member

👍🏽 Thanks for this, indeed let's improve it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants