Unit test using golang prometheus testutil

Viewed 3826
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.

Related