@@ -164,6 +164,26 @@ func TestMetricsCollector(t *testing.T) {
164
164
templateDeleted : []bool {false },
165
165
eligible : []bool {false },
166
166
},
167
+ {
168
+ name : "deleted templates never desire prebuilds" ,
169
+ transitions : allTransitions ,
170
+ jobStatuses : allJobStatuses ,
171
+ initiatorIDs : []uuid.UUID {agplprebuilds .SystemUserID },
172
+ ownerIDs : []uuid.UUID {agplprebuilds .SystemUserID , uuid .New ()},
173
+ metrics : nil ,
174
+ templateDeleted : []bool {true },
175
+ eligible : []bool {false },
176
+ },
177
+ {
178
+ name : "running prebuilds for deleted templates are still counted, so that they can be deleted" ,
179
+ transitions : []database.WorkspaceTransition {database .WorkspaceTransitionStart },
180
+ jobStatuses : []database.ProvisionerJobStatus {database .ProvisionerJobStatusSucceeded },
181
+ initiatorIDs : []uuid.UUID {agplprebuilds .SystemUserID },
182
+ ownerIDs : []uuid.UUID {agplprebuilds .SystemUserID },
183
+ metrics : nil ,
184
+ templateDeleted : []bool {true },
185
+ eligible : []bool {false },
186
+ },
167
187
}
168
188
for _ , test := range tests {
169
189
test := test // capture for parallel
@@ -256,6 +276,12 @@ func TestMetricsCollector(t *testing.T) {
256
276
"organization_name" : org .Name ,
257
277
}
258
278
279
+ // If no expected metrics have been defined, ensure we don't find any metric series (i.e. metrics with given labels).
280
+ if test .metrics == nil {
281
+ series := findAllMetricSeries (metricsFamilies , labels )
282
+ require .Empty (t , series )
283
+ }
284
+
259
285
for _ , check := range test .metrics {
260
286
metric := findMetric (metricsFamilies , check .name , labels )
261
287
if check .value == nil {
@@ -430,3 +456,33 @@ func findMetric(metricsFamilies []*prometheus_client.MetricFamily, name string,
430
456
}
431
457
return nil
432
458
}
459
+
460
+ // findAllMetricSeries finds all metrics with a given set of labels.
461
+ func findAllMetricSeries (metricsFamilies []* prometheus_client.MetricFamily , labels map [string ]string ) map [string ]* prometheus_client.Metric {
462
+ series := make (map [string ]* prometheus_client.Metric )
463
+ for _ , metricFamily := range metricsFamilies {
464
+ for _ , metric := range metricFamily .GetMetric () {
465
+ labelPairs := metric .GetLabel ()
466
+
467
+ if len (labelPairs ) != len (labels ) {
468
+ continue
469
+ }
470
+
471
+ // Convert label pairs to map for easier lookup
472
+ metricLabels := make (map [string ]string , len (labelPairs ))
473
+ for _ , label := range labelPairs {
474
+ metricLabels [label .GetName ()] = label .GetValue ()
475
+ }
476
+
477
+ // Check if all requested labels match
478
+ for wantName , wantValue := range labels {
479
+ if metricLabels [wantName ] != wantValue {
480
+ continue
481
+ }
482
+ }
483
+
484
+ series [metricFamily .GetName ()] = metric
485
+ }
486
+ }
487
+ return series
488
+ }
0 commit comments