github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/libraries/utils/async/async_read_test.go (about) 1 // Copyright 2020 Dolthub, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package async 16 17 import ( 18 "context" 19 "fmt" 20 "io" 21 "math/rand" 22 "testing" 23 24 "github.com/stretchr/testify/assert" 25 "github.com/stretchr/testify/require" 26 ) 27 28 func TestReader(t *testing.T) { 29 testReadNItems(t, 0, 32) 30 testReadNItems(t, 1, 32) 31 testReadNItems(t, 65536, 32) 32 33 const maxItems = 4 * 1024 34 const minItems = 4 35 const maxTestBufferSize = 128 36 37 for i := 0; i < 32; i++ { 38 testReadNItems(t, rand.Int63n(maxItems-minItems)+minItems, rand.Int63n(maxTestBufferSize-1)+1) 39 } 40 } 41 42 func testReadNItems(t *testing.T, n int64, bufferSize int64) { 43 t.Run(fmt.Sprintf("%d_%d", n, bufferSize), func(t *testing.T) { 44 arr := make([]int64, n) 45 46 for i := int64(0); i < n; i++ { 47 arr[i] = i 48 } 49 50 readFunc := readFuncForArr(arr) 51 rd := NewAsyncReader(readFunc, 32) 52 err := rd.Start(context.Background()) 53 require.NoError(t, err) 54 55 res := make([]int64, 0) 56 for { 57 val, err := rd.Read() 58 59 if err == io.EOF { 60 break 61 } 62 63 assert.NoError(t, err) 64 res = append(res, val.(int64)) 65 } 66 67 err = rd.Close() 68 require.NoError(t, err) 69 70 assert.Equal(t, arr, res) 71 }) 72 } 73 74 func readFuncForArr(arr []int64) ReadFunc { 75 pos := 0 76 return func(ctx context.Context) (interface{}, error) { 77 if pos >= len(arr) { 78 return nil, io.EOF 79 } 80 81 val := arr[pos] 82 pos++ 83 84 return val, nil 85 } 86 }