counter_test.go 1.5 KB

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