-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhttpserver_test.go
More file actions
311 lines (268 loc) · 8.12 KB
/
httpserver_test.go
File metadata and controls
311 lines (268 loc) · 8.12 KB
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
//go:generate go tool mockgen -write_package_comment=false -package httpserver -destination ./mock_test.go . Binder
package httpserver
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
"go.uber.org/mock/gomock"
)
func TestNopBinder(t *testing.T) {
t.Parallel()
require.NotNil(t, NopBinder())
}
func Test_nopBinder_BindHTTP(t *testing.T) {
t.Parallel()
require.Nil(t, NopBinder().BindHTTP(t.Context()))
}
type customMiddlewareBinder struct {
firstMiddleware chan struct{}
secondMiddleware chan struct{}
}
func (c *customMiddlewareBinder) BindHTTP(_ context.Context) []Route {
return []Route{
{
Method: http.MethodGet,
Path: "/hello",
Description: "Test endpoint",
Handler: c.handler,
Middleware: []MiddlewareFn{c.middleware(c.firstMiddleware), c.middleware(c.secondMiddleware)},
Timeout: 10 * time.Second,
},
{
Method: http.MethodGet,
Path: "/timeout",
Description: "Timeout endpoint",
Handler: c.slowHandler,
Middleware: []MiddlewareFn{c.middleware(c.firstMiddleware), c.middleware(c.secondMiddleware)},
Timeout: 1 * time.Millisecond,
},
}
}
func (c *customMiddlewareBinder) handler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}
func (c *customMiddlewareBinder) slowHandler(w http.ResponseWriter, _ *http.Request) {
time.Sleep(2 * time.Millisecond)
w.WriteHeader(http.StatusOK)
}
func (c *customMiddlewareBinder) middleware(ch chan struct{}) MiddlewareFn {
return func(_ MiddlewareArgs, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ch <- struct{}{}
next.ServeHTTP(w, r)
})
}
}
func Test_customMiddlewares(t *testing.T) {
t.Parallel()
binder := &customMiddlewareBinder{
firstMiddleware: make(chan struct{}),
secondMiddleware: make(chan struct{}),
}
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
defer cancel()
cfg := defaultConfig()
cfg.setRouter(ctx)
loadRoutes(ctx, binder, cfg)
go func() {
select {
case <-ctx.Done():
return
case <-binder.firstMiddleware:
}
select {
case <-ctx.Done():
return
case <-binder.secondMiddleware:
}
}()
resp := httptest.NewRecorder()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:1234/hello", nil)
require.NoError(t, err, "failed to create request")
cfg.router.ServeHTTP(resp, req)
require.Equal(t, http.StatusOK, resp.Code, "unexpected response code")
require.NoError(t, ctx.Err(), "context should not be canceled")
resp = httptest.NewRecorder()
req, err = http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:1234/timeout", nil)
require.NoError(t, err, "failed to create request")
cfg.router.ServeHTTP(resp, req)
require.Equal(t, http.StatusServiceUnavailable, resp.Code, "unexpected response code")
require.NoError(t, ctx.Err(), "context should not be canceled")
}
//nolint:gocognit
func TestStartServer(t *testing.T) {
t.Parallel()
tests := []struct {
name string
opts []Option
failListenPort int
setupBinder func(*MockBinder)
shutdownSig bool
wantErr bool
}{
{
name: "fail with invalid config",
opts: []Option{
WithTraceIDHeaderName(""),
},
wantErr: true,
},
{
name: "fail with option error",
opts: []Option{
WithTLSCertData([]byte(``), []byte(``)),
},
wantErr: true,
},
{
name: "fail listen port already bound",
opts: []Option{
WithServerAddr(":12345"),
WithShutdownTimeout(1 * time.Millisecond),
},
setupBinder: func(b *MockBinder) {
b.EXPECT().BindHTTP(gomock.Any()).Times(1)
},
failListenPort: 12345,
wantErr: true,
},
{
name: "succeed",
opts: []Option{
WithServerAddr(":11111"),
WithRequestTimeout(1 * time.Minute),
WithShutdownTimeout(1 * time.Millisecond),
WithEnableAllDefaultRoutes(),
WithMiddlewareFn(func(_ MiddlewareArgs, next http.Handler) http.Handler { return next }),
WithShutdownTimeout(1 * time.Second),
},
setupBinder: func(b *MockBinder) {
b.EXPECT().BindHTTP(gomock.Any()).Times(1)
},
wantErr: false,
},
{
name: "succeed and shutdown with signal",
opts: []Option{
WithServerAddr(":11112"),
WithShutdownTimeout(1 * time.Second),
},
setupBinder: func(b *MockBinder) {
b.EXPECT().BindHTTP(gomock.Any()).Times(1)
},
shutdownSig: true,
wantErr: false,
},
{
name: "succeed w/ TLS",
opts: []Option{
WithTLSCertData([]byte(`-----BEGIN CERTIFICATE-----
MIICBjCCAW8CFB9PJprToZgFfDJpt3Qk6JIEaMEEMA0GCSqGSIb3DQEBCwUAMEIx
CzAJBgNVBAYTAlhYMRUwEwYDVQQHDAxEZWZhdWx0IENpdHkxHDAaBgNVBAoME0Rl
ZmF1bHQgQ29tcGFueSBMdGQwHhcNMjAwNzIyMTMyMTExWhcNMzAwNzIwMTMyMTEx
WjBCMQswCQYDVQQGE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0s5CaWy0y7L3fOv+RwbfFSmBgsGPSq+zXKcvOGU0S5Oca
87P/AkAxinbN+p63bXC40SqmzK014Ig6IJl9IAthrERd6jySz3pIVO4DetDw+1zi
CS8ug4OQh3Yj70KtXZ7StQiTnn8xAkBgE4I+YDytq/BLZYeIu5Ef8DZkz7fXfsz5
ZFAD6gD2mWt5CJzQePIQvqW0z9SVyq+Lbiyr/FzVHUn09n9L9c7/AkA1VDTPiY/H
DSk+QcX0L58Fc7RiaBnykcJRfHnd15MlyqtUJ02iitNJOoSVBNQzr59Iyt7nGBzm
YlAqGKDZ+A+l
-----END PRIVATE KEY-----`)),
WithServerAddr(":22222"),
WithShutdownTimeout(1 * time.Millisecond),
WithEnableAllDefaultRoutes(),
},
setupBinder: func(b *MockBinder) {
b.EXPECT().BindHTTP(gomock.Any()).Times(1)
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
mockBinder := NewMockBinder(mockCtrl)
if tt.setupBinder != nil {
tt.setupBinder(mockBinder)
}
opts := tt.opts
shutdownWG := &sync.WaitGroup{}
shutdownSG := make(chan struct{})
opts = append(opts, WithShutdownWaitGroup(shutdownWG))
opts = append(opts, WithShutdownSignalChan(shutdownSG))
ctx, cancelCtx := context.WithCancel(t.Context())
defer func() {
if tt.shutdownSig {
close(shutdownSG)
}
time.Sleep(100 * time.Millisecond)
cancelCtx()
}()
if tt.failListenPort != 0 {
var lc net.ListenConfig
l, err := lc.Listen(t.Context(), "tcp", fmt.Sprintf(":%d", tt.failListenPort))
require.NoError(t, err, "failed starting pre-listener")
defer func() { _ = l.Close() }()
}
h, err := New(ctx, mockBinder, opts...)
if (err != nil) != tt.wantErr {
t.Errorf("NewLogger() error = %v, wantErr %v", err, tt.wantErr)
return
}
if err != nil || h == nil {
return
}
h.StartServer()
})
}
}
type mockListenerErr struct{}
func (ls mockListenerErr) Accept() (net.Conn, error) {
return nil, errors.New("ERROR")
}
func (ls mockListenerErr) Close() error {
return errors.New("ERROR")
}
func (ls mockListenerErr) Addr() net.Addr {
return nil
}
func Test_Serve_error(t *testing.T) {
t.Parallel()
h := &HTTPServer{
cfg: defaultConfig(),
ctx: t.Context(),
httpServer: &http.Server{
Addr: ":54321",
ReadHeaderTimeout: 1 * time.Millisecond,
ReadTimeout: 1 * time.Millisecond,
WriteTimeout: 1 * time.Millisecond,
},
listener: mockListenerErr{},
}
h.serve()
}