storj.io/uplink@v1.13.0/private/storage/streams/peek_test.go (about) 1 // Copyright (C) 2019 Storj Labs, Inc. 2 // See LICENSE for copying information. 3 4 package streams_test 5 6 import ( 7 "bytes" 8 "errors" 9 "io" 10 "testing" 11 12 "github.com/stretchr/testify/assert" 13 14 "storj.io/uplink/private/storage/streams" 15 ) 16 17 func TestThresholdBufAndRead(t *testing.T) { 18 for _, tt := range []struct { 19 name string 20 file []byte 21 thresholdSize int 22 expectedIsRemote bool 23 outputBufLen int 24 readsToEnd bool 25 }{ 26 {"Test strictly less than threshold: ", []byte("abcdefghijklmnopqrstuvwxyz"), 30, false, 30, true}, 27 {"Test strictly greater than threshold: ", []byte("abcdefghijklmnopqrstuvwxyz"), 10, true, 30, true}, 28 {"Test read less than threshold buf: ", []byte("abcdefghijklmnopqrstuvwxyz"), 20, true, 10, false}, 29 {"Test empty file: ", []byte(""), 10, false, 10, true}, 30 {"Test threshold size == len(file): ", []byte("abcdefghijklmnopqrstuvwxyz"), 26, false, 26, true}, 31 } { 32 ioReader := bytes.NewReader(tt.file) 33 p := streams.NewPeekThresholdReader(ioReader) 34 35 isRemote, err := p.IsLargerThan(tt.thresholdSize) 36 assert.Equal(t, tt.expectedIsRemote, isRemote, tt.name) 37 assert.NoError(t, err, tt.name) 38 39 outputBuf := make([]byte, tt.outputBufLen) 40 n, err := io.ReadFull(p, outputBuf) 41 if tt.readsToEnd && err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) { 42 t.Fatalf(tt.name, "unexpected err from ReadFull:\n%s", err.Error()) 43 } else if !tt.readsToEnd && err != nil { 44 t.Fatalf(tt.name, "unexpected err from ReadFull:\n%s", err.Error()) 45 } 46 if tt.readsToEnd && n != len(tt.file) { 47 t.Fatalf(tt.name, "expected size of n to equal length of file") 48 } 49 if !tt.readsToEnd && n != tt.outputBufLen { 50 t.Fatalf(tt.name, "expected n to equal length of outputBuf") 51 } 52 if !bytes.Equal(outputBuf[:n], tt.file[:n]) { 53 t.Fatalf(tt.name, "expected data in outputBuf to match data in file") 54 } 55 } 56 } 57 58 func TestMultipleIsLargerCall(t *testing.T) { 59 file := []byte("abcdefghijklmnopqrstuvwxyz") 60 ioReader := bytes.NewReader(file) 61 p := streams.NewPeekThresholdReader(ioReader) 62 63 _, err := p.IsLargerThan(20) 64 assert.NoError(t, err) 65 66 _, err = p.IsLargerThan(20) 67 if err == nil { 68 t.Fatal("expected to err because multiple call") 69 } 70 } 71 72 func TestIsLargerThanCalledAfterRead(t *testing.T) { 73 file := []byte("abcdefghijklmnopqrstuvwxyz") 74 ioReader := bytes.NewReader(file) 75 p := streams.NewPeekThresholdReader(ioReader) 76 77 outputBuf := make([]byte, 10) 78 _, err := p.Read(outputBuf) 79 assert.NoError(t, err) 80 81 _, err = p.IsLargerThan(20) 82 if err == nil { 83 t.Fatal("expected to err because IsLargerThan called after Read") 84 } 85 }