Skip to content

Commit 9e9cc00

Browse files
committed
Added testutil.CollectAndCount
Signed-off-by: Bartlomiej Plotka <[email protected]>
1 parent b68ba26 commit 9e9cc00

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

prometheus/testutil/testutil.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,33 @@ func ToFloat64(c prometheus.Collector) float64 {
108108
panic(fmt.Errorf("collected a non-gauge/counter/untyped metric: %s", pb))
109109
}
110110

111+
// CollectAndCount collects all Metrics from the provided Collector and returns their number.
112+
//
113+
// This can be used to assert the number of metrics collected by a given collector after certain operations.
114+
//
115+
// This function is only for testing purposes, and even for testing, other approaches
116+
// are often more appropriate (see this package's documentation).
117+
func CollectAndCount(c prometheus.Collector) int {
118+
var (
119+
mCount int
120+
mChan = make(chan prometheus.Metric)
121+
done = make(chan struct{})
122+
)
123+
124+
go func() {
125+
for range mChan {
126+
mCount++
127+
}
128+
close(done)
129+
}()
130+
131+
c.Collect(mChan)
132+
close(mChan)
133+
<-done
134+
135+
return mCount
136+
}
137+
111138
// CollectAndCompare registers the provided Collector with a newly created
112139
// pedantic Registry. It then does the same as GatherAndCompare, gathering the
113140
// metrics from the pedantic Registry.

0 commit comments

Comments
 (0)