forked from kuskoman/logstash-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collector_manager_test.go
114 lines (95 loc) · 2.55 KB
/
collector_manager_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package collectors
import (
"context"
"errors"
"sync"
"testing"
"github.com/prometheus/client_golang/prometheus"
)
func TestNewCollectorManager(t *testing.T) {
mockEndpoint := "http://localhost:9600"
cm := NewCollectorManager(mockEndpoint)
if cm == nil {
t.Error("Expected collector manager to be initialized")
}
}
type mockCollector struct {
shouldFail bool
}
func newMockCollector(shouldFail bool) *mockCollector {
return &mockCollector{
shouldFail: shouldFail,
}
}
func (m *mockCollector) Collect(ctx context.Context, ch chan<- prometheus.Metric) error {
if m.shouldFail {
return errors.New("mock collector failed")
}
ch <- prometheus.MustNewConstMetric(
prometheus.NewDesc("mock_metric", "mock metric description", nil, nil),
prometheus.GaugeValue,
1,
)
return nil
}
func TestCollect(t *testing.T) {
t.Run("should fail", func(t *testing.T) {
cm := &CollectorManager{
collectors: map[string]Collector{
"mock": newMockCollector(true),
},
scrapeDurations: getScrapeDurationsCollector(),
}
ch := make(chan prometheus.Metric)
var wg sync.WaitGroup
wg.Add(1)
go func() {
cm.Collect(ch)
wg.Done()
}()
select {
case <-ch:
t.Error("Expected no metric to be sent to the channel")
case <-func() chan struct{} {
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
return done
}():
// No metric was sent to the channel, which is expected.
}
})
t.Run("should succeed", func(t *testing.T) {
cm := &CollectorManager{
collectors: map[string]Collector{
"mock": newMockCollector(false),
},
scrapeDurations: getScrapeDurationsCollector(),
}
ch := make(chan prometheus.Metric)
go cm.Collect(ch)
metric := <-ch
desc := metric.Desc()
expectedDesc := "Desc{fqName: \"mock_metric\", help: \"mock metric description\", constLabels: {}, variableLabels: {}}"
if desc.String() != expectedDesc {
t.Errorf("Expected metric description to be '%s', got %s", expectedDesc, desc.String())
}
})
}
func TestDescribe(t *testing.T) {
cm := &CollectorManager{
collectors: map[string]Collector{
"mock": newMockCollector(false),
},
scrapeDurations: getScrapeDurationsCollector(),
}
ch := make(chan *prometheus.Desc, 1)
cm.Describe(ch)
desc := <-ch
expectedDesc := "Desc{fqName: \"logstash_exporter_scrape_duration_seconds\", help: \"logstash_exporter: Duration of a scrape job.\", constLabels: {}, variableLabels: {collector,result}}"
if desc.String() != expectedDesc {
t.Errorf("Expected metric description to be '%s', got %s", expectedDesc, desc.String())
}
}