Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/grafana-agent
Path: blob/main/component/loki/process/internal/metric/counters_test.go
4096 views
1
package metric
2
3
import (
4
"testing"
5
"time"
6
7
"github.com/prometheus/client_golang/prometheus"
8
"github.com/prometheus/common/model"
9
"github.com/stretchr/testify/assert"
10
)
11
12
func TestCounterExpiration(t *testing.T) {
13
t.Parallel()
14
cfg := &CounterConfig{
15
Action: "inc",
16
Description: "HELP ME!!!!!",
17
MaxIdle: 1 * time.Second,
18
}
19
20
cnt, err := NewCounters("test1", cfg)
21
assert.Nil(t, err)
22
23
// Create a label and increment the counter
24
lbl1 := model.LabelSet{}
25
lbl1["test"] = "i don't wanna make this a constant"
26
cnt.With(lbl1).Inc()
27
28
// Collect the metrics, should still find the metric in the map
29
collect(cnt)
30
assert.Contains(t, cnt.metrics, lbl1.Fingerprint())
31
32
time.Sleep(1100 * time.Millisecond) // Wait just past our max idle of 1 sec
33
34
//Add another counter with new label val
35
lbl2 := model.LabelSet{}
36
lbl2["test"] = "eat this linter"
37
cnt.With(lbl2).Inc()
38
39
// Collect the metrics, first counter should have expired and removed, second should still be present
40
collect(cnt)
41
assert.NotContains(t, cnt.metrics, lbl1.Fingerprint())
42
assert.Contains(t, cnt.metrics, lbl2.Fingerprint())
43
}
44
45
func collect(c prometheus.Collector) {
46
done := make(chan struct{})
47
collector := make(chan prometheus.Metric)
48
49
go func() {
50
defer close(done)
51
c.Collect(collector)
52
}()
53
54
for {
55
select {
56
case <-collector:
57
case <-done:
58
return
59
}
60
}
61
}
62
63