This repository has been archived by the owner on Oct 30, 2022. It is now read-only.
/
promredis_test.go
102 lines (87 loc) · 1.96 KB
/
promredis_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 promredis
import (
"bufio"
"context"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/go-redis/redis/v8"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
func TestRegister(t *testing.T) {
ctx := context.Background()
rc := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
defer rc.Close()
if err := rc.Ping(ctx).Err(); err != nil {
t.Fatal(err)
}
c := NewPoolStatsCollector(rc)
if err := prometheus.Register(c); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { prometheus.Unregister(c) })
for i := 0; i < 100; i++ {
k := "key" + strconv.Itoa(i)
rc.Set(ctx, k, i, -1)
rc.Get(ctx, k)
}
time.Sleep(1 * time.Second)
ph := promhttp.Handler()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
ph.ServeHTTP(rec, req)
resp := rec.Result()
hitsName := fqName("hits")
missesName := fqName("misses")
timeoutsName := fqName("timeouts")
totalConnsName := fqName("total_conns")
idleConnsName := fqName("idle_conns")
staleConnsName := fqName("stale_conns")
all := []string{
hitsName,
missesName,
timeoutsName,
totalConnsName,
idleConnsName,
staleConnsName,
}
type result struct {
found bool
value float64
}
results := make(map[string]result)
for _, name := range all {
results[name] = result{found: false}
}
s := bufio.NewScanner(resp.Body)
for s.Scan() {
line := s.Text()
println(line)
if strings.HasPrefix(line, "#") {
continue
}
for _, name := range all {
if strings.Contains(line, name) {
value, err := strconv.ParseFloat(strings.Split(line, " ")[1], 10)
if err != nil {
t.Fatal(err)
}
results[name] = result{found: true, value: value}
}
}
}
for name, result := range results {
if !result.found {
t.Errorf("%s is not found", name)
}
}
if v := results[hitsName].value; v == 0 {
t.Errorf("%s should not be 0, but got %v", hitsName, v)
}
}