Skip to content

Commit

Permalink
Merge pull request prometheus#478 from prometheus/beorn7/testing2
Browse files Browse the repository at this point in the history
 Add a concurrent end-to-end test for observe-register-gather
  • Loading branch information
beorn7 authored Oct 10, 2018
2 parents e5d4a24 + 5e8ac3c commit 7866eea
Showing 1 changed file with 99 additions and 0 deletions.
99 changes: 99 additions & 0 deletions prometheus/registry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@ package prometheus_test

import (
"bytes"
"math/rand"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"

dto "github.com/prometheus/client_model/go"

Expand Down Expand Up @@ -772,3 +775,99 @@ func TestAlreadyRegistered(t *testing.T) {
t.Error("unexpected error:", err)
}
}

// TestHistogramVecRegisterGatherConcurrency is an end-to-end test that
// concurrently calls Observe on random elements of a HistogramVec while the
// same HistogramVec is registered concurrently and the Gather method of the
// registry is called concurrently.
func TestHistogramVecRegisterGatherConcurrency(t *testing.T) {
var (
reg = prometheus.NewPedanticRegistry()
hv = prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "test_histogram",
Help: "This helps testing.",
ConstLabels: prometheus.Labels{"foo": "bar"},
},
[]string{"one", "two", "three"},
)
labelValues = []string{"a", "b", "c", "alpha", "beta", "gamma", "aleph", "beth", "gimel"}
quit = make(chan struct{})
wg sync.WaitGroup
)

observe := func() {
defer wg.Done()
for {
select {
case <-quit:
return
default:
obs := rand.NormFloat64()*.1 + .2
hv.WithLabelValues(
labelValues[rand.Intn(len(labelValues))],
labelValues[rand.Intn(len(labelValues))],
labelValues[rand.Intn(len(labelValues))],
).Observe(obs)
}
}
}

register := func() {
defer wg.Done()
for {
select {
case <-quit:
return
default:
if err := reg.Register(hv); err != nil {
if _, ok := err.(prometheus.AlreadyRegisteredError); !ok {
t.Error("Registering failed:", err)
}
}
time.Sleep(7 * time.Millisecond)
}
}
}

gather := func() {
defer wg.Done()
for {
select {
case <-quit:
return
default:
if g, err := reg.Gather(); err != nil {
t.Error("Gathering failed:", err)
} else {
if len(g) == 0 {
continue
}
if len(g) != 1 {
t.Error("Gathered unexpected number of metric families:", len(g))
}
if len(g[0].Metric[0].Label) != 4 {
t.Error("Gathered unexpected number of label pairs:", len(g[0].Metric[0].Label))
}
}
time.Sleep(4 * time.Millisecond)
}
}
}

wg.Add(10)
go observe()
go observe()
go register()
go observe()
go gather()
go observe()
go register()
go observe()
go gather()
go observe()

time.Sleep(time.Second)
close(quit)
wg.Wait()
}

0 comments on commit 7866eea

Please sign in to comment.