-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhttp_test.go
353 lines (333 loc) · 9.09 KB
/
http_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
// Copyright 2014 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package qthttptest_test
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
qt "github.com/frankban/quicktest"
"github.com/juju/qthttptest"
)
// handlerResponse holds the body of a testing handler response.
type handlerResponse struct {
URL string
Method string
Body string
Auth bool
Header http.Header
}
func makeHandler(c *qt.C, status int, ctype string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
c.Assert(err, qt.Equals, nil)
hasAuth := req.Header.Get("Authorization") != ""
for _, h := range []string{"User-Agent", "Content-Length", "Accept-Encoding", "Authorization"} {
delete(req.Header, h)
}
// Create the response.
response := handlerResponse{
URL: req.URL.String(),
Method: req.Method,
Body: string(body),
Header: req.Header,
Auth: hasAuth,
}
// Write the response.
w.Header().Set("Content-Type", ctype)
w.WriteHeader(status)
enc := json.NewEncoder(w)
err = enc.Encode(response)
c.Assert(err, qt.Equals, nil)
})
}
var assertJSONCallTests = []struct {
about string
params qthttptest.JSONCallParams
}{{
about: "simple request",
params: qthttptest.JSONCallParams{
Method: "GET",
URL: "/",
},
}, {
about: "method not specified",
params: qthttptest.JSONCallParams{
URL: "/",
},
}, {
about: "POST request with a body",
params: qthttptest.JSONCallParams{
Method: "POST",
URL: "/my/url",
Body: strings.NewReader("request body"),
},
}, {
about: "GET request with custom headers",
params: qthttptest.JSONCallParams{
Method: "GET",
URL: "/my/url",
Header: http.Header{
"Custom1": {"header1", "header2"},
"Custom2": {"foo"},
},
},
}, {
about: "POST request with a JSON body",
params: qthttptest.JSONCallParams{
Method: "POST",
URL: "/my/url",
JSONBody: map[string]int{"hello": 99},
},
}, {
about: "authentication",
params: qthttptest.JSONCallParams{
URL: "/",
Method: "PUT",
Username: "who",
Password: "bad-wolf",
ExpectStatus: http.StatusOK,
},
}, {
about: "test for ExceptHeader in response",
params: qthttptest.JSONCallParams{
URL: "/",
Do: func(req *http.Request) (*http.Response, error) {
resp, err := http.DefaultClient.Do(req)
resp.StatusCode = http.StatusOK
resp.Header["Custom"] = []string{"value1", "value2"}
resp.Header["Ignored"] = []string{"value3", "value3"}
return resp, err
},
ExpectStatus: http.StatusOK,
ExpectHeader: http.Header{
"Custom": {"value1", "value2"},
},
},
}, {
about: "test case insensitive for ExceptHeader in response",
params: qthttptest.JSONCallParams{
URL: "/",
Do: func(req *http.Request) (*http.Response, error) {
resp, err := http.DefaultClient.Do(req)
resp.StatusCode = http.StatusOK
resp.Header["Custom"] = []string{"value1", "value2"}
resp.Header["Ignored"] = []string{"value3", "value3"}
return resp, err
},
ExpectStatus: http.StatusOK,
ExpectHeader: http.Header{
"CUSTOM": {"value1", "value2"},
},
},
}, {
about: "error status",
params: qthttptest.JSONCallParams{
URL: "/",
ExpectStatus: http.StatusBadRequest,
},
}, {
about: "custom Do",
params: qthttptest.JSONCallParams{
URL: "/",
ExpectStatus: http.StatusTeapot,
Do: func(req *http.Request) (*http.Response, error) {
resp, err := http.DefaultClient.Do(req)
resp.StatusCode = http.StatusTeapot
return resp, err
},
},
}, {
about: "custom Do with seekable JSON body",
params: qthttptest.JSONCallParams{
URL: "/",
ExpectStatus: http.StatusTeapot,
JSONBody: 123,
Do: func(req *http.Request) (*http.Response, error) {
r, ok := req.Body.(io.ReadSeeker)
if !ok {
return nil, fmt.Errorf("body is not seeker")
}
data, err := ioutil.ReadAll(r)
if err != nil {
panic(err)
}
if string(data) != "123" {
panic(fmt.Errorf(`unexpected body content, got %q want "123"`, data))
}
r.Seek(0, 0)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
resp.StatusCode = http.StatusTeapot
return resp, err
},
},
}, {
about: "expect error",
params: qthttptest.JSONCallParams{
URL: "/",
ExpectStatus: http.StatusTeapot,
Do: func(req *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("some error")
},
ExpectError: "some error",
},
}, {
about: "expect error regexp",
params: qthttptest.JSONCallParams{
URL: "/",
ExpectStatus: http.StatusTeapot,
Do: func(req *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("some bad error")
},
ExpectError: "some .* error",
},
}}
func TestAssertJSONCall(t *testing.T) {
c := qt.New(t)
for _, test := range assertJSONCallTests {
c.Run(test.about, func(c *qt.C) {
params := test.params
// A missing status is assumed to be http.StatusOK.
status := params.ExpectStatus
if status == 0 {
status = http.StatusOK
}
// Create the HTTP handler for this test.
params.Handler = makeHandler(c, status, "application/json")
// Populate the expected body parameter.
expectBody := handlerResponse{
URL: params.URL,
Method: params.Method,
Header: params.Header,
}
// A missing method is assumed to be "GET".
if expectBody.Method == "" {
expectBody.Method = "GET"
}
expectBody.Header = make(http.Header)
if params.JSONBody != nil {
expectBody.Header.Set("Content-Type", "application/json")
}
for k, v := range params.Header {
expectBody.Header[k] = v
}
if params.JSONBody != nil {
data, err := json.Marshal(params.JSONBody)
c.Assert(err, qt.Equals, nil)
expectBody.Body = string(data)
params.Body = bytes.NewReader(data)
} else if params.Body != nil {
// Handle the request body parameter.
body, err := ioutil.ReadAll(params.Body)
c.Assert(err, qt.Equals, nil)
expectBody.Body = string(body)
params.Body = bytes.NewReader(body)
}
// Handle basic HTTP authentication.
if params.Username != "" || params.Password != "" {
expectBody.Auth = true
}
params.ExpectBody = expectBody
qthttptest.AssertJSONCall(c, params)
})
}
}
func TestAssertJSONCallWithBodyAsserter(t *testing.T) {
c := qt.New(t)
called := false
params := qthttptest.JSONCallParams{
URL: "/",
Handler: makeHandler(c, http.StatusOK, "application/json"),
ExpectBody: qthttptest.BodyAsserter(func(c1 *qt.C, body json.RawMessage) {
c.Assert(c1, qt.Equals, c)
c.Assert(string(body), qthttptest.JSONEquals, handlerResponse{
URL: "/",
Method: "GET",
Header: make(http.Header),
})
called = true
}),
}
qthttptest.AssertJSONCall(c, params)
c.Assert(called, qt.Equals, true)
}
func TestAssertJSONCallWithHostedURL(t *testing.T) {
c := qt.New(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(fmt.Sprintf("%q", "ok "+req.URL.Path)))
}))
defer srv.Close()
qthttptest.AssertJSONCall(c, qthttptest.JSONCallParams{
URL: srv.URL + "/foo",
ExpectBody: "ok /foo",
})
}
var bodyReaderFuncs = []func(string) io.Reader{
func(s string) io.Reader {
return strings.NewReader(s)
},
func(s string) io.Reader {
return bytes.NewBufferString(s)
},
func(s string) io.Reader {
return bytes.NewReader([]byte(s))
},
}
func TestDoRequestWithInferrableContentLength(t *testing.T) {
c := qt.New(t)
text := "hello, world"
for i, f := range bodyReaderFuncs {
c.Logf("test %d", i)
called := false
qthttptest.DoRequest(c, qthttptest.DoRequestParams{
Handler: http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {
c.Check(req.ContentLength, qt.Equals, int64(len(text)))
called = true
}),
Body: f(text),
})
c.Assert(called, qt.Equals, true)
}
}
// The TestAssertJSONCall above exercises the testing.AssertJSONCall succeeding
// calls. Failures are already massively tested in practice. DoRequest and
// AssertJSONResponse are also indirectly tested as they are called by
// AssertJSONCall.
func TestTransport(t *testing.T) {
c := qt.New(t)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(r.URL.String()))
}))
defer server.Close()
transport := qthttptest.URLRewritingTransport{
MatchPrefix: "http://example.com",
Replace: server.URL,
}
client := http.Client{
Transport: &transport,
}
resp, err := client.Get("http://example.com/path")
c.Assert(err, qt.Equals, nil)
body, err := ioutil.ReadAll(resp.Body)
c.Assert(err, qt.Equals, nil)
resp.Body.Close()
c.Assert(resp.Request.URL.String(), qt.Equals, "http://example.com/path")
c.Assert(string(body), qt.Equals, "/path")
transport.RoundTripper = &http.Transport{}
resp, err = client.Get(server.URL + "/otherpath")
c.Assert(err, qt.Equals, nil)
body, err = ioutil.ReadAll(resp.Body)
c.Assert(err, qt.Equals, nil)
resp.Body.Close()
c.Assert(resp.Request.URL.String(), qt.Equals, server.URL+"/otherpath")
c.Assert(string(body), qt.Equals, "/otherpath")
}