-
Notifications
You must be signed in to change notification settings - Fork 2
/
chromedl_test.go
618 lines (589 loc) · 14.2 KB
/
chromedl_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
package chromedl
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"testing"
"time"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
"github.com/pkg/errors"
"github.com/rusq/dlog"
)
func init() {
dlog.SetDebug(true)
}
func fakeRunnerWithErr(err error) runnerFn {
return func(ctx context.Context, actions ...chromedp.Action) error {
return err
}
}
func TestDownload(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
serveFile(rw, r, "test.txt", []byte("test data"))
}))
defer srv.Close()
t.Logf("test server at: %s", srv.URL)
tests := []struct {
name string
uri string
want []byte
wantErr bool
}{
{"x", srv.URL + "/test.txt", []byte("test data"), false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r, err := Download(context.Background(), tt.uri)
if (err != nil) != tt.wantErr {
t.Errorf("Get() error = %v, wantErr %v", err, tt.wantErr)
return
}
if r == nil {
return
}
got, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("reader error: %s", err)
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Get() = %v, want %v", got, tt.want)
}
})
}
}
func TestMultiDL(t *testing.T) {
var iterationC = make(chan int, 1)
var format = "test data %d"
var filefmt = "test%d.txt"
srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
i := <-iterationC
file := fmt.Sprintf(filefmt, i)
data := fmt.Sprintf(format, i)
serveFile(rw, r, file, []byte(data))
}))
defer srv.Close()
t.Logf("test server at: %s", srv.URL)
dlog.SetDebug(true)
defer dlog.SetDebug(false)
bi, err := New()
if err != nil {
t.Fatal(err)
}
defer bi.Stop()
for i := 0; i < 100; i++ {
t.Run(fmt.Sprintf("test %d", i), func(t *testing.T) {
val := fmt.Sprintf(format, i)
iterationC <- i
r, err := bi.Download(context.Background(), srv.URL+"/"+fmt.Sprintf(filefmt, i))
if err != nil {
t.Fatalf("%+v", err)
}
if r == nil {
t.Fatal("reader is nil")
}
got, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("reader error: %s", err)
}
if !bytes.Equal(got, []byte(val)) {
t.Errorf("data mismatch: got=%q vs want=%q", string(got), val)
}
})
}
}
func serveFile(w http.ResponseWriter, r *http.Request, filename string, data []byte) {
w.Header().Set("Content-Disposition", "attachment; filename="+filename+"")
w.Header().Set("Expires", "0")
w.Header().Set("Content-Transfer-Encoding", "binary")
w.Header().Set("Content-Length", strconv.Itoa(len(data)))
w.Header().Set("Content-Control", "private, no-transform, no-store, must-revalidate")
http.ServeContent(w, r, filename, time.Now(), bytes.NewReader(data))
}
func ExampleDownload() {
const rbnzRates = "https://www.rbnz.govt.nz/-/media/ReserveBank/Files/Statistics/tables/b1/hb1-daily.xlsx?revision=5fa61401-a877-4607-b7ae-2e060c09935d"
r, err := Download(context.Background(), rbnzRates)
if err != nil {
log.Fatal(err)
}
data, err := ioutil.ReadAll(r)
if err != nil {
log.Fatal(err)
}
fmt.Printf("file size > 0: %v\n", len(data) > 0)
fmt.Printf("file signature: %s\n", string(data[0:2]))
// Output:
// file size > 0: true
// file signature: PK
}
func TestInstance_readRequest(t *testing.T) {
type fields struct {
cfg config
ctx context.Context
allocCancel context.CancelFunc
browserCancel context.CancelFunc
lnCancel context.CancelFunc
guidC chan string
requestIDC chan network.RequestID
requests map[network.RequestID]bool
tmpdir string
}
type args struct {
reqID network.RequestID
}
tests := []struct {
name string
fields fields
args args
runner runnerFn
want []byte
wantErr bool
}{
{
"no error",
fields{},
args{reqID: network.RequestID("123")},
fakeRunnerWithErr(nil),
nil,
false,
},
{
"error",
fields{},
args{reqID: network.RequestID("123")},
fakeRunnerWithErr(errors.New("failed")),
nil,
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
bi := &Instance{
cfg: tt.fields.cfg,
ctx: tt.fields.ctx,
allocFn: tt.fields.allocCancel,
browserFn: tt.fields.browserCancel,
lnCancel: tt.fields.lnCancel,
guidC: tt.fields.guidC,
requestIDC: tt.fields.requestIDC,
requests: tt.fields.requests,
tmpdir: tt.fields.tmpdir,
}
oldRunner := runner
defer func() {
runner = oldRunner
}()
runner = tt.runner
got, err := bi.readRequest(tt.args.reqID)
if (err != nil) != tt.wantErr {
t.Errorf("Instance.readRequest() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Instance.readRequest() = %v, want %v", got, tt.want)
}
})
}
}
// genFile generates a temporary file in directory dir with contents.
func genFile(t *testing.T, dir string, contents string) string {
f, err := ioutil.TempFile(dir, "tmp*")
if err != nil {
t.Fatal(err)
}
defer f.Close()
f.Write([]byte(contents))
return filepath.Base(f.Name())
}
func TestInstance_readFile(t *testing.T) {
const contents = "test contents"
testtmp, err := ioutil.TempDir("", "chromedl_test*")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(testtmp)
type fields struct {
cfg config
ctx context.Context
allocCancel context.CancelFunc
browserCancel context.CancelFunc
lnCancel context.CancelFunc
guidC chan string
requestIDC chan network.RequestID
requests map[network.RequestID]bool
tmpdir string
}
type args struct {
name string
}
tests := []struct {
name string
fields fields
args args
want []byte
wantErr bool
}{
{
"no error",
fields{tmpdir: testtmp},
args{name: genFile(t, testtmp, contents)},
[]byte(contents),
false,
},
{
"non-existing",
fields{tmpdir: testtmp},
args{name: "$not here$"},
nil,
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
defer os.Remove(tt.args.name)
bi := &Instance{
cfg: tt.fields.cfg,
ctx: tt.fields.ctx,
allocFn: tt.fields.allocCancel,
browserFn: tt.fields.browserCancel,
lnCancel: tt.fields.lnCancel,
guidC: tt.fields.guidC,
requestIDC: tt.fields.requestIDC,
requests: tt.fields.requests,
tmpdir: tt.fields.tmpdir,
}
got, err := bi.readFile(tt.args.name)
if (err != nil) != tt.wantErr {
t.Errorf("Instance.readFile() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Instance.readFile() = %v, want %v", got, tt.want)
}
})
}
}
func TestInstance_waitTransfer(t *testing.T) {
const contents = "test contents"
testtmp, err := ioutil.TempDir("", "chromedl_test*")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(testtmp)
cancelledCtx, cancel := context.WithCancel(context.Background())
cancel()
type fields struct {
cfg config
ctx context.Context
allocCancel context.CancelFunc
browserCancel context.CancelFunc
lnCancel context.CancelFunc
guidC chan string
requestIDC chan network.RequestID
requests map[network.RequestID]bool
tmpdir string
}
type args struct {
ctx context.Context
}
tests := []struct {
name string
fields fields
args args
init func(bi *Instance) error
want []byte
wantErr bool
}{
{
"file guid",
fields{
ctx: context.Background(),
guidC: make(chan string, 1),
tmpdir: testtmp,
},
args{ctx: context.Background()},
func(bi *Instance) error {
const filename = "test_data.txt"
if err := ioutil.WriteFile(filepath.Join(bi.tmpdir, filename), []byte(contents), 0644); err != nil {
return errors.WithStack(err)
}
bi.guidC <- filename
return nil
},
[]byte(contents),
false,
},
{
"download cancelled",
fields{
ctx: context.Background(),
guidC: make(chan string, 1),
tmpdir: testtmp,
},
args{ctx: context.Background()},
func(bi *Instance) error {
bi.guidC <- ""
return nil
},
nil,
true,
},
{
"cancelled main context",
fields{
guidC: make(chan string, 1),
},
args{ctx: context.Background()},
func(bi *Instance) error {
ctx, cancel := context.WithCancel(context.Background())
bi.ctx = ctx
cancel()
// to ensure - sending the file on the guidC after some time.
go time.AfterFunc(1*time.Second, func() {
const filename = "test_data.txt"
if err := ioutil.WriteFile(filepath.Join(bi.tmpdir, filename), []byte(contents), 0644); err != nil {
t.Log(err)
}
bi.guidC <- filename
})
return nil
},
nil,
true,
},
{
"cancelled function context",
fields{
ctx: context.Background(),
guidC: make(chan string, 1),
},
args{ctx: cancelledCtx},
func(bi *Instance) error {
// to ensure - sending the file on the guidC after some time.
go time.AfterFunc(1*time.Second, func() {
const filename = "test_data.txt"
if err := ioutil.WriteFile(filepath.Join(bi.tmpdir, filename), []byte(contents), 0644); err != nil {
t.Log(err)
}
bi.guidC <- filename
})
return nil
},
nil,
true,
},
{
"request",
fields{
ctx: context.Background(),
requestIDC: make(chan network.RequestID, 1),
tmpdir: testtmp,
},
args{ctx: context.Background()},
func(bi *Instance) error {
bi.requestIDC <- network.RequestID("test")
return nil
},
[]byte{},
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
oldRunner := runner
defer func() {
runner = oldRunner
}()
runner = fakeRunnerWithErr(nil)
bi := &Instance{
cfg: tt.fields.cfg,
ctx: tt.fields.ctx,
allocFn: tt.fields.allocCancel,
browserFn: tt.fields.browserCancel,
lnCancel: tt.fields.lnCancel,
guidC: tt.fields.guidC,
requestIDC: tt.fields.requestIDC,
requests: tt.fields.requests,
tmpdir: tt.fields.tmpdir,
}
if err := tt.init(bi); err != nil {
t.Fatalf("init failed: %s", err)
}
r, err := bi.waitTransfer(tt.args.ctx)
if (err != nil) != tt.wantErr {
t.Errorf("Instance.waitTransfer() error = %v, wantErr %v", err, tt.wantErr)
return
}
if r == nil {
return
}
got, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("failed to read: %s", err)
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Instance.waitTransfer() = %v, want %v", got, tt.want)
}
})
}
}
func TestInstance_navigate(t *testing.T) {
cancelledCtx, cancel := context.WithCancel(context.Background())
cancel()
type fields struct {
cfg config
ctx context.Context
allocCancel context.CancelFunc
browserCancel context.CancelFunc
lnCancel context.CancelFunc
guidC chan string
requestIDC chan network.RequestID
requests map[network.RequestID]bool
tmpdir string
}
type args struct {
ctx context.Context
uri string
}
tests := []struct {
name string
fields fields
runnerFn runnerFn
args args
wantErr bool
}{
{
"no error",
fields{
ctx: context.Background(),
},
fakeRunnerWithErr(nil),
args{ctx: context.Background(), uri: "test"},
false,
},
{
"error",
fields{
ctx: context.Background(),
},
fakeRunnerWithErr(errors.New("test error")),
args{ctx: context.Background(), uri: "test"},
true,
},
{
"main context cancelled",
fields{
ctx: cancelledCtx,
},
fakeRunnerWithErr(nil),
args{ctx: context.Background(), uri: "test"},
true,
},
{
"arg context cancelled",
fields{
ctx: context.Background(),
},
fakeRunnerWithErr(nil),
args{ctx: cancelledCtx, uri: "test"},
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
oldRunner := runner
defer func() {
runner = oldRunner
}()
runner = tt.runnerFn
bi := &Instance{
cfg: tt.fields.cfg,
ctx: tt.fields.ctx,
allocFn: tt.fields.allocCancel,
browserFn: tt.fields.browserCancel,
lnCancel: tt.fields.lnCancel,
guidC: tt.fields.guidC,
requestIDC: tt.fields.requestIDC,
requests: tt.fields.requests,
tmpdir: tt.fields.tmpdir,
}
if err := bi.navigate(tt.args.ctx, tt.args.uri); (err != nil) != tt.wantErr {
t.Errorf("Instance.navigate() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestInstance_eventHandler(t *testing.T) {
t.Run("download progress event", func(t *testing.T) {
bi := &Instance{
guidC: make(chan string, 1),
}
bi.eventHandler(&page.EventDownloadProgress{
State: page.DownloadProgressStateCompleted,
GUID: "testGUID",
})
select {
case guid := <-bi.guidC:
if !strings.EqualFold(guid, "testGUID") {
t.Errorf("wrong value: want=%q, got=%q", "testGUID", guid)
}
default:
t.Error("did not receive anything")
}
})
t.Run("download cancelled event", func(t *testing.T) {
bi := &Instance{
guidC: make(chan string, 1),
}
bi.eventHandler(&page.EventDownloadProgress{
State: page.DownloadProgressStateCanceled,
GUID: "testGUID",
})
select {
case guid := <-bi.guidC:
if guid != "" {
t.Errorf("wrong value: want=%q, got=%q", "", guid)
}
default:
t.Error("did not receive anything")
}
})
t.Run("event request will be sent", func(t *testing.T) {
bi := &Instance{
requestIDC: make(chan network.RequestID, 1),
requests: make(map[network.RequestID]bool),
}
// emulate download start
bi.eventHandler(&network.EventRequestWillBeSent{
RequestID: "ID",
Request: &network.Request{URL: "http://example"},
})
if !bi.requests["ID"] {
t.Error("request has not been registered")
}
// emulate download complete
bi.eventHandler(&network.EventLoadingFinished{RequestID: "ID"})
select {
case reqID := <-bi.requestIDC:
if reqID != "ID" {
t.Errorf("request name mismatch: want %q, got %q", "ID", reqID)
}
default:
t.Error("no request ID")
}
// check if request has been removed.
if bi.requests["ID"] {
t.Error("request has not been removed")
}
})
}