-
Notifications
You must be signed in to change notification settings - Fork 12
/
health_check_test.go
243 lines (192 loc) · 8.54 KB
/
health_check_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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*
Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/
package httpserver
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/acronis/go-appkit/httpserver/middleware"
"github.com/acronis/go-appkit/log"
"github.com/acronis/go-appkit/log/logtest"
"github.com/acronis/go-appkit/restapi"
)
func TestHealthCheckHandler_ServeHTTP(t *testing.T) {
t.Run("health-check returns error", func(t *testing.T) {
var internalError = errors.New("internal error")
h := NewHealthCheckHandler(func() (HealthCheckResult, error) {
return nil, internalError
})
resp := httptest.NewRecorder()
logRecorder := logtest.NewRecorder()
h.ServeHTTP(resp, makeHealthCheckRequest(context.Background(), logRecorder))
require.Equal(t, http.StatusInternalServerError, resp.Code)
requireHealthCheckErrorWasLogged(t, logRecorder, internalError)
})
t.Run("health-check with empty components", func(t *testing.T) {
h := NewHealthCheckHandler(func() (HealthCheckResult, error) {
return HealthCheckResult{}, nil
})
resp := httptest.NewRecorder()
h.ServeHTTP(resp, makeHealthCheckRequest(context.Background(), log.NewDisabledLogger()))
require.Equal(t, http.StatusOK, resp.Code)
require.Equal(t, restapi.ContentTypeAppJSON, resp.Header().Get("Content-Type"))
})
t.Run("health-check returns unhealthy components", func(t *testing.T) {
h := NewHealthCheckHandler(func() (HealthCheckResult, error) {
return HealthCheckResult{
"db": HealthCheckStatusOK,
"amqp": HealthCheckStatusFail,
}, nil
})
resp := httptest.NewRecorder()
h.ServeHTTP(resp, makeHealthCheckRequest(context.Background(), log.NewDisabledLogger()))
require.Equal(t, http.StatusServiceUnavailable, resp.Code)
require.Equal(t, restapi.ContentTypeAppJSON, resp.Header().Get("Content-Type"))
var gotRespData healthCheckResponseData
require.NoError(t, json.NewDecoder(resp.Body).Decode(&gotRespData))
wantRespData := healthCheckResponseData{Components: map[string]bool{"db": true, "amqp": false}}
require.Equal(t, wantRespData, gotRespData)
})
t.Run("health-check returns healthy components", func(t *testing.T) {
h := NewHealthCheckHandler(func() (HealthCheckResult, error) {
return HealthCheckResult{
"db": HealthCheckStatusOK,
"amqp": HealthCheckStatusOK,
}, nil
})
resp := httptest.NewRecorder()
h.ServeHTTP(resp, makeHealthCheckRequest(context.Background(), log.NewDisabledLogger()))
require.Equal(t, http.StatusOK, resp.Code)
require.Equal(t, restapi.ContentTypeAppJSON, resp.Header().Get("Content-Type"))
var gotRespData healthCheckResponseData
require.NoError(t, json.NewDecoder(resp.Body).Decode(&gotRespData))
wantRespData := healthCheckResponseData{Components: map[string]bool{"db": true, "amqp": true}}
require.Equal(t, wantRespData, gotRespData)
})
t.Run("Default HealthCheck responds error on client cancel", func(t *testing.T) {
h := NewHealthCheckHandlerContext(nil)
resp := httptest.NewRecorder()
ctx, cancel := context.WithCancel(context.Background())
cancel() // cancel context immediately so default handler detects error
h.ServeHTTP(resp, makeHealthCheckRequest(ctx, log.NewDisabledLogger()))
require.Equal(t, StatusClientClosedRequest, resp.Code)
})
}
func TestHealthCheckHandlerContext_ServeHTTP(t *testing.T) {
t.Run("health-check returns error", func(t *testing.T) {
var internalError = errors.New("internal error")
h := NewHealthCheckHandlerContext(func(_ context.Context) (HealthCheckResult, error) {
return nil, internalError
})
resp := httptest.NewRecorder()
logRecorder := logtest.NewRecorder()
h.ServeHTTP(resp, makeHealthCheckRequest(context.Background(), logRecorder))
require.Equal(t, http.StatusInternalServerError, resp.Code)
requireHealthCheckErrorWasLogged(t, logRecorder, internalError)
})
t.Run("health-check with empty components", func(t *testing.T) {
h := NewHealthCheckHandlerContext(func(_ context.Context) (HealthCheckResult, error) {
return HealthCheckResult{}, nil
})
resp := httptest.NewRecorder()
h.ServeHTTP(resp, makeHealthCheckRequest(context.Background(), log.NewDisabledLogger()))
require.Equal(t, http.StatusOK, resp.Code)
require.Equal(t, restapi.ContentTypeAppJSON, resp.Header().Get("Content-Type"))
})
t.Run("health-check returns unhealthy components", func(t *testing.T) {
h := NewHealthCheckHandlerContext(func(_ context.Context) (HealthCheckResult, error) {
return HealthCheckResult{
"db": HealthCheckStatusOK,
"amqp": HealthCheckStatusFail,
}, nil
})
resp := httptest.NewRecorder()
h.ServeHTTP(resp, makeHealthCheckRequest(context.Background(), log.NewDisabledLogger()))
require.Equal(t, http.StatusServiceUnavailable, resp.Code)
require.Equal(t, restapi.ContentTypeAppJSON, resp.Header().Get("Content-Type"))
var gotRespData healthCheckResponseData
require.NoError(t, json.NewDecoder(resp.Body).Decode(&gotRespData))
wantRespData := healthCheckResponseData{Components: map[string]bool{"db": true, "amqp": false}}
require.Equal(t, wantRespData, gotRespData)
})
t.Run("health-check returns healthy components", func(t *testing.T) {
h := NewHealthCheckHandlerContext(func(_ context.Context) (HealthCheckResult, error) {
return HealthCheckResult{
"db": HealthCheckStatusOK,
"amqp": HealthCheckStatusOK,
}, nil
})
resp := httptest.NewRecorder()
h.ServeHTTP(resp, makeHealthCheckRequest(context.Background(), log.NewDisabledLogger()))
require.Equal(t, http.StatusOK, resp.Code)
require.Equal(t, restapi.ContentTypeAppJSON, resp.Header().Get("Content-Type"))
var gotRespData healthCheckResponseData
require.NoError(t, json.NewDecoder(resp.Body).Decode(&gotRespData))
wantRespData := healthCheckResponseData{Components: map[string]bool{"db": true, "amqp": true}}
require.Equal(t, wantRespData, gotRespData)
})
t.Run("health-check responds error on client timeout", func(t *testing.T) {
const requestTimeout = 100 * time.Millisecond
h := NewHealthCheckHandlerContext(func(ctx context.Context) (HealthCheckResult, error) {
select {
case <-ctx.Done():
case <-time.After(requestTimeout * 2):
}
return HealthCheckResult{}, ctx.Err()
})
resp := httptest.NewRecorder()
logRecorder := logtest.NewRecorder()
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
h.ServeHTTP(resp, makeHealthCheckRequest(ctx, logRecorder))
require.Equal(t, http.StatusInternalServerError, resp.Code)
require.ErrorIs(t, ctx.Err(), context.DeadlineExceeded)
requireHealthCheckErrorWasLogged(t, logRecorder, ctx.Err())
})
t.Run("default HealthCheckContext function responds error on client cancel", func(t *testing.T) {
h := NewHealthCheckHandlerContext(func(ctx context.Context) (HealthCheckResult, error) {
return HealthCheckResult{}, ctx.Err()
})
resp := httptest.NewRecorder()
logRecorder := logtest.NewRecorder()
ctx, cancel := context.WithCancel(context.Background())
cancel() // cancel context immediately so default handler detects error
h.ServeHTTP(resp, makeHealthCheckRequest(ctx, logRecorder))
require.Equal(t, StatusClientClosedRequest, resp.Code)
require.ErrorIs(t, ctx.Err(), context.Canceled)
requireHealthCheckErrorWasLogged(t, logRecorder, ctx.Err())
})
t.Run("HealthCheckContext that doesn't return ctx.Err() responds error on client cancel", func(t *testing.T) {
h := NewHealthCheckHandlerContext(func(ctx context.Context) (HealthCheckResult, error) {
return HealthCheckResult{}, nil
})
resp := httptest.NewRecorder()
ctx, cancel := context.WithCancel(context.Background())
cancel() // cancel context immediately so default handler detects error
ctx = middleware.NewContextWithLogger(ctx, log.NewDisabledLogger())
req := httptest.NewRequest(http.MethodGet, "/", nil).WithContext(ctx)
h.ServeHTTP(resp, req)
require.Equal(t, StatusClientClosedRequest, resp.Code)
})
}
func makeHealthCheckRequest(ctx context.Context, logger log.FieldLogger) *http.Request {
req := httptest.NewRequest(http.MethodGet, "/", http.NoBody)
return req.WithContext(middleware.NewContextWithLogger(ctx, logger))
}
func requireHealthCheckErrorWasLogged(t *testing.T, logRecorder *logtest.Recorder, wantErr error) {
t.Helper()
loggedEntries := logRecorder.Entries()
require.Len(t, loggedEntries, 1)
require.Equal(t, log.LevelError, loggedEntries[0].Level)
require.Contains(t, loggedEntries[0].Text, "error while checking health")
loggedErrorField, found := loggedEntries[0].FindField("error")
require.True(t, found)
require.Equal(t, wantErr, loggedErrorField.Any)
}