github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/sink/codec/craft/codec_test.go (about) 1 // Copyright 2021 PingCAP, 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 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package craft 15 16 import ( 17 "math/rand" 18 "testing" 19 "time" 20 21 "github.com/pingcap/tiflow/pkg/leakutil" 22 "github.com/stretchr/testify/require" 23 ) 24 25 func init() { 26 rand.Seed(time.Now().UnixNano()) 27 } 28 29 func TestMain(m *testing.M) { 30 leakutil.SetUpLeakTest(m) 31 } 32 33 func TestSizeTable(t *testing.T) { 34 t.Parallel() 35 36 tables := [][]int64{ 37 { 38 1, 3, 5, 7, 9, 39 }, 40 { 41 2, 4, 6, 8, 10, 42 }, 43 } 44 bits := make([]byte, 16) 45 rand.Read(bits) 46 bits = encodeSizeTables(bits, tables) 47 48 size, decoded, err := decodeSizeTables(bits, NewSliceAllocator(64)) 49 require.Nil(t, err) 50 require.Equal(t, tables, decoded) 51 require.Equal(t, len(bits)-16, size) 52 } 53 54 func TestUvarintReverse(t *testing.T) { 55 t.Parallel() 56 57 var i uint64 = 0 58 59 for i < 0x8000000000000000 { 60 bits := make([]byte, 16) 61 rand.Read(bits) 62 bits, bytes1 := encodeUvarintReversed(bits, i) 63 bytes2, u64, err := decodeUvarintReversed(bits) 64 require.Nil(t, err) 65 require.Equal(t, i, u64) 66 require.Equal(t, len(bits)-16, bytes1) 67 require.Equal(t, bytes2, bytes1) 68 if i == 0 { 69 i = 1 70 } else { 71 i <<= 1 72 } 73 } 74 } 75 76 func newNullableString(a string) *string { 77 return &a 78 } 79 80 func TestEncodeChunk(t *testing.T) { 81 t.Parallel() 82 83 stringChunk := []string{"a", "b", "c"} 84 nullableStringChunk := []*string{newNullableString("a"), newNullableString("b"), newNullableString("c")} 85 int64Chunk := []int64{1, 2, 3} 86 allocator := NewSliceAllocator(64) 87 88 bits := encodeStringChunk(nil, stringChunk) 89 bits, decodedStringChunk, err := decodeStringChunk(bits, 3, allocator) 90 require.Nil(t, err) 91 require.Equal(t, 0, len(bits)) 92 require.Equal(t, stringChunk, decodedStringChunk) 93 94 bits = encodeNullableStringChunk(nil, nullableStringChunk) 95 bits, decodedNullableStringChunk, err := decodeNullableStringChunk(bits, 3, allocator) 96 require.Nil(t, err) 97 require.Equal(t, 0, len(bits)) 98 require.Equal(t, nullableStringChunk, decodedNullableStringChunk) 99 100 bits = encodeVarintChunk(nil, int64Chunk) 101 bits, decodedVarintChunk, err := decodeVarintChunk(bits, 3, allocator) 102 require.Nil(t, err) 103 require.Equal(t, 0, len(bits)) 104 require.Equal(t, int64Chunk, decodedVarintChunk) 105 }