counter_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package metric
  2. import (
  3. "testing"
  4. "github.com/prometheus/client_golang/prometheus/testutil"
  5. "github.com/stretchr/testify/assert"
  6. "github.com/wuntsong-org/go-zero-plus/core/proc"
  7. "github.com/wuntsong-org/go-zero-plus/core/prometheus"
  8. )
  9. func TestNewCounterVec(t *testing.T) {
  10. counterVec := NewCounterVec(&CounterVecOpts{
  11. Namespace: "http_server",
  12. Subsystem: "requests",
  13. Name: "total",
  14. Help: "rpc client requests error count.",
  15. })
  16. defer counterVec.close()
  17. counterVecNil := NewCounterVec(nil)
  18. counterVec.Inc("path", "code")
  19. counterVec.Add(1, "path", "code")
  20. proc.Shutdown()
  21. assert.NotNil(t, counterVec)
  22. assert.Nil(t, counterVecNil)
  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. func TestCounterAdd(t *testing.T) {
  41. startAgent()
  42. counterVec := NewCounterVec(&CounterVecOpts{
  43. Namespace: "rpc_server",
  44. Subsystem: "requests",
  45. Name: "err_total",
  46. Help: "rpc client requests error count.",
  47. Labels: []string{"method", "code"},
  48. })
  49. defer counterVec.close()
  50. cv, _ := counterVec.(*promCounterVec)
  51. cv.Add(11, "/Users", "500")
  52. cv.Add(22, "/Users", "500")
  53. r := testutil.ToFloat64(cv.counter)
  54. assert.Equal(t, float64(33), r)
  55. }
  56. func startAgent() {
  57. prometheus.StartAgent(prometheus.Config{
  58. Host: "127.0.0.1",
  59. Port: 9101,
  60. Path: "/metrics",
  61. })
  62. }