github.com/cavaliergopher/grab/v3@v3.0.1/response_test.go (about) 1 package grab 2 3 import ( 4 "bytes" 5 "os" 6 "testing" 7 "time" 8 9 "github.com/cavaliergopher/grab/v3/pkg/grabtest" 10 ) 11 12 // testComplete validates that a completed Response has all the desired fields. 13 func testComplete(t *testing.T, resp *Response) { 14 <-resp.Done 15 if !resp.IsComplete() { 16 t.Errorf("Response.IsComplete returned false") 17 } 18 19 if resp.Start.IsZero() { 20 t.Errorf("Response.Start is zero") 21 } 22 23 if resp.End.IsZero() { 24 t.Error("Response.End is zero") 25 } 26 27 if eta := resp.ETA(); eta != resp.End { 28 t.Errorf("Response.ETA is not equal to Response.End: %v", eta) 29 } 30 31 // the following fields should only be set if no error occurred 32 if resp.Err() == nil { 33 if resp.Filename == "" { 34 t.Errorf("Response.Filename is empty") 35 } 36 37 if resp.Size() == 0 { 38 t.Error("Response.Size is zero") 39 } 40 41 if p := resp.Progress(); p != 1.00 { 42 t.Errorf("Response.Progress returned %v (%v/%v bytes), expected 1", p, resp.BytesComplete(), resp.Size()) 43 } 44 } 45 } 46 47 // TestResponseProgress tests the functions which indicate the progress of an 48 // in-process file transfer. 49 func TestResponseProgress(t *testing.T) { 50 filename := ".testResponseProgress" 51 defer os.Remove(filename) 52 53 sleep := 300 * time.Millisecond 54 size := 1024 * 8 // bytes 55 56 grabtest.WithTestServer(t, func(url string) { 57 // request a slow transfer 58 req := mustNewRequest(filename, url) 59 resp := DefaultClient.Do(req) 60 61 // make sure transfer has not started 62 if resp.IsComplete() { 63 t.Errorf("Transfer should not have started") 64 } 65 66 if p := resp.Progress(); p != 0 { 67 t.Errorf("Transfer should not have started yet but progress is %v", p) 68 } 69 70 // wait for transfer to complete 71 <-resp.Done 72 73 // make sure transfer is complete 74 if p := resp.Progress(); p != 1 { 75 t.Errorf("Transfer is complete but progress is %v", p) 76 } 77 78 if s := resp.BytesComplete(); s != int64(size) { 79 t.Errorf("Expected to transfer %v bytes, got %v", size, s) 80 } 81 }, 82 grabtest.TimeToFirstByte(sleep), 83 grabtest.ContentLength(size), 84 ) 85 } 86 87 func TestResponseOpen(t *testing.T) { 88 grabtest.WithTestServer(t, func(url string) { 89 resp := mustDo(mustNewRequest("", url+"/someFilename")) 90 f, err := resp.Open() 91 if err != nil { 92 t.Error(err) 93 return 94 } 95 defer func() { 96 if err := f.Close(); err != nil { 97 t.Error(err) 98 } 99 }() 100 grabtest.AssertSHA256Sum(t, grabtest.DefaultHandlerSHA256ChecksumBytes, f) 101 }) 102 } 103 104 func TestResponseBytes(t *testing.T) { 105 grabtest.WithTestServer(t, func(url string) { 106 resp := mustDo(mustNewRequest("", url+"/someFilename")) 107 b, err := resp.Bytes() 108 if err != nil { 109 t.Error(err) 110 return 111 } 112 grabtest.AssertSHA256Sum( 113 t, 114 grabtest.DefaultHandlerSHA256ChecksumBytes, 115 bytes.NewReader(b), 116 ) 117 }) 118 }