-
Notifications
You must be signed in to change notification settings - Fork 814
/
Copy pathhandler_test.go
93 lines (82 loc) · 2.43 KB
/
handler_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
package transport
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/go-kit/kit/log"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
promtest "github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/weaveworks/common/httpgrpc"
"github.com/weaveworks/common/user"
)
type roundTripperFunc func(*http.Request) (*http.Response, error)
func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) {
return f(r)
}
func TestWriteError(t *testing.T) {
for _, test := range []struct {
status int
err error
}{
{http.StatusInternalServerError, errors.New("unknown")},
{http.StatusGatewayTimeout, context.DeadlineExceeded},
{StatusClientClosedRequest, context.Canceled},
{http.StatusBadRequest, httpgrpc.Errorf(http.StatusBadRequest, "")},
} {
t.Run(test.err.Error(), func(t *testing.T) {
w := httptest.NewRecorder()
writeError(w, test.err)
require.Equal(t, test.status, w.Result().StatusCode)
})
}
}
func TestHandler_ServeHTTP(t *testing.T) {
for _, tt := range []struct {
name string
cfg HandlerConfig
expectedMetrics int
}{
{
name: "test handler with stats enabled",
cfg: HandlerConfig{QueryStatsEnabled: true},
expectedMetrics: 3,
},
{
name: "test handler with stats disabled",
cfg: HandlerConfig{QueryStatsEnabled: false},
expectedMetrics: 0,
},
} {
t.Run(tt.name, func(t *testing.T) {
roundTripper := roundTripperFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusOK,
Body: io.NopCloser(strings.NewReader("{}")),
}, nil
})
reg := prometheus.NewPedanticRegistry()
handler := NewHandler(tt.cfg, roundTripper, log.NewNopLogger(), reg)
ctx := user.InjectOrgID(context.Background(), "12345")
req := httptest.NewRequest("GET", "/", nil)
req = req.WithContext(ctx)
resp := httptest.NewRecorder()
handler.ServeHTTP(resp, req)
_, _ = io.ReadAll(resp.Body)
require.Equal(t, resp.Code, http.StatusOK)
count, err := promtest.GatherAndCount(
reg,
"cortex_query_seconds_total",
"cortex_query_fetched_series_per_query",
"cortex_query_fetched_chunks_bytes_per_query",
)
assert.NoError(t, err)
assert.Equal(t, tt.expectedMetrics, count)
})
}
}