Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test using golang prometheus testutil

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

like image 648
Viraths Avatar asked Mar 29 '26 20:03

Viraths


1 Answers

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.

like image 188
katexochen Avatar answered Apr 02 '26 12:04

katexochen