forked from parnurzeal/gorequest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest_test.go
540 lines (499 loc) · 15.9 KB
/
request_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
package gorequest
import (
"bytes"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/elazarl/goproxy"
)
// testing for Get method
func TestGet(t *testing.T) {
const case1_empty = "/"
const case2_set_header = "/set_header"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is GET before going to check other features
if r.Method != GET {
t.Errorf("Expected method %q; got %q", GET, r.Method)
}
if r.Header == nil {
t.Errorf("Expected non-nil request Header")
}
switch r.URL.Path {
default:
t.Errorf("No testing for this case yet : %q", r.URL.Path)
case case1_empty:
t.Logf("case %v ", case1_empty)
case case2_set_header:
t.Logf("case %v ", case2_set_header)
if r.Header.Get("API-Key") != "fookey" {
t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key"))
}
}
}))
defer ts.Close()
New().Get(ts.URL + case1_empty).
End()
New().Get(ts.URL+case2_set_header).
Set("API-Key", "fookey").
End()
}
// testing for POST method
func TestPost(t *testing.T) {
const case1_empty = "/"
const case2_set_header = "/set_header"
const case3_send_json = "/send_json"
const case4_send_string = "/send_string"
const case5_integration_send_json_string = "/integration_send_json_string"
const case6_set_query = "/set_query"
const case7_integration_send_json_struct = "/integration_send_json_struct"
// Check that the number conversion should be converted as string not float64
const case8_send_json_with_long_id_number = "/send_json_with_long_id_number"
const case9_send_json_string_with_long_id_number_as_form_result = "/send_json_string_with_long_id_number_as_form_result"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is PATCH before going to check other features
if r.Method != POST {
t.Errorf("Expected method %q; got %q", POST, r.Method)
}
if r.Header == nil {
t.Errorf("Expected non-nil request Header")
}
switch r.URL.Path {
default:
t.Errorf("No testing for this case yet : %q", r.URL.Path)
case case1_empty:
t.Logf("case %v ", case1_empty)
case case2_set_header:
t.Logf("case %v ", case2_set_header)
if r.Header.Get("API-Key") != "fookey" {
t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key"))
}
case case3_send_json:
t.Logf("case %v ", case3_send_json)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != `{"query1":"test","query2":"test"}` {
t.Error(`Expected Body with {"query1":"test","query2":"test"}`, "| but got", string(body))
}
case case4_send_string:
t.Logf("case %v ", case4_send_string)
if r.Header.Get("Content-Type") != "application/x-www-form-urlencoded" {
t.Error("Expected Header Content-Type -> application/x-www-form-urlencoded", "| but got", r.Header.Get("Content-Type"))
}
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != "query1=test&query2=test" {
t.Error("Expected Body with \"query1=test&query2=test\"", "| but got", string(body))
}
case case5_integration_send_json_string:
t.Logf("case %v ", case5_integration_send_json_string)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != "query1=test&query2=test" {
t.Error("Expected Body with \"query1=test&query2=test\"", "| but got", string(body))
}
case case6_set_query:
t.Logf("case %v ", case6_set_query)
v := r.URL.Query()
if v["query1"][0] != "test" {
t.Error("Expected query1:test", "| but got", v["query1"][0])
}
if v["query2"][0] != "test" {
t.Error("Expected query2:test", "| but got", v["query2"][0])
}
case case7_integration_send_json_struct:
t.Logf("case %v ", case7_integration_send_json_struct)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
comparedBody := []byte(`{"Lower":{"Color":"green","Size":1.7},"Upper":{"Color":"red","Size":0},"a":"a","name":"Cindy"}`)
if !bytes.Equal(body, comparedBody) {
t.Errorf(`Expected correct json but got ` + string(body))
}
case case8_send_json_with_long_id_number:
t.Logf("case %v ", case8_send_json_with_long_id_number)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != `{"id":123456789,"name":"nemo"}` {
t.Error(`Expected Body with {"id":123456789,"name":"nemo"}`, "| but got", string(body))
}
case case9_send_json_string_with_long_id_number_as_form_result:
t.Logf("case %v ", case9_send_json_string_with_long_id_number_as_form_result)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != `id=123456789&name=nemo` {
t.Error(`Expected Body with "id=123456789&name=nemo"`, `| but got`, string(body))
}
}
}))
defer ts.Close()
New().Post(ts.URL + case1_empty).
End()
New().Post(ts.URL+case2_set_header).
Set("API-Key", "fookey").
End()
New().Post(ts.URL + case3_send_json).
Send(`{"query1":"test"}`).
Send(`{"query2":"test"}`).
End()
New().Post(ts.URL + case4_send_string).
Send("query1=test").
Send("query2=test").
End()
New().Post(ts.URL + case5_integration_send_json_string).
Send("query1=test").
Send(`{"query2":"test"}`).
End()
/* TODO: More testing post for application/x-www-form-urlencoded
post.query(json), post.query(string), post.send(json), post.send(string), post.query(both).send(both)
*/
New().Post(ts.URL + case6_set_query).
Query("query1=test").
Query("query2=test").
End()
// TODO:
// 1. test normal struct
// 2. test 2nd layer nested struct
// 3. test struct pointer
// 4. test lowercase won't be export to json
// 5. test field tag change to json field name
type Upper struct {
Color string
Size int
note string
}
type Lower struct {
Color string
Size float64
note string
}
type Style struct {
Upper Upper
Lower Lower
Name string `json:"name"`
}
myStyle := Style{Upper: Upper{Color: "red"}, Name: "Cindy", Lower: Lower{Color: "green", Size: 1.7}}
New().Post(ts.URL + case7_integration_send_json_struct).
Send(`{"a":"a"}`).
Send(myStyle).
End()
New().Post(ts.URL + case8_send_json_with_long_id_number).
Send(`{"id":123456789, "name":"nemo"}`).
End()
New().Post(ts.URL + case9_send_json_string_with_long_id_number_as_form_result).
Type("form").
Send(`{"id":123456789, "name":"nemo"}`).
End()
}
// testing for Patch method
func TestPatch(t *testing.T) {
const case1_empty = "/"
const case2_set_header = "/set_header"
const case3_send_json = "/send_json"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// check method is PATCH before going to check other features
if r.Method != PATCH {
t.Errorf("Expected method %q; got %q", PATCH, r.Method)
}
if r.Header == nil {
t.Errorf("Expected non-nil request Header")
}
switch r.URL.Path {
default:
t.Errorf("No testing for this case yet : %q", r.URL.Path)
case case1_empty:
t.Logf("case %v ", case1_empty)
case case2_set_header:
t.Logf("case %v ", case2_set_header)
if r.Header.Get("API-Key") != "fookey" {
t.Errorf("Expected 'API-Key' == %q; got %q", "fookey", r.Header.Get("API-Key"))
}
case case3_send_json:
t.Logf("case %v ", case3_send_json)
defer r.Body.Close()
body, _ := ioutil.ReadAll(r.Body)
if string(body) != `{"query1":"test","query2":"test"}` {
t.Error(`Expected Body with {"query1":"test","query2":"test"}`, "| but got", string(body))
}
}
}))
defer ts.Close()
New().Patch(ts.URL + case1_empty).
End()
New().Patch(ts.URL+case2_set_header).
Set("API-Key", "fookey").
End()
New().Patch(ts.URL + case3_send_json).
Send(`{"query1":"test"}`).
Send(`{"query2":"test"}`).
End()
}
func checkQuery(t *testing.T, q map[string][]string, key string, want string) {
v, ok := q[key]
if !ok {
t.Error(key, "Not Found")
} else if len(v) < 1 {
t.Error("No values for", key)
} else if v[0] != want {
t.Errorf("Expected %v:%v | but got %v", key, want, v[0])
}
return
}
// TODO: more check on url query (all testcases)
func TestQueryFunc(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header == nil {
t.Errorf("Expected non-nil request Header")
}
v := r.URL.Query()
checkQuery(t, v, "query1", "test1")
checkQuery(t, v, "query2", "test2")
}))
defer ts.Close()
New().Post(ts.URL).
Query("query1=test1").
Query("query2=test2").
End()
qq := struct {
Query1 string
Query2 string
}{
Query1: "test1",
Query2: "test2",
}
New().Post(ts.URL).
Query(qq).
End()
}
// TODO: more tests on redirect
func TestRedirectPolicyFunc(t *testing.T) {
redirectSuccess := false
redirectFuncGetCalled := false
tsRedirect := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
redirectSuccess = true
}))
defer tsRedirect.Close()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, tsRedirect.URL, http.StatusMovedPermanently)
}))
defer ts.Close()
New().
Get(ts.URL).
RedirectPolicy(func(req Request, via []Request) error {
redirectFuncGetCalled = true
return nil
}).End()
if !redirectSuccess {
t.Errorf("Expected reaching another redirect url not original one")
}
if !redirectFuncGetCalled {
t.Errorf("Expected redirect policy func to get called")
}
}
func TestEndBytes(t *testing.T) {
serverOutput := "hello world"
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte(serverOutput))
}))
defer ts.Close()
// Callback.
{
resp, bodyBytes, errs := New().Get(ts.URL).EndBytes(func(resp Response, body []byte, errs []error) {
if len(errs) > 0 {
t.Fatalf("Unexpected errors: %s", errs)
}
if resp.StatusCode != 200 {
t.Fatalf("Expected StatusCode=200, actual StatusCode=%v", resp.StatusCode)
}
if string(body) != serverOutput {
t.Errorf("Expected bodyBytes=%s, actual bodyBytes=%s", serverOutput, string(body))
}
})
if len(errs) > 0 {
t.Fatalf("Unexpected errors: %s", errs)
}
if resp.StatusCode != 200 {
t.Fatalf("Expected StatusCode=200, actual StatusCode=%v", resp.StatusCode)
}
if string(bodyBytes) != serverOutput {
t.Errorf("Expected bodyBytes=%s, actual bodyBytes=%s", serverOutput, string(bodyBytes))
}
}
// No callback.
{
resp, bodyBytes, errs := New().Get(ts.URL).EndBytes()
if len(errs) > 0 {
t.Errorf("Unexpected errors: %s", errs)
}
if resp.StatusCode != 200 {
t.Errorf("Expected StatusCode=200, actual StatusCode=%v", resp.StatusCode)
}
if string(bodyBytes) != serverOutput {
t.Errorf("Expected bodyBytes=%s, actual bodyBytes=%s", serverOutput, string(bodyBytes))
}
}
}
func TestProxyFunc(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "proxy passed")
}))
defer ts.Close()
// start proxy
proxy := goproxy.NewProxyHttpServer()
proxy.OnRequest().DoFunc(
func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
return r, nil
})
ts2 := httptest.NewServer(proxy)
// sending request via Proxy
resp, body, _ := New().Proxy(ts2.URL).Get(ts.URL).End()
if resp.StatusCode != 200 {
t.Errorf("Expected 200 Status code")
}
if body != "proxy passed" {
t.Errorf("Expected 'proxy passed' body string")
}
}
func TestTimeoutFunc(t *testing.T) {
// 1st case, dial timeout
startTime := time.Now()
_, _, errs := New().Timeout(1000 * time.Millisecond).Get("http://www.google.com:81").End()
elapsedTime := time.Since(startTime)
if errs == nil {
t.Errorf("Expected dial timeout error but get nothing")
}
if elapsedTime < 1000*time.Millisecond || elapsedTime > 1500*time.Millisecond {
t.Errorf("Expected timeout in between 1000 -> 1500 ms | but got ", elapsedTime)
}
// 2st case, read/write timeout (Can dial to url but want to timeout because too long operation on the server)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(1 * time.Second)
w.WriteHeader(200)
}))
request := New().Timeout(1000 * time.Millisecond)
startTime = time.Now()
_, _, errs = request.Get(ts.URL).End()
elapsedTime = time.Since(startTime)
if errs == nil {
t.Errorf("Expected dial+read/write timeout | but get nothing")
}
if elapsedTime < 1000*time.Millisecond || elapsedTime > 1500*time.Millisecond {
t.Errorf("Expected timeout in between 1000 -> 1500 ms | but got ", elapsedTime)
}
// 3rd case, testing reuse of same request
ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(1 * time.Second)
w.WriteHeader(200)
}))
startTime = time.Now()
_, _, errs = request.Get(ts.URL).End()
elapsedTime = time.Since(startTime)
if errs == nil {
t.Errorf("Expected dial+read/write timeout | but get nothing")
}
if elapsedTime < 1000*time.Millisecond || elapsedTime > 1500*time.Millisecond {
t.Errorf("Expected timeout in between 1000 -> 1500 ms | but got ", elapsedTime)
}
}
func TestCookies(t *testing.T) {
request := New().Timeout(60 * time.Second)
_, _, errs := request.Get("https://github.com").End()
if errs != nil {
t.Errorf("Cookies test request did not complete")
return
}
domain, _ := url.Parse("https://github.com")
if len(request.Client.Jar.Cookies(domain)) == 0 {
t.Errorf("Expected cookies | but get nothing")
}
}
func TestGetSetCookie(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != GET {
t.Errorf("Expected method %q; got %q", GET, r.Method)
}
c, err := r.Cookie("API-Cookie-Name")
if err != nil {
t.Error(err)
}
if c == nil {
t.Errorf("Expected non-nil request Cookie 'API-Cookie-Name'")
} else if c.Value != "api-cookie-value" {
t.Errorf("Expected 'API-Cookie-Name' == %q; got %q", "api-cookie-value", c.Value)
}
}))
defer ts.Close()
New().Get(ts.URL).
AddCookie(&http.Cookie{Name: "API-Cookie-Name", Value: "api-cookie-value"}).
End()
}
func TestGetSetCookies(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != GET {
t.Errorf("Expected method %q; got %q", GET, r.Method)
}
c, err := r.Cookie("API-Cookie-Name1")
if err != nil {
t.Error(err)
}
if c == nil {
t.Errorf("Expected non-nil request Cookie 'API-Cookie-Name1'")
} else if c.Value != "api-cookie-value1" {
t.Errorf("Expected 'API-Cookie-Name1' == %q; got %q", "api-cookie-value1", c.Value)
}
c, err = r.Cookie("API-Cookie-Name2")
if err != nil {
t.Error(err)
}
if c == nil {
t.Errorf("Expected non-nil request Cookie 'API-Cookie-Name2'")
} else if c.Value != "api-cookie-value2" {
t.Errorf("Expected 'API-Cookie-Name2' == %q; got %q", "api-cookie-value2", c.Value)
}
}))
defer ts.Close()
New().Get(ts.URL).AddCookies([]*http.Cookie{
&http.Cookie{Name: "API-Cookie-Name1", Value: "api-cookie-value1"},
&http.Cookie{Name: "API-Cookie-Name2", Value: "api-cookie-value2"},
}).End()
}
func TestErrorTypeWrongKey(t *testing.T) {
//defer afterTest(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, checkTypeWrongKey")
}))
defer ts.Close()
_, _, err := New().
Get(ts.URL).
Type("wrongtype").
End()
if len(err) != 0 {
if err[0].Error() != "Type func: incorrect type \"wrongtype\"" {
t.Errorf("Wrong error message: " + err[0].Error())
}
} else {
t.Errorf("Should have error")
}
}
func TestBasicAuth(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
auth := strings.SplitN(r.Header["Authorization"][0], " ", 2)
if len(auth) != 2 || auth[0] != "Basic" {
t.Error("bad syntax")
}
payload, _ := base64.StdEncoding.DecodeString(auth[1])
pair := strings.SplitN(string(payload), ":", 2)
if pair[0] != "myusername" || pair[1] != "mypassword" {
t.Error("Wrong username/password")
}
}))
defer ts.Close()
New().Post(ts.URL).
SetBasicAuth("myusername", "mypassword").
End()
}