1 // Package teststat provides helpers for testing metrics backends.
11 "github.com/go-kit/kit/metrics"
14 // TestCounter puts some deltas through the counter, and then calls the value
15 // func to check that the counter has the correct final value.
16 func TestCounter(counter metrics.Counter, value func() float64) error {
17 want := FillCounter(counter)
18 if have := value(); want != have {
19 return fmt.Errorf("want %f, have %f", want, have)
25 // FillCounter puts some deltas through the counter and returns the total value.
26 func FillCounter(counter metrics.Counter) float64 {
28 n := rand.Intn(len(a))
31 for i := 0; i < n; i++ {
39 // TestGauge puts some values through the gauge, and then calls the value func
40 // to check that the gauge has the correct final value.
41 func TestGauge(gauge metrics.Gauge, value func() float64) error {
43 n := rand.Intn(len(a))
46 for i := 0; i < n; i++ {
52 for i := 0; i < n; i++ {
58 if have := value(); want != have {
59 return fmt.Errorf("want %f, have %f", want, have)
65 // TestHistogram puts some observations through the histogram, and then calls
66 // the quantiles func to checks that the histogram has computed the correct
67 // quantiles within some tolerance
68 func TestHistogram(histogram metrics.Histogram, quantiles func() (p50, p90, p95, p99 float64), tolerance float64) error {
69 PopulateNormalHistogram(histogram, rand.Int())
71 want50, want90, want95, want99 := normalQuantiles()
72 have50, have90, have95, have99 := quantiles()
75 if want, have := want50, have50; !cmp(want, have, tolerance) {
76 errs = append(errs, fmt.Sprintf("p50: want %f, have %f", want, have))
78 if want, have := want90, have90; !cmp(want, have, tolerance) {
79 errs = append(errs, fmt.Sprintf("p90: want %f, have %f", want, have))
81 if want, have := want95, have95; !cmp(want, have, tolerance) {
82 errs = append(errs, fmt.Sprintf("p95: want %f, have %f", want, have))
84 if want, have := want99, have99; !cmp(want, have, tolerance) {
85 errs = append(errs, fmt.Sprintf("p99: want %f, have %f", want, have))
88 return errors.New(strings.Join(errs, "; "))
95 // Count is the number of observations.
98 // Mean is the center of the normal distribution of observations.
101 // Stdev of the normal distribution of observations.
105 // ExpectedObservationsLessThan returns the number of observations that should
106 // have a value less than or equal to the given value, given a normal
107 // distribution of observations described by Count, Mean, and Stdev.
108 func ExpectedObservationsLessThan(bucket int64) int64 {
109 // https://code.google.com/p/gostat/source/browse/stat/normal.go
110 cdf := ((1.0 / 2.0) * (1 + math.Erf((float64(bucket)-float64(Mean))/(float64(Stdev)*math.Sqrt2))))
111 return int64(cdf * float64(Count))
114 func cmp(want, have, tol float64) bool {
115 if (math.Abs(want-have) / want) > tol {