@@ -112,31 +112,43 @@ func ToFloat64(c prometheus.Collector) float64 {
112
112
panic (fmt .Errorf ("collected a non-gauge/counter/untyped metric: %s" , pb ))
113
113
}
114
114
115
- // CollectAndCount collects all Metrics from the provided Collector and returns their number.
116
- //
117
- // This can be used to assert the number of metrics collected by a given collector after certain operations.
118
- //
119
- // This function is only for testing purposes, and even for testing, other approaches
120
- // are often more appropriate (see this package's documentation).
121
- func CollectAndCount (c prometheus.Collector ) int {
122
- var (
123
- mCount int
124
- mChan = make (chan prometheus.Metric )
125
- done = make (chan struct {})
126
- )
127
-
128
- go func () {
129
- for range mChan {
130
- mCount ++
131
- }
132
- close (done )
133
- }()
115
+ // CollectAndCount registers the provided Collector with a newly created
116
+ // pedantic Registry. It then calls GatherAndCount with that Registry and with
117
+ // the provided metricNames. In the unlikely case that the registration or the
118
+ // gathering fails, this function panics. (This is inconsistent with the other
119
+ // CollectAnd… functions in this package and has historical reasons. Changing
120
+ // the function signature would be a breaking change and will therefore only
121
+ // happen with the next major version bump.)
122
+ func CollectAndCount (c prometheus.Collector , metricNames ... string ) int {
123
+ reg := prometheus .NewPedanticRegistry ()
124
+ if err := reg .Register (c ); err != nil {
125
+ panic (fmt .Errorf ("registering collector failed: %s" , err ))
126
+ }
127
+ result , err := GatherAndCount (reg , metricNames ... )
128
+ if err != nil {
129
+ panic (err )
130
+ }
131
+ return result
132
+ }
134
133
135
- c .Collect (mChan )
136
- close (mChan )
137
- <- done
134
+ // GatherAndCount gathers all metrics from the provided Gatherer and counts
135
+ // them. It returns the number of metric children in all gathered metric
136
+ // families together. If any metricNames are provided, only metrics with those
137
+ // names are counted.
138
+ func GatherAndCount (g prometheus.Gatherer , metricNames ... string ) (int , error ) {
139
+ got , err := g .Gather ()
140
+ if err != nil {
141
+ return 0 , fmt .Errorf ("gathering metrics failed: %s" , err )
142
+ }
143
+ if metricNames != nil {
144
+ got = filterMetrics (got , metricNames )
145
+ }
138
146
139
- return mCount
147
+ result := 0
148
+ for _ , mf := range got {
149
+ result += len (mf .GetMetric ())
150
+ }
151
+ return result , nil
140
152
}
141
153
142
154
// CollectAndCompare registers the provided Collector with a newly created
0 commit comments