github.com/turingchain2020/turingchain@v1.1.21/common/db/go_mem_db_test.go (about) 1 // Copyright Turing Corp. 2018 All Rights Reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package db 6 7 import ( 8 "bytes" 9 "fmt" 10 "io/ioutil" 11 "testing" 12 13 "github.com/stretchr/testify/require" 14 ) 15 16 // memdb迭代器测试 17 func TestGoMemDBIterator(t *testing.T) { 18 dir, err := ioutil.TempDir("", "gomemdb") 19 require.NoError(t, err) 20 t.Log(dir) 21 22 memdb, err := NewGoMemDB("gomemdb", dir, 128) 23 require.NoError(t, err) 24 defer memdb.Close() 25 26 testDBIterator(t, memdb) 27 } 28 29 func TestGoMemDBIteratorDel(t *testing.T) { 30 dir, err := ioutil.TempDir("", "gomemdb") 31 require.NoError(t, err) 32 t.Log(dir) 33 34 memdb, err := NewGoMemDB("gomemdb", dir, 128) 35 require.NoError(t, err) 36 defer memdb.Close() 37 38 testDBIteratorDel(t, memdb) 39 } 40 41 func TestGoMemDBBatch(t *testing.T) { 42 dir, err := ioutil.TempDir("", "gomemdb") 43 require.NoError(t, err) 44 t.Log(dir) 45 46 leveldb, err := NewGoMemDB("gomemdb", dir, 128) 47 require.NoError(t, err) 48 defer leveldb.Close() 49 testBatch(t, leveldb) 50 } 51 52 // memdb边界测试 53 func TestGoMemDBBoundary(t *testing.T) { 54 dir, err := ioutil.TempDir("", "gomemdb") 55 require.NoError(t, err) 56 t.Log(dir) 57 58 memdb, err := NewGoMemDB("gomemdb", dir, 128) 59 require.NoError(t, err) 60 defer memdb.Close() 61 62 testDBBoundary(t, memdb) 63 } 64 65 func BenchmarkRandomGoMemDBReadsWrites(b *testing.B) { 66 b.StopTimer() 67 68 numItems := int64(1000000) 69 internal := map[int64]int64{} 70 for i := 0; i < int(numItems); i++ { 71 internal[int64(i)] = int64(0) 72 } 73 db, err := NewGoMemDB(fmt.Sprintf("test_%x", RandStr(12)), "", 1000) 74 if err != nil { 75 b.Fatal(err.Error()) 76 return 77 } 78 79 fmt.Println("ok, starting") 80 b.StartTimer() 81 82 for i := 0; i < b.N; i++ { 83 // Write something 84 { 85 idx := (int64(RandInt()) % numItems) 86 internal[idx]++ 87 val := internal[idx] 88 idxBytes := int642Bytes(idx) 89 valBytes := int642Bytes(val) 90 //fmt.Printf("Set %X -> %X\n", idxBytes, valBytes) 91 db.Set( 92 idxBytes, 93 valBytes, 94 ) 95 } 96 // Read something 97 { 98 idx := (int64(RandInt()) % numItems) 99 val := internal[idx] 100 idxBytes := int642Bytes(idx) 101 valBytes, _ := db.Get(idxBytes) 102 //fmt.Printf("Get %X -> %X\n", idxBytes, valBytes) 103 if val == 0 { 104 if !bytes.Equal(valBytes, nil) { 105 b.Errorf("Expected %v for %v, got %X", 106 nil, idx, valBytes) 107 break 108 } 109 } else { 110 if len(valBytes) != 8 { 111 b.Errorf("Expected length 8 for %v, got %X", 112 idx, valBytes) 113 break 114 } 115 valGot := bytes2Int64(valBytes) 116 if val != valGot { 117 b.Errorf("Expected %v for %v, got %v", 118 val, idx, valGot) 119 break 120 } 121 } 122 } 123 } 124 125 db.Close() 126 }