github.com/ydb-platform/ydb-go-sdk/v3@v3.57.0/internal/topic/topicreaderinternal/one_time_reader_test.go (about) 1 package topicreaderinternal 2 3 import ( 4 "bytes" 5 "errors" 6 "io" 7 "testing" 8 "testing/iotest" 9 10 "github.com/stretchr/testify/require" 11 ) 12 13 func TestOneTimeReader(t *testing.T) { 14 t.Run("FullRead", func(t *testing.T) { 15 r := newOneTimeReader(bytes.NewReader([]byte{1, 2, 3})) 16 dstBuf := make([]byte, 3) 17 n, err := r.Read(dstBuf) 18 require.NoError(t, err) 19 require.Equal(t, 3, n) 20 require.Equal(t, []byte{1, 2, 3}, dstBuf) 21 _, err = r.Read(dstBuf) 22 require.ErrorIs(t, err, io.EOF) 23 require.Empty(t, r.reader) 24 require.Equal(t, io.EOF, r.err) 25 }) 26 t.Run("DstMoreThenContent", func(t *testing.T) { 27 r := newOneTimeReader(bytes.NewReader([]byte{1, 2, 3})) 28 dstBuf := make([]byte, 4) 29 n, err := r.Read(dstBuf) 30 require.NoError(t, err) 31 require.Equal(t, 3, n) 32 require.Equal(t, []byte{1, 2, 3, 0}, dstBuf) 33 34 _, err = r.Read(dstBuf) 35 require.ErrorIs(t, err, io.EOF) 36 require.Empty(t, r.reader) 37 require.Equal(t, io.EOF, r.err) 38 }) 39 t.Run("ReadLess", func(t *testing.T) { 40 r := newOneTimeReader(bytes.NewReader([]byte{1, 2, 3})) 41 dstBuf := make([]byte, 2) 42 n, err := r.Read(dstBuf) 43 require.NoError(t, err) 44 require.Equal(t, 2, n) 45 require.Equal(t, []byte{1, 2}, dstBuf) 46 require.NotEmpty(t, r.reader) 47 require.NoError(t, r.err) 48 }) 49 t.Run("ReadAfterError", func(t *testing.T) { 50 testErr := errors.New("err") 51 r := &oneTimeReader{err: testErr} 52 dstBuf := make([]byte, 2) 53 n, err := r.Read(dstBuf) 54 require.Equal(t, testErr, err) 55 require.Equal(t, 0, n) 56 }) 57 t.Run("InnerErr", func(t *testing.T) { 58 r := newOneTimeReader(nil) 59 60 bufSize := 2 61 preparedData := make([]byte, 2*bufSize) 62 for i := 0; i < 2*bufSize; i++ { 63 if i < bufSize { 64 preparedData[i] = 1 65 } else { 66 preparedData[i] = 2 67 } 68 } 69 r.reader = iotest.TimeoutReader(bytes.NewReader(preparedData)) 70 71 // first read is ok 72 firstBuf := make([]byte, bufSize) 73 n, err := r.Read(firstBuf) 74 require.NoError(t, err) 75 require.Equal(t, bufSize, n) 76 require.Equal(t, preparedData[:bufSize], firstBuf) 77 require.NoError(t, err) 78 79 // iotest.TimeoutReader return timeout for second read 80 secondBuf := make([]byte, bufSize) 81 n, err = r.Read(secondBuf) 82 require.Equal(t, err, iotest.ErrTimeout) 83 require.Equal(t, 0, n) 84 require.Equal(t, make([]byte, bufSize), secondBuf) 85 86 // Next read again 87 n, err = r.Read(secondBuf) 88 require.Equal(t, err, iotest.ErrTimeout) 89 require.Equal(t, 0, n) 90 }) 91 }