diff --git a/prometheus/testutil/testutil.go b/prometheus/testutil/testutil.go index 4c72bc6cb..1108b451d 100644 --- a/prometheus/testutil/testutil.go +++ b/prometheus/testutil/testutil.go @@ -108,6 +108,34 @@ func ToFloat64(c prometheus.Collector) float64 { panic(fmt.Errorf("collected a non-gauge/counter/untyped metric: %s", pb)) } +// MetricCount collects all Metrics from the provided Collector and counts them. +// +// Typical use case is when you want to assert certain number of series of given collector after +// some operation. +// +// This function is only for testing purposes, and even for testing, other approaches +// are often more appropriate (see this package's documentation). +func MetricCount(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.