File: client_test.go

package info (click to toggle)
golang-gopkg-httprequest.v1 0.0~git20171212.fdaf1bf-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 316 kB
  • sloc: makefile: 4
file content (776 lines) | stat: -rw-r--r-- 21,069 bytes parent folder | download
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
package httprequest_test

import (
	"io"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"reflect"
	"strings"

	"github.com/juju/testing"
	jc "github.com/juju/testing/checkers"
	"github.com/julienschmidt/httprouter"
	"golang.org/x/net/context"
	"golang.org/x/net/context/ctxhttp"
	gc "gopkg.in/check.v1"
	"gopkg.in/errgo.v1"

	"gopkg.in/httprequest.v1"
)

type clientSuite struct {
	testing.CleanupSuite
}

var _ = gc.Suite(&clientSuite{})

var callTests = []struct {
	about       string
	client      httprequest.Client
	req         interface{}
	requestUUID string
	expectError string
	assertError func(c *gc.C, err error)
	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:.*: cannot unmarshal parameters: cannot unmarshal into field Body: cannot unmarshal request body: json: cannot unmarshal .*`,
	assertError: func(c *gc.C, err error) {
		c.Assert(errgo.Cause(err), gc.FitsTypeOf, (*httprequest.RemoteError)(nil))
		err1 := errgo.Cause(err).(*httprequest.RemoteError)
		c.Assert(err1.Code, gc.Equals, "bad request")
		c.Assert(err1.Message, gc.Matches, `cannot unmarshal parameters: cannot unmarshal into field Body: cannot unmarshal request body: json: cannot unmarshal .*`)
	},
}, {
	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:       "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`,
	assertError: func(c *gc.C, err error) {
		c.Assert(errgo.Cause(err), gc.FitsTypeOf, (*httprequest.DecodeResponseError)(nil))

		err1 := errgo.Cause(err).(*httprequest.DecodeResponseError)
		c.Assert(err1.Response, gc.NotNil)
		data, err := ioutil.ReadAll(err1.Response.Body)
		c.Assert(err, gc.IsNil)
		c.Assert(string(data), gc.Equals, "bad response")
	},
}, {
	about:       "bad content in error response",
	req:         &chM5Req{},
	expectResp:  new(int),
	expectError: `Get http://.*/m5: cannot unmarshal error response \(status 418 I'm a teapot\): unexpected content type text/plain; want application/json; content: bad error value`,
	assertError: func(c *gc.C, err error) {
		c.Assert(errgo.Cause(err), gc.FitsTypeOf, (*httprequest.DecodeResponseError)(nil))

		err1 := errgo.Cause(err).(*httprequest.DecodeResponseError)
		c.Assert(err1.Response, gc.NotNil)
		data, err := ioutil.ReadAll(err1.Response.Body)
		c.Assert(err, gc.IsNil)
		c.Assert(string(data), gc.Equals, "bad error value")
		c.Assert(err1.Response.StatusCode, gc.Equals, http.StatusTeapot)
	},
}, {
	about: "doer with context",
	client: httprequest.Client{
		Doer: doerWithContextFunc(func(ctx context.Context, req *http.Request) (*http.Response, error) {
			if ctx == nil {
				panic("Do called when DoWithContext expected")
			}
			return ctxhttp.Do(ctx, http.DefaultClient, req)
		}),
	},
	req: &chM2Req{
		P:    "hello",
		Body: struct{ I int }{999},
	},
	expectResp: &chM2Resp{"hello", 999},
}, {
	about: "doer with context and body",
	client: httprequest.Client{
		Doer: doerWithContextFunc(func(ctx context.Context, req *http.Request) (*http.Response, error) {
			if ctx == nil {
				panic("Do called when DoWithContext expected")
			}
			return ctxhttp.Do(ctx, http.DefaultClient, req)
		}),
	},
	req: &chM2Req{
		P:    "hello",
		Body: struct{ I int }{999},
	},
	expectResp: &chM2Resp{"hello", 999},
}, {
	about: "doer with context and body but no body",
	client: httprequest.Client{
		Doer: doerWithContextFunc(func(ctx context.Context, req *http.Request) (*http.Response, error) {
			if ctx == nil {
				panic("Do called when DoWithContext expected")
			}
			return ctxhttp.Do(ctx, http.DefaultClient, req)
		}),
	},
	req: &chM1Req{
		P: "hello",
	},
	expectResp: &chM1Resp{"hello"},
}}

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
		ctx := context.Background()
		err := client.Call(ctx, test.req, resp)
		if test.expectError != "" {
			c.Logf("err %v", errgo.Details(err))
			c.Check(err, gc.ErrorMatches, test.expectError)
			if test.assertError != nil {
				test.assertError(c, err)
			}
			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(context.Background(), 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 {
	return mustNewRequestWithHeader(url, method, body, http.Header{
		"Content-Type": []string{"application/json"},
	})
}

func mustNewRequestWithHeader(url string, method string, body io.Reader, hdr http.Header) *http.Request {
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		panic(err)
	}
	for k, v := range hdr {
		req.Header[k] = append(req.Header[k], v...)
	}
	return req
}

var doTests = []struct {
	about       string
	client      httprequest.Client
	request     *http.Request
	requestUUID string

	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: "Do returns error",
	client: httprequest.Client{
		Doer: doerFunc(func(req *http.Request) (*http.Response, error) {
			return nil, errgo.Newf("an error")
		}),
	},
	request:     mustNewRequest("/m2/foo", "POST", strings.NewReader(`{"I": 999}`)),
	expectError: "Post http://.*/m2/foo: an error",
}, {
	about: "doer with context",
	client: httprequest.Client{
		Doer: doerWithContextFunc(func(ctx context.Context, req *http.Request) (*http.Response, error) {
			if ctx == nil {
				panic("Do called when DoWithContext expected")
			}
			return ctxhttp.Do(ctx, http.DefaultClient, req)
		}),
	},
	request:    mustNewRequest("/m2/foo", "POST", strings.NewReader(`{"I": 999}`)),
	expectResp: &chM2Resp{"foo", 999},
}}

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
		}
		ctx := context.Background()
		err := client.Do(ctx, test.request, 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(context.Background(), "/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(context.Background(), "/m3", &resp)
	c.Assert(resp, gc.IsNil)
	c.Assert(err, gc.ErrorMatches, `Get http:.*/m3: 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(context.Background(), &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(context.Background(), &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(context.Background(), &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(context.Background(), req, &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(context.Background(), req, 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) TestGet(c *gc.C) {
	srv := s.newServer()
	defer srv.Close()
	client := httprequest.Client{
		BaseURL: srv.URL,
	}
	var resp chM1Resp
	err := client.Get(context.Background(), "/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(context.Background(), srv.URL+"/m1/foo", &resp)
	c.Assert(err, gc.IsNil)
	c.Assert(resp, jc.DeepEquals, chM1Resp{"foo"})
}

func (s *clientSuite) TestUnmarshalJSONResponseWithBodyReadError(c *gc.C) {
	resp := &http.Response{
		Header: http.Header{
			"Content-Type": {"application/json"},
		},
		StatusCode: http.StatusOK,
		Body: ioutil.NopCloser(io.MultiReader(
			strings.NewReader(`{"one": "two"}`),
			errorReader("some bad read"),
		)),
	}
	var val map[string]string
	err := httprequest.UnmarshalJSONResponse(resp, &val)
	c.Assert(err, gc.ErrorMatches, `error reading response body: some bad read`)
	c.Assert(val, gc.IsNil)
	assertDecodeResponseError(c, err, http.StatusOK, `{"one": "two"}`)
}

func (s *clientSuite) TestUnmarshalJSONResponseWithBadContentType(c *gc.C) {
	resp := &http.Response{
		Header: http.Header{
			"Content-Type": {"foo/bar"},
		},
		StatusCode: http.StatusTeapot,
		Body:       ioutil.NopCloser(strings.NewReader(`something or other`)),
	}
	var val map[string]string
	err := httprequest.UnmarshalJSONResponse(resp, &val)
	c.Assert(err, gc.ErrorMatches, `unexpected content type foo/bar; want application/json; content: "something or other"`)
	c.Assert(val, gc.IsNil)
	assertDecodeResponseError(c, err, http.StatusTeapot, `something or other`)
}

func (s *clientSuite) TestUnmarshalJSONResponseWithErrorAndLargeBody(c *gc.C) {
	s.PatchValue(httprequest.MaxErrorBodySize, 11)

	resp := &http.Response{
		Header: http.Header{
			"Content-Type": {"foo/bar"},
		},
		StatusCode: http.StatusOK,
		Body:       ioutil.NopCloser(strings.NewReader(`123456789 123456789`)),
	}
	var val map[string]string
	err := httprequest.UnmarshalJSONResponse(resp, &val)
	c.Assert(err, gc.ErrorMatches, `unexpected content type foo/bar; want application/json; content: "123456789 1"`)
	c.Assert(val, gc.IsNil)
	assertDecodeResponseError(c, err, http.StatusOK, `123456789 1`)
}

func (s *clientSuite) TestUnmarshalJSONResponseWithLargeBody(c *gc.C) {
	s.PatchValue(httprequest.MaxErrorBodySize, 11)

	resp := &http.Response{
		Header: http.Header{
			"Content-Type": {"application/json"},
		},
		StatusCode: http.StatusOK,
		Body:       ioutil.NopCloser(strings.NewReader(`"23456789 123456789"`)),
	}
	var val string
	err := httprequest.UnmarshalJSONResponse(resp, &val)
	c.Assert(err, gc.IsNil)
	c.Assert(val, gc.Equals, "23456789 123456789")
}

func (s *clientSuite) TestUnmarshalJSONWithDecodeError(c *gc.C) {
	resp := &http.Response{
		Header: http.Header{
			"Content-Type": {"application/json"},
		},
		StatusCode: http.StatusOK,
		Body:       ioutil.NopCloser(strings.NewReader(`{"one": "two"}`)),
	}
	var val chan string
	err := httprequest.UnmarshalJSONResponse(resp, &val)
	c.Assert(err, gc.ErrorMatches, `json: cannot unmarshal object into Go value of type chan string`)
	c.Assert(val, gc.IsNil)
	assertDecodeResponseError(c, err, http.StatusOK, `{"one": "two"}`)
}

func (s *clientSuite) TestUnmarshalJSONWithDecodeErrorAndLargeBody(c *gc.C) {
	s.PatchValue(httprequest.MaxErrorBodySize, 11)

	resp := &http.Response{
		Header: http.Header{
			"Content-Type": {"application/json"},
		},
		StatusCode: http.StatusOK,
		Body:       ioutil.NopCloser(strings.NewReader(`"23456789 123456789"`)),
	}
	var val chan string
	err := httprequest.UnmarshalJSONResponse(resp, &val)
	c.Assert(err, gc.ErrorMatches, `json: cannot unmarshal string into Go value of type chan string`)
	c.Assert(val, gc.IsNil)
	assertDecodeResponseError(c, err, http.StatusOK, `"23456789 1`)
}

func assertDecodeResponseError(c *gc.C, err error, status int, body string) {
	c.Assert(errgo.Cause(err), gc.FitsTypeOf, (*httprequest.DecodeResponseError)(nil))
	err1 := errgo.Cause(err).(*httprequest.DecodeResponseError)
	data, err := ioutil.ReadAll(err1.Response.Body)
	c.Assert(err, gc.IsNil)
	c.Assert(err1.Response.StatusCode, gc.Equals, status)
	c.Assert(string(data), gc.Equals, body)
}

func (*clientSuite) newServer() *httptest.Server {
	f := func(p httprequest.Params) (clientHandlers, context.Context, error) {
		return clientHandlers{}, p.Context, nil
	}
	handlers := testServer.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 chM5Req struct {
	httprequest.Route `httprequest:"GET /m5"`
}

func (clientHandlers) M5(p httprequest.Params, _ *chM5Req) {
	p.Response.WriteHeader(http.StatusTeapot)
	p.Response.Write([]byte("bad error value"))
}

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) (*http.Response, error)

func (f doerFunc) Do(req *http.Request) (*http.Response, error) {
	return f(req)
}

type doerWithContextFunc func(ctx context.Context, req *http.Request) (*http.Response, error)

func (f doerWithContextFunc) Do(req *http.Request) (*http.Response, error) {
	return f(nil, req)
}

func (f doerWithContextFunc) DoWithContext(ctx context.Context, req *http.Request) (*http.Response, error) {
	if ctx == nil {
		panic("unexpected nil context")
	}
	return f(ctx, 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 {
	byte  byte
	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{r.byte}), 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
}