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
|
package httptransport
import (
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/require"
)
func Test_withRoundTripper(t *testing.T) {
tests := []struct {
name string
statusCode int
err error
}{
{
name: "successful_response",
statusCode: http.StatusNoContent,
},
{
name: "error_response",
statusCode: http.StatusForbidden,
},
{
name: "internal_error_response",
statusCode: http.StatusInternalServerError,
},
{
name: "unhandled_status_response",
statusCode: http.StatusPermanentRedirect,
},
{
name: "client_error",
err: fmt.Errorf("something went wrong"),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gaugeVec := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Name: t.Name(),
}, []string{"status_code"})
counterVec := prometheus.NewCounterVec(prometheus.CounterOpts{
Name: t.Name(),
}, []string{"status_code"})
next := &mockRoundTripper{
res: &http.Response{
StatusCode: tt.statusCode,
},
err: tt.err,
}
mtr := &meteredRoundTripper{next, gaugeVec, counterVec}
r := httptest.NewRequest("GET", "/", nil)
res, err := mtr.RoundTrip(r)
if tt.err != nil {
counterCount := testutil.ToFloat64(counterVec.WithLabelValues("error"))
require.Equal(t, float64(1), counterCount, "error")
return
}
require.NoError(t, err)
require.NotNil(t, res)
statusCode := strconv.Itoa(res.StatusCode)
gaugeValue := testutil.ToFloat64(gaugeVec.WithLabelValues(statusCode))
require.Greater(t, gaugeValue, float64(0))
counterCount := testutil.ToFloat64(counterVec.WithLabelValues(statusCode))
require.Equal(t, float64(1), counterCount, statusCode)
})
}
}
type mockRoundTripper struct {
res *http.Response
err error
}
func (mrt *mockRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
return mrt.res, mrt.err
}
|