-
Notifications
You must be signed in to change notification settings - Fork 10
/
service_test.go
499 lines (421 loc) · 12.9 KB
/
service_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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
package goa_test
import (
"bytes"
"context"
"fmt"
"go/build"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"sync"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/shogo82148/goa-v1"
)
var _ = Describe("Service", func() {
const appName = "foo"
var s *goa.Service
BeforeEach(func() {
s = goa.New(appName)
s.Decoder.Register(goa.NewJSONDecoder, "*/*")
s.Encoder.Register(goa.NewJSONEncoder, "*/*")
})
Describe("New", func() {
It("creates a service", func() {
Ω(s).ShouldNot(BeNil())
})
It("initializes the service fields", func() {
Ω(s.Name).Should(Equal(appName))
Ω(s.Mux).ShouldNot(BeNil())
Ω(s.Server).ShouldNot(BeNil())
})
})
Describe("NotFound", func() {
var rw *TestResponseWriter
var req *http.Request
BeforeEach(func() {
req, _ = http.NewRequest("GET", "/foo", nil)
rw = &TestResponseWriter{ParentHeader: make(http.Header)}
})
JustBeforeEach(func() {
s.Mux.ServeHTTP(rw, req)
})
It("handles requests with no registered handlers", func() {
Ω(string(rw.Body)).Should(MatchRegexp(`{"id":".*","code":"not_found","status":404,"detail":"/foo"}` + "\n"))
})
Context("with middleware", func() {
middlewareCalled := false
BeforeEach(func() {
s.Use(TMiddleware(&middlewareCalled))
// trigger finalize
ctrl := s.NewController("test")
ctrl.MuxHandler("", nil, nil)
})
It("calls the middleware", func() {
Ω(middlewareCalled).Should(BeTrue())
})
})
Context("middleware and multiple controllers", func() {
middlewareCalled := 0
BeforeEach(func() {
s.Use(CMiddleware(&middlewareCalled))
ctrl := s.NewController("test")
ctrl.MuxHandler("/foo", nil, nil)
ctrl.MuxHandler("/bar", nil, nil)
})
It("calls the middleware once", func() {
Ω(middlewareCalled).Should(Equal(1))
})
})
})
Describe("MethodNotAllowed", func() {
var rw *TestResponseWriter
var req *http.Request
JustBeforeEach(func() {
rw = &TestResponseWriter{ParentHeader: http.Header{}}
s.Mux.ServeHTTP(rw, req)
})
BeforeEach(func() {
req, _ = http.NewRequest("GET", "/foo", nil)
s.Mux.Handle("POST", "/foo", func(rw http.ResponseWriter, req *http.Request, vals url.Values) {})
s.Mux.Handle("PUT", "/foo", func(rw http.ResponseWriter, req *http.Request, vals url.Values) {})
})
It("handles requests with wrong method but existing endpoint", func() {
Ω(rw.Status).Should(Equal(405))
Ω(rw.Header().Get("Allow")).Should(Or(Equal("POST, PUT"), Equal("PUT, POST")))
Ω(string(rw.Body)).Should(MatchRegexp(`{"id":".*","code":"method_not_allowed","status":405,"detail":".*","meta":{.*}}` + "\n"))
})
})
Describe("MaxRequestBodyLength", func() {
var rw *TestResponseWriter
var req *http.Request
var muxHandler goa.MuxHandler
BeforeEach(func() {
body := bytes.NewBuffer([]byte{'"', '2', '3', '4', '"'})
req, _ = http.NewRequest("GET", "/foo", body)
rw = &TestResponseWriter{ParentHeader: make(http.Header)}
ctrl := s.NewController("test")
ctrl.MaxRequestBodyLength = 4
unmarshaler := func(ctx context.Context, service *goa.Service, req *http.Request) error {
_, err := io.ReadAll(req.Body)
return err
}
handler := func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
rw.WriteHeader(400)
rw.Write([]byte(goa.ContextError(ctx).Error()))
return nil
}
muxHandler = ctrl.MuxHandler("testMax", handler, unmarshaler)
})
JustBeforeEach(func() {
muxHandler(rw, req, nil)
})
It("prevents reading more bytes", func() {
Ω(string(rw.Body)).Should(MatchRegexp(`\[.*\] 413 request_too_large: request body length exceeds 4 bytes`))
})
})
Describe("MuxHandler", func() {
var handler goa.Handler
var unmarshaler goa.Unmarshaler
const respStatus = 200
var respContent = []byte("response")
var muxHandler goa.MuxHandler
var ctx context.Context
JustBeforeEach(func() {
ctrl := s.NewController("test")
muxHandler = ctrl.MuxHandler("testAct", handler, unmarshaler)
})
BeforeEach(func() {
handler = func(c context.Context, rw http.ResponseWriter, req *http.Request) error {
if err := goa.ContextError(c); err != nil {
rw.WriteHeader(400)
rw.Write([]byte(err.Error()))
return nil
}
goa.ContextRequest(c).Request = req
ctx = c
rw.WriteHeader(respStatus)
rw.Write(respContent)
return nil
}
unmarshaler = func(c context.Context, service *goa.Service, req *http.Request) error {
ctx = c
if req != nil {
var payload interface{}
err := service.DecodeRequest(req, &payload)
if err != nil {
return err
}
goa.ContextRequest(ctx).Payload = payload
}
return nil
}
})
It("creates a handler", func() {
Ω(muxHandler).ShouldNot(BeNil())
})
Context("with multiple instances and middlewares", func() {
var ctrl *goa.Controller
var handlers []goa.MuxHandler
var rws []*TestResponseWriter
var reqs []*http.Request
var p url.Values
var wg sync.WaitGroup
BeforeEach(func() {
nopHandler := func(context.Context, http.ResponseWriter, *http.Request) error {
return nil
}
ctrl = s.NewController("test")
for i := 0; i < 5; i++ {
ctrl.Service.Use(func(goa.Handler) goa.Handler {
return nopHandler
})
}
ctrl.Use(func(goa.Handler) goa.Handler { return nopHandler })
for i := 0; i < 10; i++ {
tmp := ctrl.MuxHandler("test", nopHandler, nil)
handlers = append(handlers, tmp)
rws = append(rws, &TestResponseWriter{})
req, _ := http.NewRequest("GET", "", nil)
reqs = append(reqs, req)
}
p = url.Values{}
wg = sync.WaitGroup{}
wg.Add(10)
})
It("doesn't race with parallel handler calls", func() {
for i := range handlers {
go func(j int) {
handlers[j](rws[j], reqs[j], p)
wg.Done()
}(i)
}
wg.Wait()
})
})
Context("with a request", func() {
var rw http.ResponseWriter
var r *http.Request
var p url.Values
BeforeEach(func() {
var err error
r, err = http.NewRequest("GET", "/foo", nil)
Ω(err).ShouldNot(HaveOccurred())
rw = &TestResponseWriter{ParentHeader: make(http.Header)}
p = url.Values{"id": []string{"42"}, "sort": []string{"asc"}}
})
JustBeforeEach(func() {
muxHandler(rw, r, p)
})
It("creates a handle that handles the request", func() {
i := goa.ContextRequest(ctx).Params.Get("id")
Ω(i).Should(Equal("42"))
s := goa.ContextRequest(ctx).Params.Get("sort")
Ω(s).Should(Equal("asc"))
tw := rw.(*TestResponseWriter)
Ω(tw.Status).Should(Equal(respStatus))
Ω(tw.Body).Should(Equal(respContent))
})
Context("with an invalid payload", func() {
BeforeEach(func() {
r.Body = io.NopCloser(bytes.NewBuffer([]byte("not json")))
r.ContentLength = 8
})
It("triggers the error handler", func() {
Ω(rw.(*TestResponseWriter).Status).Should(Equal(400))
Ω(string(rw.(*TestResponseWriter).Body)).Should(ContainSubstring("failed to decode"))
})
Context("then a valid payload", func() {
It("then succeeds", func() {
var err error
r, err = http.NewRequest("GET", "/foo2", nil)
Ω(err).ShouldNot(HaveOccurred())
rw = &TestResponseWriter{ParentHeader: make(http.Header)}
muxHandler(rw, r, p)
Ω(rw.(*TestResponseWriter).Status).Should(Equal(200))
})
})
})
Context("and middleware", func() {
middlewareCalled := false
BeforeEach(func() {
s.Use(TMiddleware(&middlewareCalled))
})
It("calls the middleware", func() {
Ω(middlewareCalled).Should(BeTrue())
})
})
Context("and a middleware chain", func() {
middlewareCalled := false
secondCalled := false
BeforeEach(func() {
s.Use(TMiddleware(&middlewareCalled))
s.Use(SecondMiddleware(&middlewareCalled, &secondCalled))
})
It("calls the middleware in the right order", func() {
Ω(middlewareCalled).Should(BeTrue())
Ω(secondCalled).Should(BeTrue())
})
})
Context("with a handler that fails", func() {
errorHandlerCalled := false
BeforeEach(func() {
s.Use(TErrorHandler(&errorHandlerCalled))
})
Context("by returning an error", func() {
BeforeEach(func() {
handler = func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
return fmt.Errorf("boom")
}
s.WithLogger(nil)
})
It("triggers the error handler", func() {
Ω(errorHandlerCalled).Should(BeTrue())
})
})
})
Context("with different payload types", func() {
content := []byte(`{"hello": "world"}`)
decodedContent := map[string]interface{}{"hello": "world"}
BeforeEach(func() {
r.Header.Set("Content-Type", "application/json")
r.Body = io.NopCloser(bytes.NewReader(content))
r.ContentLength = int64(len(content))
})
It("should work with application/json and load properly", func() {
Ω(goa.ContextRequest(ctx).Payload).Should(Equal(decodedContent))
})
Context("with an empty Content-Type", func() {
BeforeEach(func() {
delete(r.Header, "Content-Type")
})
It("defaults to application/json and loads properly for JSON bodies", func() {
Ω(goa.ContextRequest(ctx).Payload).Should(Equal(decodedContent))
})
})
Context("with a Content-Type of 'application/octet-stream' or any other", func() {
BeforeEach(func() {
s.Decoder.Register(goa.NewJSONDecoder, "*/*")
r.Header.Set("Content-Type", "application/octet-stream")
})
It("should use the default decoder", func() {
Ω(goa.ContextRequest(ctx).Payload).Should(Equal(decodedContent))
})
})
Context("with a Content-Type of 'application/octet-stream' or any other and no default decoder", func() {
BeforeEach(func() {
s = goa.New("test")
s.Decoder.Register(goa.NewJSONDecoder, "application/json")
r.Header.Set("Content-Type", "application/octet-stream")
})
It("should bypass decoding", func() {
Ω(goa.ContextRequest(ctx).Payload).Should(BeNil())
})
})
})
})
})
Describe("FileHandler", func() {
const publicPath = "github.com/shogo82148/goa-v1/public"
var outDir string
var handler goa.Handler
const respStatus = 200
var respContent = []byte(`{"foo":"bar"}`)
var muxHandler goa.MuxHandler
JustBeforeEach(func() {
gopath := filepath.SplitList(build.Default.GOPATH)[0]
outDir = filepath.Join(gopath, "src", publicPath)
err := os.MkdirAll(filepath.Join(outDir, "swagger"), 0777)
Ω(err).ShouldNot(HaveOccurred())
file, err := os.Create(filepath.Join(outDir, "swagger", "swagger.json"))
Ω(err).ShouldNot(HaveOccurred())
_, err = file.Write(respContent)
Ω(err).ShouldNot(HaveOccurred())
file.Close()
ctrl := s.NewController("test")
handler = ctrl.FileHandler("/swagger.json", "public/swagger/swagger.json")
muxHandler = ctrl.MuxHandler("testAct", handler, nil)
})
AfterEach(func() {
err := os.RemoveAll(outDir)
Ω(err).ShouldNot(HaveOccurred())
})
It("creates a handler", func() {
Ω(muxHandler).ShouldNot(BeNil())
})
Context("with a request", func() {
var rw http.ResponseWriter
var r *http.Request
var p url.Values
BeforeEach(func() {
var err error
r, err = http.NewRequest("GET", "/swagger.json", nil)
Ω(err).ShouldNot(HaveOccurred())
rw = &TestResponseWriter{ParentHeader: make(http.Header)}
})
JustBeforeEach(func() {
muxHandler(rw, r, p)
})
It("creates a handle that handles the request", func() {
tw := rw.(*TestResponseWriter)
Ω(tw.Status).Should(Equal(respStatus))
Ω(tw.Body).Should(Equal(respContent))
})
})
})
})
func TErrorHandler(witness *bool) goa.Middleware {
return func(h goa.Handler) goa.Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
err := h(ctx, rw, req)
if err != nil {
*witness = true
}
return nil
}
}
}
func TMiddleware(witness *bool) goa.Middleware {
return func(h goa.Handler) goa.Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
*witness = true
return h(ctx, rw, req)
}
}
}
func CMiddleware(witness *int) goa.Middleware {
return func(h goa.Handler) goa.Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
*witness++
return h(ctx, rw, req)
}
}
}
func SecondMiddleware(witness1, witness2 *bool) goa.Middleware {
return func(h goa.Handler) goa.Handler {
return func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
if !*witness1 {
panic("middleware called in wrong order")
}
*witness2 = true
return h(ctx, rw, req)
}
}
}
type TestResponseWriter struct {
ParentHeader http.Header
Body []byte
Status int
}
func (t *TestResponseWriter) Header() http.Header {
return t.ParentHeader
}
func (t *TestResponseWriter) Write(b []byte) (int, error) {
t.Body = append(t.Body, b...)
return len(b), nil
}
func (t *TestResponseWriter) WriteHeader(s int) {
t.Status = s
}