-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassert.go
More file actions
80 lines (70 loc) · 2.3 KB
/
Copy pathassert.go
File metadata and controls
80 lines (70 loc) · 2.3 KB
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
package ph
import (
"fmt"
"strings"
"testing"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
)
// AssertMetricExists asserts that a metric with the given fully-qualified name was gathered from
// gatherer. For Vec types that have no observations, it also checks registered descriptors if
// gatherer is a *TrackingRegistry.
func AssertMetricExists(t *testing.T, gatherer prometheus.Gatherer, name string) {
t.Helper()
g, err := gatherer.Gather()
assert.NoError(t, err)
for _, metric := range g {
if metric.GetName() == name {
return
}
}
// Vec metrics with no observations don't appear in Gather; fall back to descriptor check.
if tr, ok := gatherer.(*TrackingRegistry); ok {
tr.mu.Lock()
descs := make([]*prometheus.Desc, len(tr.descs))
copy(descs, tr.descs)
tr.mu.Unlock()
needle := fmt.Sprintf("fqName: %q", name)
for _, d := range descs {
if strings.Contains(d.String(), needle) {
return
}
}
}
assert.Fail(t, fmt.Sprintf("Metric %s not found", name))
}
// AssertMetricNotExists asserts that no metric with the given fully-qualified name was
// gathered from gatherer. It checks both Gather results and registered descriptors so
// that Vec metrics with no observations are also covered.
func AssertMetricNotExists(t *testing.T, gatherer prometheus.Gatherer, name string) {
t.Helper()
g, err := gatherer.Gather()
assert.NoError(t, err)
for _, metric := range g {
if metric.GetName() == name {
assert.Fail(t, fmt.Sprintf("Metric %s was found but should not exist", name))
return
}
}
// Also check descriptors for Vec metrics that have no observations yet.
if tr, ok := gatherer.(*TrackingRegistry); ok {
tr.mu.Lock()
descs := make([]*prometheus.Desc, len(tr.descs))
copy(descs, tr.descs)
tr.mu.Unlock()
needle := fmt.Sprintf("fqName: %q", name)
for _, d := range descs {
if strings.Contains(d.String(), needle) {
assert.Fail(t, fmt.Sprintf("Metric %s was found in descriptors but should not exist", name))
return
}
}
}
}
// AssertMetricsCount asserts that exactly expectedCount metrics were gathered from gatherer.
func AssertMetricsCount(t *testing.T, gatherer prometheus.Gatherer, expectedCount int) {
t.Helper()
g, err := gatherer.Gather()
assert.NoError(t, err)
assert.Equal(t, expectedCount, len(g))
}