-
Notifications
You must be signed in to change notification settings - Fork 1
/
downloader_test.go
679 lines (539 loc) · 16.7 KB
/
downloader_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
671
672
673
674
675
676
677
678
679
package tegenaria
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/go-kiss/monkey"
)
var onceServer sync.Once
var onceProxyServer sync.Once
var ts *httptest.Server
var proxyServer *httptest.Server
func testParser(resp *Context, item chan<- *ItemMeta, req chan<- *Context) error {
newItem := &testItem{
test: "test",
pipelines: make([]int, 0),
}
item <- NewItem(resp, newItem)
return nil
}
// func doTest(request *Request)(Response, Error, context.CancelFunc){
// return nil, nil, nil
// }
func newTestProxyServer() *httptest.Server {
onceProxyServer.Do(func() {
gin.SetMode(gin.ReleaseMode)
router := gin.New()
router.GET("/:a", func(c *gin.Context) {
reqUrl := c.Request.URL.String() // Get request url
req, err := http.NewRequest(c.Request.Method, reqUrl, nil)
if err != nil {
c.AbortWithStatus(404)
return
}
// Forwarding requests from client.
cli := &http.Client{}
resp, err := cli.Do(req)
if err != nil {
c.AbortWithStatus(404)
return
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
c.Data(200, "text/plain", body) // write response body to response.
c.String(200, "This is proxy Server.") // add proxy info.
})
proxyServer = httptest.NewServer(router)
})
return proxyServer
}
func newTestServer() *httptest.Server {
onceServer.Do(func() {
gin.SetMode(gin.ReleaseMode)
router := gin.New()
router.GET("/testGET", func(c *gin.Context) {
c.String(200, "GET")
})
router.POST("/testPOST", func(c *gin.Context) {
dataType, _ := json.Marshal(map[string]string{"key": "value"})
data, err := c.GetRawData()
if err != nil {
c.AbortWithStatus(404)
return
}
if string(data) == string(dataType) {
c.String(200, "POST")
} else {
s := string(data)
c.String(200, s)
}
})
router.GET("/testGetCookie", func(c *gin.Context) {
cookies := c.Request.Cookies()
for _, cookie := range cookies {
http.SetCookie(c.Writer, &http.Cookie{
Name: cookie.Name,
Value: cookie.Value,
Path: "/",
Expires: time.Now().Add(30 * time.Second),
})
}
c.String(200, "cookie")
})
router.GET("/testHeader", func(c *gin.Context) {
header := c.GetHeader("key")
c.String(200, header)
})
router.GET("/testTimeout", func(c *gin.Context) {
time.Sleep(5 * time.Second)
c.String(200, "timeout")
})
router.GET("/test403", func(c *gin.Context) {
c.String(403, "forbidden")
})
router.GET("/testParams", func(c *gin.Context) {
value := c.Query("key")
c.String(200, value)
})
router.GET("/testRedirect1", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "/testRedirect2")
})
router.GET("/testRedirect2", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "/testRedirect3")
})
router.GET("/testRedirect3", func(c *gin.Context) {
c.String(200, "/testRedirect3")
})
router.GET("/testJson", func(c *gin.Context) {
data := gin.H{
"name": "json",
"msg": "hello world",
"age": 18,
}
c.JSON(200, data)
})
router.GET("/proxy", func(c *gin.Context) {
c.String(200, "This is target website.")
})
router.GET("/testFile", func(c *gin.Context) {
testString := make([]string, 200000)
for i := 0; i < 200000; i++ {
testString = append(testString, "This test files")
}
c.String(200, "", testString)
})
ts = httptest.NewServer(router)
})
return ts
}
func TestRequestGet(t *testing.T) {
server := newTestServer()
request := NewRequest(server.URL+"/testGET", GET, testParser)
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader := NewDownloader(DownloadWithTlsConfig(&tls.Config{InsecureSkipVerify: true}))
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
resp := result.DownloadResult.Response
if err != nil {
t.Errorf("request error")
}
if resp.Status != 200 {
t.Errorf("response status = %d; expected %d", resp.Status, 200)
}
if resp.String() != "GET" {
t.Errorf("response text = %s; expected %s", resp.String(), "GET")
}
}
func TestRequestPost(t *testing.T) {
body := map[string]interface{}{
"key1": "value1",
}
server := newTestServer()
request := NewRequest(server.URL+"/testPOST", POST, testParser, RequestWithRequestBody(body))
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader := NewDownloader()
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
resp := result.DownloadResult.Response
if err != nil {
t.Errorf("request error %s", err.Error())
}
if resp.Status != 200 {
t.Errorf("response status = %d; expected %d", resp.Status, 200)
}
data,_ := resp.Json()
if data["key1"].(string) != "value1" {
t.Errorf("response text = %v; expected %s", data, body)
}
}
func TestRequestCookie(t *testing.T) {
cookies := map[string]string{
"test1": "test1",
"test2": "test2",
}
server := newTestServer()
// downloader := NewDownloader()
request := NewRequest(server.URL+"/testGetCookie", GET, testParser, RequestWithRequestCookies(cookies))
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
// var MainCtx context.Context = context.Background()
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader := NewDownloader()
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
resp := result.DownloadResult.Response
if err != nil {
t.Errorf("request error with cookies")
}
if resp.Status != 200 {
t.Errorf("response with cookies status = %d; expected %d", resp.Status, 200)
}
if len(resp.Header["Set-Cookie"]) != 2 {
t.Errorf("request with cookies get = %d; expected %d", len(resp.Header["Set-Cookie"]), 2)
}
}
func TestRequestQueryParams(t *testing.T) {
params := map[string]string{
"key": "value",
}
server := newTestServer()
downloader := NewDownloader()
request := NewRequest(server.URL+"/testParams", GET, testParser, RequestWithRequestParams(params))
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
// var MainCtx context.Context = context.Background()
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
resp := result.DownloadResult.Response
if err != nil {
t.Errorf("request error")
}
if resp.Status != 200 {
t.Errorf("response with cookies status = %d; expected %d", resp.Status, 200)
}
if resp.String() != "value" {
t.Errorf("request with params get = %s; expected %s", resp.String(), "value")
}
}
func TestRequestProxy(t *testing.T) {
server := newTestServer()
proxyServer := newTestProxyServer()
downloader := NewDownloader()
proxy := Proxy{
ProxyUrl: proxyServer.URL,
}
defer proxyServer.Close()
request := NewRequest(server.URL+"/proxy", GET, testParser, RequestWithRequestProxy(proxy))
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
// var MainCtx context.Context = context.Background()
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
resp := result.DownloadResult.Response
if err != nil {
t.Errorf("request error")
}
if resp.Status != 200 {
t.Errorf("response status = %d; expected %d", resp.Status, 200)
}
if resp.String() != "This is target website.This is proxy Server." {
t.Errorf("response text = %s; expected %s", resp.String(), "This is target website.This is proxy Server.")
}
}
func TestRequestHeaders(t *testing.T) {
server := newTestServer()
downloader := NewDownloader()
headers := map[string]string{
"KEY": "value",
"Intparams": "1",
"Boolparams": "false",
}
request := NewRequest(server.URL+"/testHeader", GET, testParser, RequestWithRequestHeader(headers))
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
// var MainCtx context.Context = context.Background()
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
go downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
resp := result.DownloadResult.Response
if err != nil {
t.Errorf("request error")
}
if resp.Status != 200 {
t.Errorf("response status = %d; expected %d", resp.Status, 200)
}
if resp.String() != "value" {
t.Errorf("request with headers get = %s; expected %s", resp.String(), "value")
}
}
func TestTimeout(t *testing.T) {
server := newTestServer()
downloader := NewDownloader(DownloadWithTimeout(1 * time.Second))
request := NewRequest(server.URL+"/testTimeout", GET, testParser)
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
// var MainCtx context.Context = context.Background()
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
resp := result.DownloadResult.Response
if err == nil {
t.Errorf("request timeout expected error but no any errors")
}
if resp != nil {
t.Errorf("response = %v; expected nil", resp)
}
}
func TestLargeFile(t *testing.T) {
server := newTestServer()
file, _ := os.Create("test.file")
// writer := bufio.NewWriter(file)
defer os.Remove("test.file")
defer file.Close()
downloader := NewDownloader(DownloadWithTimeout(1 * time.Second))
request := NewRequest(server.URL+"/testFile", GET, testParser, RequestWithResponseWriter(file))
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
// var MainCtx context.Context = context.Background()
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
resp := result.DownloadResult.Response
if err != nil || resp == nil {
t.Errorf("request error %s", err.Error())
}
if resp.Status != 200 {
t.Errorf("response status = %d; expected %d", resp.Status, 200)
}
fi, statErr := os.Stat("test.file")
if statErr != nil {
t.Errorf("get test.file info fail %s", err)
}
if fi.Size() == 0 {
t.Errorf("get test.file size 0")
}
}
func TestJsonResponse(t *testing.T) {
server := newTestServer()
downloader := NewDownloader()
request := NewRequest(server.URL+"/testJson", GET, testParser)
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
resp := result.DownloadResult.Response
if err != nil {
t.Errorf("request json error %s", err.Error())
}
if resp.Status != 200 {
t.Errorf("response status = %d; expected %d", resp.Status, 200)
}
r,errJson := resp.Json()
if r["name"] != "json" {
t.Errorf("request with headers get = %s; expected %s", resp.String(), "json")
}
if errJson !=nil{
t.Errorf("read response json err %s", errJson.Error())
}
monkey.Patch(json.Unmarshal, func(data []byte, v interface{}) error {
return errors.New("Unmarshal json response")
})
_,errJson = resp.Json()
if !strings.Contains(errJson.Error(), "Unmarshal json response"){
t.Errorf("unmarshal json response except 'Unmarshal json response' error but not")
}
}
func TestRedirectLimit(t *testing.T) {
server := newTestServer()
downloader := NewDownloader()
request := NewRequest(server.URL+"/testRedirect1", GET, testParser, RequestWithMaxRedirects(1))
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
resp := result.DownloadResult.Response
if err == nil {
t.Errorf("request redirect should be limit error\n")
}
if resp != nil {
t.Errorf("response is not empty ")
}
}
func TestNotAllowRedirect(t *testing.T) {
server := newTestServer()
downloader := NewDownloader()
request := NewRequest(server.URL+"/testRedirect1", GET, testParser, RequestWithAllowRedirects(false))
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
resp := result.DownloadResult.Response
if !strings.Contains(err.Error(), "maximum number of redirects") {
t.Errorf("Except error exceeded the maximum number of redirects,but get %s\n", err.Error())
}
if resp != nil {
t.Errorf("response is not empty ")
}
}
func TestInvalidURL(t *testing.T) {
downloader := NewDownloader()
request := NewRequest("error"+"/testRedirect1", GET, testParser)
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
if err == nil {
t.Errorf("request invlid url should get an error\n")
}
}
func TestResponseReadError(t *testing.T) {
server := newTestServer()
request := NewRequest(server.URL+"/testGET", GET, testParser)
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
monkey.Patch(io.Copy, func(dst io.Writer, src io.Reader) (written int64, err error) {
return 0, errors.New("empty buffer in CopyBuffer")
})
downloader := NewDownloader()
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
msg := err.Error()
if !strings.Contains(msg, "read response to buffer error") {
t.Errorf("request should have error read response to buffer error,but get %s\n", err.Error())
}
}
func TestProxyUrlError(t *testing.T) {
server := newTestServer()
proxyServer := newTestProxyServer()
proxy := Proxy{
ProxyUrl: "error",
}
monkey.Patch(urlParse, func(string) (url *url.URL, err error) {
return nil, errors.New("proxy invail url")
})
defer proxyServer.Close()
request := NewRequest(server.URL+"/proxy", GET, testParser, RequestWithRequestProxy(proxy))
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
downloader := NewDownloader()
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
if err.Error() == "proxy invail url" {
t.Errorf("request should have error proxy invail url, but get %s\n", err.Error())
}
}
func TestDownloaderRequestConextError(t *testing.T) {
server := newTestServer()
request := NewRequest(server.URL+"/testGET", GET, testParser)
var MainCtx context.Context = context.Background()
cancelCtx, cancel := context.WithCancel(MainCtx)
ctx := NewContext(request, WithContext(cancelCtx))
defer func() {
cancel()
}()
resultChan := make(chan *Context, 1)
monkey.Patch(http.NewRequestWithContext, func(ctx context.Context, method, url string, body io.Reader) (*http.Request, error) {
return nil, errors.New("creat request with context fail")
})
downloader := NewDownloader()
downloader.Download(ctx, resultChan)
result := <-resultChan
err := result.DownloadResult.Error
if err.Error() == "creat request with context fail" {
t.Errorf("request should have error creat request with context fail, but get %s\n", err.Error())
}
}