-
Notifications
You must be signed in to change notification settings - Fork 0
/
router_test.go
369 lines (279 loc) · 9.98 KB
/
router_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
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package medium
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/stretchr/testify/require"
)
func TestHappyPath(t *testing.T) {
router := New(WithNoData)
router.Use(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
rw.Header().Add("x-from-middleware", "wow")
next(rw, r)
})
router.Before(func(ctx context.Context, req *Request[NoData], next Next) Response {
res := next(ctx)
res.Header().Add("x-from-before", "amazing")
return res
})
router.Get("/hello/:name", func(ctx context.Context, r *Request[NoData]) Response {
require.Equal(t, "/hello/:name", r.MatchedPath())
return StringResponse(http.StatusOK, fmt.Sprintf("hello %s", r.Params()["name"]))
})
req := httptest.NewRequest(http.MethodGet, "/hello/Fox%20Mulder", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.Equal(t, "hello Fox Mulder", rw.Body.String())
require.Equal(t, "wow", rw.Header().Get("x-from-middleware"))
require.Equal(t, "amazing", rw.Header().Get("x-from-before"))
}
func TestGroup_RouteMethods(t *testing.T) {
testCases := map[string]struct {
method string
}{
"Get": {method: http.MethodGet},
"Post": {method: http.MethodPost},
"Put": {method: http.MethodPut},
"Patch": {method: http.MethodPatch},
"Delete": {method: http.MethodDelete},
}
router := New(WithNoData)
for name, tc := range testCases {
path := reflect.ValueOf("/")
var handler HandlerFunc[NoData] = func(ctx context.Context, r *Request[NoData]) Response {
res := NewResponse()
res.WriteStatus(http.StatusOK)
res.WriteString("hello")
return res
}
handlerValue := reflect.ValueOf(handler)
t.Run(name, func(t *testing.T) {
reflect.ValueOf(router).MethodByName(name).Call([]reflect.Value{path, handlerValue})
req := httptest.NewRequest(tc.method, "/", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.Equal(t, 200, rw.Code)
})
}
}
func TestRouter_Post(t *testing.T) {
router := New(WithNoData)
router.Post("/hello/:name", func(ctx context.Context, r *Request[NoData]) Response {
return StringResponse(http.StatusOK, fmt.Sprintf("hello %s", r.Params()["name"]))
})
req := httptest.NewRequest(http.MethodPost, "/hello/Fox%20Mulder", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.Equal(t, "hello Fox Mulder", rw.Body.String())
}
func TestRouter_MissingRoute_NoHandler(t *testing.T) {
router := New(WithNoData)
req := httptest.NewRequest(http.MethodGet, "/where/do/i/go", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.Equal(t, "404 not found", rw.Body.String())
require.Equal(t, 404, rw.Result().StatusCode)
}
func TestRouter_MissingRoute_WithHandler(t *testing.T) {
router := New(WithNoData)
router.Missing(func(ctx context.Context, r *Request[NoData]) Response {
return StringResponse(http.StatusNotFound, "Sorry, can't find that page.")
})
req := httptest.NewRequest(http.MethodGet, "/where/do/i/go", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.Equal(t, "Sorry, can't find that page.", rw.Body.String())
require.Equal(t, 404, rw.Result().StatusCode)
}
func TestCustomActionType(t *testing.T) {
router := New[*MyData](func(rootRequest *RootRequest) *MyData {
return &MyData{Value: 1}
})
router.Use(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
rw.Header().Add("x-from-middleware", "wow")
next(rw, r)
})
router.Get("/hello/:name", func(ctx context.Context, r *Request[*MyData]) Response {
return StringResponse(http.StatusOK, fmt.Sprintf("hello %s, data %d", r.Params()["name"], r.Data.Value))
})
req := httptest.NewRequest(http.MethodGet, "/hello/Fox%20Mulder", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.Equal(t, "hello Fox Mulder, data 1", rw.Body.String())
require.Equal(t, "wow", rw.Header().Get("x-from-middleware"))
}
type myResponseWriter struct {
orw http.ResponseWriter
onWrite func()
}
var _ http.ResponseWriter = (*myResponseWriter)(nil)
func (mrw *myResponseWriter) Header() http.Header { return mrw.orw.Header() }
func (mrw *myResponseWriter) WriteHeader(s int) { mrw.orw.WriteHeader(s) }
func (mrw *myResponseWriter) Write(b []byte) (int, error) {
mrw.onWrite()
return mrw.orw.Write(b)
}
func TestCustomResponseWriter(t *testing.T) {
mrwCalled := false
router := New(WithNoData)
router.Use(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
mrw := &myResponseWriter{orw: rw, onWrite: func() { mrwCalled = true }}
next(mrw, r)
})
called := false
router.Get("/", func(ctx context.Context, r *Request[NoData]) Response {
called = true
return OK()
})
req := httptest.NewRequest(http.MethodGet, "/", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.True(t, called)
require.True(t, mrwCalled)
}
func TestCustomResponse(t *testing.T) {
router := New(WithNoData)
router.Use(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
ctx := context.WithValue(r.Context(), "foo", "bar")
next(rw, r.WithContext(ctx))
})
called := false
router.Get("/", func(ctx context.Context, r *Request[NoData]) Response {
require.Equal(t, "bar", r.Request().Context().Value("foo"))
called = true
return OK()
})
req := httptest.NewRequest(http.MethodGet, "/", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.True(t, called)
}
func TestWritesHeaders(t *testing.T) {
router := New(WithNoData)
router.Get("/", func(ctx context.Context, r *Request[NoData]) Response {
res := NewResponse()
res.WriteStatus(http.StatusOK)
res.Header().Add("x-foo", "bar")
res.WriteString("hello")
return res
})
req := httptest.NewRequest(http.MethodGet, "/", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.Equal(t, "bar", rw.Header().Get("x-foo"))
}
func TestBefore_EarlyExit(t *testing.T) {
router := New(WithNoData)
router.Use(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
rw.Header().Add("x-from-middleware", "wow")
next(rw, r)
})
firstBeforeCalled := false
router.Before(func(ctx context.Context, req *Request[NoData], next Next) Response {
firstBeforeCalled = true
return StringResponse(http.StatusNotFound, "not found")
})
secondBeforeCalled := false
router.Before(func(ctx context.Context, req *Request[NoData], next Next) Response {
secondBeforeCalled = true
return next(ctx)
})
routeCalled := false
router.Get("/hello/:name", func(ctx context.Context, r *Request[NoData]) Response {
routeCalled = true
return StringResponse(http.StatusOK, fmt.Sprintf("hello %s", r.Params()["name"]))
})
req := httptest.NewRequest(http.MethodGet, "/hello/Fox%20Mulder", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.Equal(t, http.StatusNotFound, rw.Code)
require.True(t, firstBeforeCalled)
require.False(t, secondBeforeCalled)
require.False(t, routeCalled)
}
func TestBefore_DifferentDataType(t *testing.T) {
router := New(func(rootRequest *RootRequest) *MyData {
return &MyData{Value: 1}
})
router.Before(func(ctx context.Context, req *Request[*MyData], next Next) Response {
return GenericBefore(ctx, req, next)
})
router.Get("/hello/:name", func(ctx context.Context, r *Request[*MyData]) Response {
return StringResponse(http.StatusOK, fmt.Sprintf("hello %s", r.Params()["name"]))
})
req := httptest.NewRequest(http.MethodGet, "/hello/Fox%20Mulder", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
}
func TestBefore_Context(t *testing.T) {
router := New(WithNoData)
router.Before(func(ctx context.Context, req *Request[NoData], next Next) Response {
ctx = context.WithValue(ctx, "first", "bar")
return GenericBefore(ctx, req, next)
})
router.Before(func(ctx context.Context, req *Request[NoData], next Next) Response {
ctx = context.WithValue(ctx, "second", "baz")
return next(ctx)
})
called := false
var handlerCtx context.Context
router.Get("/hello/:name", func(ctx context.Context, r *Request[NoData]) Response {
handlerCtx = ctx
called = true
return StringResponse(http.StatusOK, fmt.Sprintf("hello %s", r.Params()["name"]))
})
req := httptest.NewRequest(http.MethodGet, "/hello/Fox%20Mulder", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.True(t, called)
require.NotNil(t, handlerCtx)
require.Equal(t, "bar", handlerCtx.Value("first"))
require.Equal(t, "baz", handlerCtx.Value("second"))
}
func GenericBefore[T any](ctx context.Context, req *Request[T], next Next) Response {
return next(ctx)
}
func Test_BeforeModifiesData(t *testing.T) {
router := New(func(rootRequest *RootRequest) *MyData {
return &MyData{Value: 1}
})
router.Before(func(ctx context.Context, req *Request[*MyData], next Next) Response {
require.Equal(t, 1, req.Data.Value)
req.Data.Value = 2
return next(ctx)
})
router.Before(func(ctx context.Context, req *Request[*MyData], next Next) Response {
require.Equal(t, 2, req.Data.Value)
req.Data.Value = 3
return next(ctx)
})
router.Get("/hello/:name", func(ctx context.Context, r *Request[*MyData]) Response {
return OK()
})
req := httptest.NewRequest(http.MethodGet, "/hello/Fox%20Mulder", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.Equal(t, http.StatusOK, rw.Code)
}
func TestDataCreator_WithContext(t *testing.T) {
router := NewWithContext(func(ctx context.Context, rootRequest *RootRequest) (context.Context, *MyData) {
return context.WithValue(ctx, "init", "present"), &MyData{Value: 1}
})
router.Use(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
next(rw, r.WithContext(context.WithValue(r.Context(), "middleware", "also present")))
})
called := false
router.Get("/hello/:name", func(ctx context.Context, r *Request[*MyData]) Response {
require.Equal(t, "present", ctx.Value("init"))
require.Equal(t, "also present", ctx.Value("middleware"))
called = true
return OK()
})
req := httptest.NewRequest(http.MethodGet, "/hello/Fox%20Mulder", nil)
rw := httptest.NewRecorder()
router.ServeHTTP(rw, req)
require.True(t, called)
}