diff --git a/prometheus/histogram_test.go b/prometheus/histogram_test.go index 5a20f4b..9e5e3a1 100644 --- a/prometheus/histogram_test.go +++ b/prometheus/histogram_test.go @@ -17,6 +17,7 @@ import ( "math" "math/rand" "reflect" + "runtime" "sort" "sync" "testing" @@ -346,3 +347,41 @@ func TestBuckets(t *testing.T) { t.Errorf("linear buckets: got %v, want %v", got, want) } } + +func TestHistogramAtomicObserve(t *testing.T) { + var ( + quit = make(chan struct{}) + his = NewHistogram(HistogramOpts{ + Buckets: []float64{0.5, 10, 20}, + }) + ) + + defer func() { close(quit) }() + + go func() { + for { + select { + case <-quit: + return + default: + his.Observe(1) + } + } + }() + + for i := 0; i < 100; i++ { + m := &dto.Metric{} + if err := his.Write(m); err != nil { + t.Fatal("unexpected error writing histogram:", err) + } + h := m.GetHistogram() + if h.GetSampleCount() != uint64(h.GetSampleSum()) || + h.GetSampleCount() != h.GetBucket()[1].GetCumulativeCount() { + t.Fatalf( + "inconsistent counts in histogram: count=%d sum=%f bucket=%d", + h.GetSampleCount(), h.GetSampleSum(), h.GetBucket()[1].GetCumulativeCount(), + ) + } + runtime.Gosched() + } +}