github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/pkg/spanz/convert_test.go (about) 1 // Copyright 2022 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 spanz 15 16 import ( 17 "testing" 18 19 "github.com/pingcap/tiflow/cdc/processor/tablepb" 20 "github.com/stretchr/testify/require" 21 ) 22 23 func TestHashableSpan(t *testing.T) { 24 t.Parallel() 25 26 // Make sure it can be a map key. 27 m := make(map[hashableSpan]int) 28 m[hashableSpan{}] = 1 29 require.Equal(t, 1, m[hashableSpan{}]) 30 31 span := toHashableSpan(TableIDToComparableSpan(1)) 32 require.EqualValues(t, TableIDToComparableSpan(1), span.toSpan()) 33 } 34 35 func TestHashableSpanHeapAlloc(t *testing.T) { 36 span := tablepb.Span{TableID: 1} 37 for i := 0; i < 10; i++ { 38 span.StartKey = append(span.StartKey, byte(i)) 39 span.EndKey = append(span.EndKey, byte(i)) 40 } 41 42 n := 0 43 results := testing.Benchmark(func(b *testing.B) { 44 n = b.N 45 b.ReportAllocs() 46 b.ResetTimer() 47 for i := 0; i < b.N; i++ { 48 hspan := toHashableSpan(span) 49 span = hspan.toSpan() 50 } 51 }) 52 require.EqualValues(t, 0, results.MemAllocs/uint64(n)) 53 } 54 55 func TestUnsafeStringByte(t *testing.T) { 56 b := []byte("unsafe bytes") 57 s := "unsafe bytes" 58 59 us := unsafeBytesToString(b) 60 require.EqualValues(t, s, us) 61 require.EqualValues(t, len(b), len(us)) 62 63 ub := unsafeStringToBytes(s) 64 require.EqualValues(t, b, ub) 65 require.EqualValues(t, len(s), len(ub)) 66 require.EqualValues(t, len(s), cap(ub)) 67 } 68 69 func TestHexKey(t *testing.T) { 70 span := TableIDToComparableSpan(8616) 71 require.Equal(t, "7480000000000021FFA85F720000000000FA", HexKey(span.StartKey)) 72 require.Equal(t, "7480000000000021FFA85F730000000000FA", HexKey(span.EndKey)) 73 }