11

We can assert that a metric is registered and collected using testutil.CollectAndCount and testutil.CollectAndCompare etc. But is there a way to collect the metrics by metric name and the labels if it's CounterVec.

for reference https://godoc.org/github.com/prometheus/client_golang/prometheus/testutil

1
  • Hi, not sure if I understood your question entirely: do you want to test the output of a CounterVec as text or are you trying to assert that the value is correct? Commented Jan 15, 2021 at 10:01

1 Answer 1

15

As I understood your question, you want to test the value of a metric with a specific label from a metrics collection like CounterVec.

You can do so by using the ToFloat64 function in combination with the WithLabelsValue function, as in the following example:

import (
    "testing"

    "github.com/prometheus/client_golang/prometheus"
    "github.com/prometheus/client_golang/prometheus/testutil"
    "github.com/stretchr/testify/assert"
)

func TestVecMetricT(t *testing.T) {
    assert := assert.New(t)

    var C = prometheus.NewCounterVec(prometheus.CounterOpts{
        Name: "C",
        Help: "Help",
    }, []string{"subname"},
    )

    prometheus.MustRegister(C)

    C.WithLabelValues("firstLabel").Inc()
    C.WithLabelValues("secondLabel").Inc()
    C.WithLabelValues("thirdLabel").Inc()
    C.WithLabelValues("thirdLabel").Inc()

    // collected three metrics
    assert.Equal(3, testutil.CollectAndCount(C))
    // check the expected values using the ToFloat64 function
    assert.Equal(float64(1), testutil.ToFloat64(C.WithLabelValues("firstLabel")))
    assert.Equal(float64(1), testutil.ToFloat64(C.WithLabelValues("secondLabel")))
    assert.Equal(float64(2), testutil.ToFloat64(C.WithLabelValues("thirdLabel")))
}

Correct me if I'm wrong, but I don't think there a way to use the testutil package to get a slice of label values from a metric collection like CounterVec.

Sign up to request clarification or add additional context in comments.

1 Comment

This is strange. It looks like you have to use a vector to have access to the ToFloat64() functionality. At first I just had a Gauge instead of a GaugeVec and I could not see how to get the value out of it!?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.