-
Notifications
You must be signed in to change notification settings - Fork 3
/
hook_test.go
102 lines (81 loc) · 2.32 KB
/
hook_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
package redisprom_test
import (
"context"
"errors"
"strings"
"testing"
"github.com/go-redis/redis/v8"
"github.com/prometheus/client_golang/prometheus"
dto "github.com/prometheus/client_model/go"
"github.com/stretchr/testify/assert"
"github.com/globocom/go-redis-prometheus"
)
func TestHook(t *testing.T) {
assert := assert.New(t)
t.Run("create a new hook", func(t *testing.T) {
// act
sut := redisprom.NewHook()
// assert
assert.NotNil(sut)
})
t.Run("do not panic if metrics are already registered", func(t *testing.T) {
// arrange
_ = redisprom.NewHook()
// act/assert
assert.NotPanics(func() {
_ = redisprom.NewHook()
})
})
t.Run("export metrics after a command is processed", func(t *testing.T) {
// arrange
sut := redisprom.NewHook(
redisprom.WithNamespace("namespace1"),
redisprom.WithDurationBuckets([]float64{0.1, 0.2}),
)
cmd := redis.NewStringCmd(context.TODO(), "get")
cmd.SetErr(errors.New("some error"))
// act
ctx, err1 := sut.BeforeProcess(context.TODO(), cmd)
err2 := sut.AfterProcess(ctx, cmd)
// assert
assert.Nil(err1)
assert.Nil(err2)
metrics, err := prometheus.DefaultGatherer.Gather()
assert.Nil(err)
assert.ElementsMatch([]string{
"namespace1_redis_single_commands",
"namespace1_redis_single_errors",
}, filter(metrics, "namespace1"))
})
t.Run("export metrics after a pipeline is processed", func(t *testing.T) {
// arrange
sut := redisprom.NewHook(
redisprom.WithNamespace("namespace2"),
redisprom.WithDurationBuckets([]float64{0.1, 0.2}),
)
cmd := redis.NewStringCmd(context.TODO(), "get")
cmd.SetErr(errors.New("some error"))
// act
ctx, err1 := sut.BeforeProcessPipeline(context.TODO(), []redis.Cmder{cmd})
err2 := sut.AfterProcessPipeline(ctx, []redis.Cmder{cmd})
// assert
assert.Nil(err1)
assert.Nil(err2)
metrics, err := prometheus.DefaultGatherer.Gather()
assert.Nil(err)
assert.ElementsMatch([]string{
"namespace2_redis_single_commands",
"namespace2_redis_pipelined_commands",
"namespace2_redis_pipelined_errors",
}, filter(metrics, "namespace2"))
})
}
func filter(metrics []*dto.MetricFamily, namespace string) []string {
var result []string
for _, metric := range metrics {
if strings.HasPrefix(*metric.Name, namespace) {
result = append(result, *metric.Name)
}
}
return result
}