histogram_test.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package metric
  2. import (
  3. "strings"
  4. "testing"
  5. "github.com/prometheus/client_golang/prometheus/testutil"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestNewHistogramVec(t *testing.T) {
  9. histogramVec := NewHistogramVec(&HistogramVecOpts{
  10. Name: "duration_ms",
  11. Help: "rpc server requests duration(ms).",
  12. Buckets: []float64{1, 2, 3},
  13. })
  14. defer histogramVec.close()
  15. histogramVecNil := NewHistogramVec(nil)
  16. assert.NotNil(t, histogramVec)
  17. assert.Nil(t, histogramVecNil)
  18. }
  19. func TestHistogramObserve(t *testing.T) {
  20. histogramVec := NewHistogramVec(&HistogramVecOpts{
  21. Name: "counts",
  22. Help: "rpc server requests duration(ms).",
  23. Buckets: []float64{1, 2, 3},
  24. Labels: []string{"method"},
  25. })
  26. defer histogramVec.close()
  27. hv, _ := histogramVec.(*promHistogramVec)
  28. hv.Observe(2, "/Users")
  29. metadata := `
  30. # HELP counts rpc server requests duration(ms).
  31. # TYPE counts histogram
  32. `
  33. val := `
  34. counts_bucket{method="/Users",le="1"} 0
  35. counts_bucket{method="/Users",le="2"} 1
  36. counts_bucket{method="/Users",le="3"} 1
  37. counts_bucket{method="/Users",le="+Inf"} 1
  38. counts_sum{method="/Users"} 2
  39. counts_count{method="/Users"} 1
  40. `
  41. err := testutil.CollectAndCompare(hv.histogram, strings.NewReader(metadata+val))
  42. assert.Nil(t, err)
  43. }