github.com/lingyao2333/mo-zero@v1.4.1/core/metric/counter_test.go (about)

     1  package metric
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/lingyao2333/mo-zero/core/prometheus"
     7  	"github.com/prometheus/client_golang/prometheus/testutil"
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestNewCounterVec(t *testing.T) {
    12  	counterVec := NewCounterVec(&CounterVecOpts{
    13  		Namespace: "http_server",
    14  		Subsystem: "requests",
    15  		Name:      "total",
    16  		Help:      "rpc client requests error count.",
    17  	})
    18  	defer counterVec.close()
    19  	counterVecNil := NewCounterVec(nil)
    20  	assert.NotNil(t, counterVec)
    21  	assert.Nil(t, counterVecNil)
    22  }
    23  
    24  func TestCounterIncr(t *testing.T) {
    25  	startAgent()
    26  	counterVec := NewCounterVec(&CounterVecOpts{
    27  		Namespace: "http_client",
    28  		Subsystem: "call",
    29  		Name:      "code_total",
    30  		Help:      "http client requests error count.",
    31  		Labels:    []string{"path", "code"},
    32  	})
    33  	defer counterVec.close()
    34  	cv, _ := counterVec.(*promCounterVec)
    35  	cv.Inc("/Users", "500")
    36  	cv.Inc("/Users", "500")
    37  	r := testutil.ToFloat64(cv.counter)
    38  	assert.Equal(t, float64(2), r)
    39  }
    40  
    41  func TestCounterAdd(t *testing.T) {
    42  	startAgent()
    43  	counterVec := NewCounterVec(&CounterVecOpts{
    44  		Namespace: "rpc_server",
    45  		Subsystem: "requests",
    46  		Name:      "err_total",
    47  		Help:      "rpc client requests error count.",
    48  		Labels:    []string{"method", "code"},
    49  	})
    50  	defer counterVec.close()
    51  	cv, _ := counterVec.(*promCounterVec)
    52  	cv.Add(11, "/Users", "500")
    53  	cv.Add(22, "/Users", "500")
    54  	r := testutil.ToFloat64(cv.counter)
    55  	assert.Equal(t, float64(33), r)
    56  }
    57  
    58  func startAgent() {
    59  	prometheus.StartAgent(prometheus.Config{
    60  		Host: "127.0.0.1",
    61  		Port: 9101,
    62  		Path: "/metrics",
    63  	})
    64  }