Skip to content

Commit

Permalink
Merge pull request #703 from prometheus/testutil-metric-count
Browse files Browse the repository at this point in the history
Added `testutil.CollectAndCount`
  • Loading branch information
beorn7 committed Jan 9, 2020
2 parents b68ba26 + 9e9cc00 commit 803ef2a
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions prometheus/testutil/testutil.go
Expand Up @@ -108,6 +108,33 @@ func ToFloat64(c prometheus.Collector) float64 {
panic(fmt.Errorf("collected a non-gauge/counter/untyped metric: %s", pb))
}

// CollectAndCount collects all Metrics from the provided Collector and returns their number.
//
// This can be used to assert the number of metrics collected by a given collector after certain operations.
//
// This function is only for testing purposes, and even for testing, other approaches
// are often more appropriate (see this package's documentation).
func CollectAndCount(c prometheus.Collector) int {
var (
mCount int
mChan = make(chan prometheus.Metric)
done = make(chan struct{})
)

go func() {
for range mChan {
mCount++
}
close(done)
}()

c.Collect(mChan)
close(mChan)
<-done

return mCount
}

// CollectAndCompare registers the provided Collector with a newly created
// pedantic Registry. It then does the same as GatherAndCompare, gathering the
// metrics from the pedantic Registry.
Expand Down

0 comments on commit 803ef2a

Please sign in to comment.