-
Notifications
You must be signed in to change notification settings - Fork 1
/
books_test.go
380 lines (312 loc) · 8.15 KB
/
books_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
package books
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
)
var (
mux *http.ServeMux
client *Client
server *httptest.Server
)
func setup() {
mux = http.NewServeMux()
server = httptest.NewServer(mux)
client = NewClient(nil)
url, _ := url.Parse(server.URL)
client.BaseURL = url
}
func teardown() {
server.Close()
}
func testMethod(t *testing.T, r *http.Request, expected string) {
if expected != r.Method {
t.Errorf("Request method = %v, expected %v", r.Method, expected)
}
}
type values map[string]string
func testFormValues(t *testing.T, r *http.Request, values values) {
expected := url.Values{}
for k, v := range values {
expected.Add(k, v)
}
err := r.ParseForm()
if err != nil {
t.Fatalf("parseForm(): %v", err)
}
if !reflect.DeepEqual(expected, r.Form) {
t.Errorf("Request parameters = %v, expected %v", r.Form, expected)
}
}
func testURLParseError(t *testing.T, err error) {
if err == nil {
t.Errorf("Expected error to be returned")
}
if err, ok := err.(*url.Error); !ok || err.Op != "parse" {
t.Errorf("Expected URL parse error, got %+v", err)
}
}
func testClientDefaultBaseURL(t *testing.T, c *Client) {
if c.BaseURL == nil || c.BaseURL.String() != defaultBaseURL {
t.Errorf("NewOAuthClient BaseURL = %v, expected %v", c.BaseURL, defaultBaseURL)
}
}
func testClientDefaultUserAgent(t *testing.T, c *Client) {
if c.UserAgent != userAgent {
t.Errorf("NewClick UserAgent = %v, expected %v", c.UserAgent, userAgent)
}
}
func testClientDefaults(t *testing.T, c *Client) {
testClientDefaultBaseURL(t, c)
testClientDefaultUserAgent(t, c)
}
func TestNewClient(t *testing.T) {
c := NewClient(nil)
testClientDefaults(t, c)
}
func TestNew(t *testing.T) {
c, err := New(nil)
if err != nil {
t.Fatalf("New(): %v", err)
}
testClientDefaults(t, c)
}
func TestNewRequest_badURL(t *testing.T) {
c := NewClient(nil)
_, err := c.NewRequest("GET", ":", nil)
testURLParseError(t, err)
}
func TestDo(t *testing.T) {
setup()
defer teardown()
type foo struct {
A string
}
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if m := "GET"; m != r.Method {
t.Errorf("Request method = %v, expected %v", r.Method, m)
}
fmt.Fprint(w, `{"A":"a"}`)
})
req, _ := client.NewRequest("GET", "/", nil)
body := new(foo)
_, err := client.Do(req, body)
if err != nil {
t.Fatalf("Do(): %v", err)
}
expected := &foo{"a"}
if !reflect.DeepEqual(body, expected) {
t.Errorf("Response body = %v, expected %v", body, expected)
}
}
func TestDo_httpError(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Bad Request", 400)
})
req, _ := client.NewRequest("GET", "/", nil)
_, err := client.Do(req, nil)
if err == nil {
t.Error("Expected HTTP 400 error.")
}
}
// Test handling of an error caused by the internal http client's Do()
// function.
func TestDo_redirectLoop(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusFound)
})
req, _ := client.NewRequest("GET", "/", nil)
_, err := client.Do(req, nil)
if err == nil {
t.Error("Expected error to be returned.")
}
if err, ok := err.(*url.Error); !ok {
t.Errorf("Expected a URL error; got %#v.", err)
}
}
func TestDo_noContent(t *testing.T) {
setup()
defer teardown()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
var body json.RawMessage
req, _ := client.NewRequest("GET", "/", nil)
_, err := client.Do(req, &body)
// Check that empty resp.Body does not return error.
if err != nil {
t.Fatalf("Do returned unexpected error: %v", err)
}
}
func TestCheckResponse(t *testing.T) {
res := &http.Response{
Request: &http.Request{},
StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(strings.NewReader(`{"message":"m",
"errors": [{"resource": "r", "field": "f", "code": "c"}]}`)),
}
err := CheckResponse(res).(*ErrorResponse)
if err == nil {
t.Fatalf("Expected error response.")
}
expected := &ErrorResponse{
Response: res,
}
if !reflect.DeepEqual(err, expected) {
t.Errorf("Error = %#v, expected %#v", err, expected)
}
}
// ensure that we properly handle API errors that do not contain a response
// body
func TestCheckResponse_noBody(t *testing.T) {
res := &http.Response{
Request: &http.Request{},
StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(strings.NewReader("")),
}
err := CheckResponse(res).(*ErrorResponse)
if err == nil {
t.Errorf("Expected error response.")
}
expected := &ErrorResponse{
Response: res,
}
if !reflect.DeepEqual(err, expected) {
t.Errorf("Error = %#v, expected %#v", err, expected)
}
}
func TestNewRequest_withCustomUserAgent(t *testing.T) {
ua := "testing"
c, err := New(nil, SetUserAgent(ua))
if err != nil {
t.Fatalf("New() unexpected error: %v", err)
}
req, _ := c.NewRequest("GET", "/foo", nil)
expected := fmt.Sprintf("%s+%s", ua, userAgent)
if got := req.Header.Get("User-Agent"); got != expected {
t.Errorf("New() UserAgent = %s; expected %s", got, expected)
}
}
func TestNewRequest_withBaseURL(t *testing.T) {
base := "http://localhost/foo"
c, err := New(nil, SetBaseURL(base))
if err != nil {
t.Fatalf("New() unexpected error %v", err)
}
req, _ := c.NewRequest("GET", "/foo", nil)
expected := fmt.Sprintf("%s", base)
if got := req.URL.String(); got != expected {
t.Errorf("New() BaseURL = %s; expected %s", got, expected)
}
}
func TestNewRequest_withBaseURL_badURL(t *testing.T) {
base := ":"
_, err := New(nil, SetBaseURL(base))
testURLParseError(t, err)
}
func TestErrorResponse_error(t *testing.T) {
res := &http.Response{Request: &http.Request{}}
customError := Error{Code: 400, Message: "Employee not Found"}
err := ErrorResponse{
Response: res,
CustomError: customError,
}
if err.Error() == "" {
t.Errorf("Expected non-empty ErrorResponse.Error()")
}
}
func TestNewRequest_emptyBody(t *testing.T) {
c, _ := New(nil)
req, err := c.NewRequest("GET", "/", nil)
if err != nil {
t.Fatalf("NewRequest returned unexpected error: %v", err)
}
if req.Body != nil {
t.Fatalf("constructed request contains a non-nil Body")
}
}
func TestAddOptions(t *testing.T) {
cases := []struct {
name string
path string
expected string
opts *AnnotationsListOptions
isErr bool
}{
{
name: "add options",
path: "/annotations",
expected: "/annotations?volumeId=1",
opts: &AnnotationsListOptions{VolumeID: "1"},
isErr: false,
},
{
name: "add options with existing parameters",
path: "/annotations?source=all&maxResults=10",
expected: "/annotations?volumeId=1&maxResults=40",
opts: &AnnotationsListOptions{VolumeID: "1", MaxResults: 40},
isErr: false,
},
{
name: "bad url string to parse",
path: ":",
expected: ":",
opts: &AnnotationsListOptions{VolumeID: "1", MaxResults: 40},
isErr: true,
},
{
name: "opt set to nil.",
path: "/annotations",
expected: "/annotations",
opts: nil,
isErr: false,
},
}
for _, c := range cases {
got, err := addOptions(c.path, c.opts)
if c.isErr && err == nil {
t.Errorf("%q expected error but none was encountered", c.name)
continue
}
if !c.isErr && err != nil {
t.Errorf("%q unexpected error: %v", c.name, err)
continue
}
if c.isErr {
continue
}
if c.opts == nil && err != nil {
t.Errorf("%q expected error to return nil: %v", c.name, err)
}
gotURL, err := url.Parse(got)
if err != nil {
t.Errorf("%q unable to parse returned URL", c.name)
continue
}
expectedURL, err := url.Parse(c.expected)
if err != nil {
t.Errorf("%q unable to parse expected URL", c.name)
continue
}
// Test for url path to be expected.
if g, e := gotURL.Path, expectedURL.Path; g != e {
t.Errorf("%q path = %q; expected %q", c.name, g, e)
continue
}
// Test for query values to be as expected.
if g, e := gotURL.Query(), expectedURL.Query(); !reflect.DeepEqual(g, e) {
t.Errorf("%q query = %#v; expected %#v", c.name, g, e)
continue
}
}
}