github.com/huaweicloud/golangsdk@v0.0.0-20210831081626-d823fe11ceba/openstack/imageservice/v2/imagedata/testing/requests_test.go (about) 1 package testing 2 3 import ( 4 "fmt" 5 "io" 6 "io/ioutil" 7 "testing" 8 9 "github.com/huaweicloud/golangsdk/openstack/imageservice/v2/imagedata" 10 th "github.com/huaweicloud/golangsdk/testhelper" 11 fakeclient "github.com/huaweicloud/golangsdk/testhelper/client" 12 ) 13 14 func TestUpload(t *testing.T) { 15 th.SetupHTTP() 16 defer th.TeardownHTTP() 17 18 HandlePutImageDataSuccessfully(t) 19 20 err := imagedata.Upload( 21 fakeclient.ServiceClient(), 22 "da3b75d9-3f4a-40e7-8a2c-bfab23927dea", 23 readSeekerOfBytes([]byte{5, 3, 7, 24})).ExtractErr() 24 25 th.AssertNoErr(t, err) 26 } 27 28 func TestStage(t *testing.T) { 29 th.SetupHTTP() 30 defer th.TeardownHTTP() 31 32 HandleStageImageDataSuccessfully(t) 33 34 err := imagedata.Stage( 35 fakeclient.ServiceClient(), 36 "da3b75d9-3f4a-40e7-8a2c-bfab23927dea", 37 readSeekerOfBytes([]byte{5, 3, 7, 24})).ExtractErr() 38 39 th.AssertNoErr(t, err) 40 } 41 42 func readSeekerOfBytes(bs []byte) io.ReadSeeker { 43 return &RS{bs: bs} 44 } 45 46 // implements io.ReadSeeker 47 type RS struct { 48 bs []byte 49 offset int 50 } 51 52 func (rs *RS) Read(p []byte) (int, error) { 53 leftToRead := len(rs.bs) - rs.offset 54 55 if 0 < leftToRead { 56 bytesToWrite := min(leftToRead, len(p)) 57 for i := 0; i < bytesToWrite; i++ { 58 p[i] = rs.bs[rs.offset] 59 rs.offset++ 60 } 61 return bytesToWrite, nil 62 } 63 return 0, io.EOF 64 } 65 66 func min(a int, b int) int { 67 if a < b { 68 return a 69 } 70 return b 71 } 72 73 func (rs *RS) Seek(offset int64, whence int) (int64, error) { 74 var offsetInt = int(offset) 75 if whence == 0 { 76 rs.offset = offsetInt 77 } else if whence == 1 { 78 rs.offset = rs.offset + offsetInt 79 } else if whence == 2 { 80 rs.offset = len(rs.bs) - offsetInt 81 } else { 82 return 0, fmt.Errorf("For parameter `whence`, expected value in {0,1,2} but got: %#v", whence) 83 } 84 85 return int64(rs.offset), nil 86 } 87 88 func TestDownload(t *testing.T) { 89 th.SetupHTTP() 90 defer th.TeardownHTTP() 91 92 HandleGetImageDataSuccessfully(t) 93 94 rdr, err := imagedata.Download(fakeclient.ServiceClient(), "da3b75d9-3f4a-40e7-8a2c-bfab23927dea").Extract() 95 th.AssertNoErr(t, err) 96 97 defer rdr.Close() 98 99 bs, err := ioutil.ReadAll(rdr) 100 th.AssertNoErr(t, err) 101 102 th.AssertByteArrayEquals(t, []byte{34, 87, 0, 23, 23, 23, 56, 255, 254, 0}, bs) 103 }