forked from juju/httprequest
/
client_test.go
670 lines (609 loc) · 16.6 KB
/
client_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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
package httprequest_test
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"reflect"
"strings"
jc "github.com/juju/testing/checkers"
"github.com/julienschmidt/httprouter"
gc "gopkg.in/check.v1"
"gopkg.in/errgo.v1"
"github.com/juju/httprequest"
)
type clientSuite struct{}
var _ = gc.Suite(&clientSuite{})
var callTests = []struct {
about string
client httprequest.Client
req interface{}
expectError string
expectCause interface{}
expectResp interface{}
}{{
about: "GET success",
req: &chM1Req{
P: "hello",
},
expectResp: &chM1Resp{"hello"},
}, {
about: "GET with nil response",
req: &chM1Req{
P: "hello",
},
}, {
about: "POST success",
req: &chM2Req{
P: "hello",
Body: struct{ I int }{999},
},
expectResp: &chM2Resp{"hello", 999},
}, {
about: "GET marshal error",
req: 123,
expectError: `type is not pointer to struct`,
}, {
about: "error response",
req: &chInvalidM2Req{
P: "hello",
Body: struct{ I bool }{true},
},
expectError: `POST http://.*/m2/hello: httprequest: cannot unmarshal parameters: cannot unmarshal into field: cannot unmarshal request body: json: cannot unmarshal bool into Go value of type int`,
expectCause: &httprequest.RemoteError{
Message: `cannot unmarshal parameters: cannot unmarshal into field: cannot unmarshal request body: json: cannot unmarshal bool into Go value of type int`,
Code: "bad request",
},
}, {
about: "error unmarshaler returns nil",
client: httprequest.Client{
UnmarshalError: func(*http.Response) error {
return nil
},
},
req: &chM3Req{},
expectError: `GET http://.*/m3: unexpected HTTP response status: 500 Internal Server Error`,
}, {
about: "unexpected redirect",
req: &chM2RedirectM2Req{},
expectError: `POST http://.*/m2/foo//: unexpected redirect \(status 307 Temporary Redirect\) from "http://.*/m2/foo//" to "http://.*/m2/foo"`,
}, {
about: "doer with body",
client: httprequest.Client{
Doer: doerFunc(func(req *http.Request, body io.ReadSeeker) (*http.Response, error) {
if body == nil {
panic("Do called when DoWithBody expected")
}
req.Body = ioutil.NopCloser(body)
return http.DefaultClient.Do(req)
}),
},
req: &chM2Req{
P: "hello",
Body: struct{ I int }{999},
},
expectResp: &chM2Resp{"hello", 999},
}, {
about: "doer that implements DoWithBody but no body",
client: httprequest.Client{
Doer: doerFunc(func(req *http.Request, body io.ReadSeeker) (*http.Response, error) {
if body == nil {
panic("Do called but DoWithBody should always be called")
}
return http.DefaultClient.Do(req)
}),
},
req: &chM1Req{
P: "hello",
},
expectResp: &chM1Resp{"hello"},
}, {
about: "bad content in successful response",
req: &chM4Req{},
expectResp: new(int),
expectError: `GET http://.*/m4: unexpected content type text/plain; want application/json; content: bad response`,
}}
func (s *clientSuite) TestCall(c *gc.C) {
srv := s.newServer()
defer srv.Close()
for i, test := range callTests {
c.Logf("test %d: %s", i, test.about)
var resp interface{}
if test.expectResp != nil {
resp = reflect.New(reflect.TypeOf(test.expectResp).Elem()).Interface()
}
client := test.client
client.BaseURL = srv.URL
err := client.Call(test.req, resp)
if test.expectError != "" {
c.Assert(err, gc.ErrorMatches, test.expectError)
if test.expectCause != nil {
c.Assert(errgo.Cause(err), jc.DeepEquals, test.expectCause)
}
continue
}
c.Assert(err, gc.IsNil)
c.Assert(resp, jc.DeepEquals, test.expectResp)
}
}
func (s *clientSuite) TestCallURLNoRequestPath(c *gc.C) {
srv := s.newServer()
defer srv.Close()
var client httprequest.Client
req := struct {
httprequest.Route `httprequest:"GET"`
chM1Req
}{
chM1Req: chM1Req{
P: "hello",
},
}
var resp chM1Resp
err := client.CallURL(srv.URL+"/m1/:P", &req, &resp)
c.Assert(err, gc.IsNil)
c.Assert(resp, jc.DeepEquals, chM1Resp{"hello"})
}
func mustNewRequest(url string, method string, body io.Reader) *http.Request {
req, err := http.NewRequest(method, url, body)
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
return req
}
var doTests = []struct {
about string
client httprequest.Client
request *http.Request
body io.ReadSeeker
expectError string
expectCause interface{}
expectResp interface{}
}{{
about: "GET success",
request: mustNewRequest("/m1/hello", "GET", nil),
expectResp: &chM1Resp{"hello"},
}, {
about: "appendURL error",
request: mustNewRequest("/m1/hello", "GET", nil),
client: httprequest.Client{
BaseURL: ":::",
},
expectError: `cannot parse ":::": parse :::: missing protocol scheme`,
}, {
about: "body supplied in request",
request: mustNewRequest("/m1/hello", "GET", strings.NewReader("")),
expectError: `GET http://.*/m1/hello: request body supplied unexpectedly`,
}, {
about: "content length is inferred from strings.Reader",
request: mustNewRequest("/content-length", "PUT", nil),
body: strings.NewReader("hello"),
expectResp: newInt64(int64(len("hello"))),
}, {
about: "content length is inferred from bytes.Reader",
request: mustNewRequest("/content-length", "PUT", nil),
body: bytes.NewReader([]byte("hello")),
expectResp: newInt64(int64(len("hello"))),
}, {
about: "DoWithBody implemented but no body",
client: httprequest.Client{
Doer: doerFunc(func(req *http.Request, body io.ReadSeeker) (*http.Response, error) {
if body != nil {
panic("DoWithBody called when Do expected")
}
return http.DefaultClient.Do(req)
}),
},
request: mustNewRequest("/m1/hello", "GET", nil),
expectResp: &chM1Resp{"hello"},
}, {
about: "DoWithBody not implemented and body present",
client: httprequest.Client{
Doer: doerOnlyFunc(func(req *http.Request) (*http.Response, error) {
return http.DefaultClient.Do(req)
}),
},
request: mustNewRequest("/m2/foo", "POST", nil),
body: strings.NewReader(`{"I": 999}`),
expectResp: &chM2Resp{
P: "foo",
Arg: 999,
},
}, {
about: "DoWithBody implemented and body present",
client: httprequest.Client{
Doer: doerFunc(func(req *http.Request, body io.ReadSeeker) (*http.Response, error) {
if body == nil {
panic("Do called when DoWithBody expected")
}
req.Body = ioutil.NopCloser(body)
return http.DefaultClient.Do(req)
}),
},
request: mustNewRequest("/m2/foo", "POST", nil),
body: strings.NewReader(`{"I": 999}`),
expectResp: &chM2Resp{
P: "foo",
Arg: 999,
},
}, {
about: "Do returns error",
client: httprequest.Client{
Doer: doerOnlyFunc(func(req *http.Request) (*http.Response, error) {
return nil, errgo.Newf("an error")
}),
},
request: mustNewRequest("/m2/foo", "POST", nil),
body: strings.NewReader(`{"I": 999}`),
expectError: "POST http://.*/m2/foo: an error",
}}
func newInt64(i int64) *int64 {
return &i
}
func (s *clientSuite) TestDo(c *gc.C) {
srv := s.newServer()
defer srv.Close()
for i, test := range doTests {
c.Logf("test %d: %s", i, test.about)
var resp interface{}
if test.expectResp != nil {
resp = reflect.New(reflect.TypeOf(test.expectResp).Elem()).Interface()
}
client := test.client
if client.BaseURL == "" {
client.BaseURL = srv.URL
}
err := client.Do(test.request, test.body, resp)
if test.expectError != "" {
c.Assert(err, gc.ErrorMatches, test.expectError)
if test.expectCause != nil {
c.Assert(errgo.Cause(err), jc.DeepEquals, test.expectCause)
}
continue
}
c.Assert(err, gc.IsNil)
c.Assert(resp, jc.DeepEquals, test.expectResp)
}
}
func (s *clientSuite) TestDoWithHTTPReponse(c *gc.C) {
srv := s.newServer()
defer srv.Close()
client := &httprequest.Client{
BaseURL: srv.URL,
}
var resp *http.Response
err := client.Get("/m1/foo", &resp)
c.Assert(err, gc.IsNil)
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
c.Assert(err, gc.IsNil)
c.Assert(string(data), gc.Equals, `{"P":"foo"}`)
}
func (s *clientSuite) TestDoWithHTTPReponseAndError(c *gc.C) {
srv := s.newServer()
defer srv.Close()
var doer closeCountingDoer // Also check the body is closed.
client := &httprequest.Client{
BaseURL: srv.URL,
Doer: &doer,
}
var resp *http.Response
err := client.Get("/m3", &resp)
c.Assert(resp, gc.IsNil)
c.Assert(err, gc.ErrorMatches, `GET http://.*/m3: httprequest: m3 error`)
c.Assert(doer.openedBodies, gc.Equals, 1)
c.Assert(doer.closedBodies, gc.Equals, 1)
}
func (s *clientSuite) TestCallWithHTTPResponse(c *gc.C) {
srv := s.newServer()
defer srv.Close()
client := &httprequest.Client{
BaseURL: srv.URL,
}
var resp *http.Response
err := client.Call(&chM1Req{
P: "foo",
}, &resp)
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
c.Assert(err, gc.IsNil)
c.Assert(string(data), gc.Equals, `{"P":"foo"}`)
}
func (s *clientSuite) TestCallClosesResponseBodyOnSuccess(c *gc.C) {
srv := s.newServer()
defer srv.Close()
var doer closeCountingDoer
client := &httprequest.Client{
BaseURL: srv.URL,
Doer: &doer,
}
var resp chM1Resp
err := client.Call(&chM1Req{
P: "foo",
}, &resp)
c.Assert(err, gc.IsNil)
c.Assert(resp, jc.DeepEquals, chM1Resp{"foo"})
c.Assert(doer.openedBodies, gc.Equals, 1)
c.Assert(doer.closedBodies, gc.Equals, 1)
}
func (s *clientSuite) TestCallClosesResponseBodyOnError(c *gc.C) {
srv := s.newServer()
defer srv.Close()
var doer closeCountingDoer
client := &httprequest.Client{
BaseURL: srv.URL,
Doer: &doer,
}
err := client.Call(&chM3Req{}, nil)
c.Assert(err, gc.ErrorMatches, ".*m3 error")
c.Assert(doer.openedBodies, gc.Equals, 1)
c.Assert(doer.closedBodies, gc.Equals, 1)
}
func (s *clientSuite) TestDoClosesResponseBodyOnSuccess(c *gc.C) {
srv := s.newServer()
defer srv.Close()
var doer closeCountingDoer
client := &httprequest.Client{
BaseURL: srv.URL,
Doer: &doer,
}
req, err := http.NewRequest("GET", "/m1/foo", nil)
c.Assert(err, gc.IsNil)
var resp chM1Resp
err = client.Do(req, nil, &resp)
c.Assert(err, gc.IsNil)
c.Assert(resp, jc.DeepEquals, chM1Resp{"foo"})
c.Assert(doer.openedBodies, gc.Equals, 1)
c.Assert(doer.closedBodies, gc.Equals, 1)
}
func (s *clientSuite) TestDoClosesResponseBodyOnError(c *gc.C) {
srv := s.newServer()
defer srv.Close()
var doer closeCountingDoer
client := &httprequest.Client{
BaseURL: srv.URL,
Doer: &doer,
}
req, err := http.NewRequest("GET", "/m3", nil)
c.Assert(err, gc.IsNil)
err = client.Do(req, nil, nil)
c.Assert(err, gc.ErrorMatches, ".*m3 error")
c.Assert(doer.openedBodies, gc.Equals, 1)
c.Assert(doer.closedBodies, gc.Equals, 1)
}
func (s *clientSuite) TestDoDoesNotReadRequestBodyAfterReturning(c *gc.C) {
body := &largeReader{total: 300 * 1024}
// Closing the body will cause a panic under the race
// detector if the Do method reads after returning.
defer body.Close()
srv := s.newServer()
defer srv.Close()
req, err := http.NewRequest("GET", "/not-an-endpoint", nil)
c.Assert(err, gc.IsNil)
client := &httprequest.Client{
BaseURL: srv.URL,
}
err = client.Do(req, body, nil)
c.Assert(err, gc.ErrorMatches, `GET .*/not-an-endpoint: cannot unmarshal error response \(status 404 Not Found\): unexpected content type text/plain; want application/json; content: 404 page not found`)
}
func (s *clientSuite) TestGet(c *gc.C) {
srv := s.newServer()
defer srv.Close()
client := httprequest.Client{
BaseURL: srv.URL,
}
var resp chM1Resp
err := client.Get("/m1/foo", &resp)
c.Assert(err, gc.IsNil)
c.Assert(resp, jc.DeepEquals, chM1Resp{"foo"})
}
func (s *clientSuite) TestGetNoBaseURL(c *gc.C) {
srv := s.newServer()
defer srv.Close()
client := httprequest.Client{}
var resp chM1Resp
err := client.Get(srv.URL+"/m1/foo", &resp)
c.Assert(err, gc.IsNil)
c.Assert(resp, jc.DeepEquals, chM1Resp{"foo"})
}
func (*clientSuite) newServer() *httptest.Server {
f := func(p httprequest.Params) (clientHandlers, error) {
return clientHandlers{}, nil
}
handlers := errorMapper.Handlers(f)
router := httprouter.New()
for _, h := range handlers {
router.Handle(h.Method, h.Path, h.Handle)
}
return httptest.NewServer(router)
}
var appendURLTests = []struct {
u string
p string
expect string
expectError string
}{{
u: "http://foo",
p: "bar",
expect: "http://foo/bar",
}, {
u: "http://foo",
p: "/bar",
expect: "http://foo/bar",
}, {
u: "http://foo/",
p: "bar",
expect: "http://foo/bar",
}, {
u: "http://foo/",
p: "/bar",
expect: "http://foo/bar",
}, {
u: "",
p: "bar",
expect: "/bar",
}, {
u: "http://xxx",
p: "",
expect: "http://xxx",
}, {
u: "http://xxx.com",
p: "http://foo.com",
expectError: "relative URL specifies a host",
}, {
u: "http://xxx.com/a/b",
p: "foo?a=45&b=c",
expect: "http://xxx.com/a/b/foo?a=45&b=c",
}, {
u: "http://xxx.com",
p: "?a=45&b=c",
expect: "http://xxx.com?a=45&b=c",
}, {
u: "http://xxx.com/a?z=w",
p: "foo?a=45&b=c",
expect: "http://xxx.com/a/foo?z=w&a=45&b=c",
}, {
u: "http://xxx.com?z=w",
p: "/a/b/c",
expect: "http://xxx.com/a/b/c?z=w",
}}
func (*clientSuite) TestAppendURL(c *gc.C) {
for i, test := range appendURLTests {
c.Logf("test %d: %s %s", i, test.u, test.p)
u, err := httprequest.AppendURL(test.u, test.p)
if test.expectError != "" {
c.Assert(u, gc.IsNil)
c.Assert(err, gc.ErrorMatches, test.expectError)
} else {
c.Assert(err, gc.IsNil)
c.Assert(u.String(), gc.Equals, test.expect)
}
}
}
type clientHandlers struct{}
type chM1Req struct {
httprequest.Route `httprequest:"GET /m1/:P"`
P string `httprequest:",path"`
}
type chM1Resp struct {
P string
}
func (clientHandlers) M1(p *chM1Req) (*chM1Resp, error) {
return &chM1Resp{p.P}, nil
}
type chM2Req struct {
httprequest.Route `httprequest:"POST /m2/:P"`
P string `httprequest:",path"`
Body struct {
I int
} `httprequest:",body"`
}
type chInvalidM2Req struct {
httprequest.Route `httprequest:"POST /m2/:P"`
P string `httprequest:",path"`
Body struct {
I bool
} `httprequest:",body"`
}
type chM2RedirectM2Req struct {
httprequest.Route `httprequest:"POST /m2/foo//"`
}
type chM2Resp struct {
P string
Arg int
}
func (clientHandlers) M2(p *chM2Req) (*chM2Resp, error) {
return &chM2Resp{p.P, p.Body.I}, nil
}
type chM3Req struct {
httprequest.Route `httprequest:"GET /m3"`
}
func (clientHandlers) M3(p *chM3Req) error {
return errgo.New("m3 error")
}
type chM4Req struct {
httprequest.Route `httprequest:"GET /m4"`
}
func (clientHandlers) M4(p httprequest.Params, _ *chM4Req) {
p.Response.Write([]byte("bad response"))
}
type chContentLengthReq struct {
httprequest.Route `httprequest:"PUT /content-length"`
}
func (clientHandlers) ContentLength(rp httprequest.Params, p *chContentLengthReq) (int64, error) {
return rp.Request.ContentLength, nil
}
type doerFunc func(req *http.Request, body io.ReadSeeker) (*http.Response, error)
func (f doerFunc) Do(req *http.Request) (*http.Response, error) {
return f(req, nil)
}
func (f doerFunc) DoWithBody(req *http.Request, body io.ReadSeeker) (*http.Response, error) {
if req.Body != nil {
panic("unexpected non-nil body in request")
}
if body == nil {
panic("unexpected nil body argument")
}
return f(req, body)
}
type doerOnlyFunc func(req *http.Request) (*http.Response, error)
func (f doerOnlyFunc) Do(req *http.Request) (*http.Response, error) {
return f(req)
}
type closeCountingDoer struct {
// openBodies records the number of response bodies
// that have been returned.
openedBodies int
// closedBodies records the number of response bodies
// that have been closed.
closedBodies int
}
func (doer *closeCountingDoer) Do(req *http.Request) (*http.Response, error) {
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
resp.Body = &closeCountingReader{
doer: doer,
ReadCloser: resp.Body,
}
doer.openedBodies++
return resp, nil
}
type closeCountingReader struct {
doer *closeCountingDoer
io.ReadCloser
}
func (r *closeCountingReader) Close() error {
r.doer.closedBodies++
return r.ReadCloser.Close()
}
// largeReader implements a reader that produces up to total bytes
// in 1 byte reads.
type largeReader struct {
total int
n int
}
func (r *largeReader) Read(buf []byte) (int, error) {
if r.n >= r.total {
return 0, io.EOF
}
r.n++
return copy(buf, []byte("a")), nil
}
func (r *largeReader) Seek(offset int64, whence int) (int64, error) {
if offset != 0 || whence != 0 {
panic("unexpected seek")
}
r.n = 0
return 0, nil
}
func (r *largeReader) Close() error {
// By setting n to zero, we ensure that if there's
// a concurrent read, it will also read from n
// and so the race detector should pick up the
// problem.
r.n = 0
return nil
}