github.com/turingchain2020/turingchain@v1.1.21/common/db/localdb_test.go (about) 1 package db 2 3 import ( 4 "testing" 5 6 "github.com/turingchain2020/turingchain/types" 7 "github.com/stretchr/testify/assert" 8 ) 9 10 //localdb 不会往 maindb 写数据,他都是临时的数据,在内存中临时计算的一个数据库 11 func TestLocalDB(t *testing.T) { 12 db1 := newGoMemDB(t) 13 db := NewLocalDB(db1, false) 14 15 db1.Set([]byte("key1"), []byte("value1")) 16 v1, err := db.Get([]byte("key1")) 17 assert.Nil(t, err) 18 assert.Equal(t, v1, []byte("value1")) 19 20 db.Set([]byte("key2"), []byte("value2")) 21 data, err := db.List([]byte("key"), nil, 2, 1) 22 assert.Nil(t, err) 23 assert.Equal(t, data[0], []byte("value1")) 24 assert.Equal(t, data[1], []byte("value2")) 25 26 //test commit 27 db.Begin() 28 db.Set([]byte("key3"), []byte("value3")) 29 data, err = db.List([]byte("key"), nil, 0, 1) 30 assert.Nil(t, err) 31 assert.Equal(t, data[0], []byte("value1")) 32 assert.Equal(t, data[1], []byte("value2")) 33 assert.Equal(t, data[2], []byte("value3")) 34 db.Commit() 35 data, err = db.List([]byte("key"), nil, 0, 1) 36 assert.Nil(t, err) 37 assert.Equal(t, data[0], []byte("value1")) 38 assert.Equal(t, data[1], []byte("value2")) 39 assert.Equal(t, data[2], []byte("value3")) 40 41 //test rollback 42 db.Begin() 43 db.Set([]byte("key4"), []byte("value4")) 44 data, err = db.List([]byte("key"), nil, 0, 0) 45 assert.Nil(t, err) 46 assert.Equal(t, data[0], []byte("value4")) 47 assert.Equal(t, data[1], []byte("value3")) 48 assert.Equal(t, data[2], []byte("value2")) 49 assert.Equal(t, data[3], []byte("value1")) 50 db.Rollback() 51 data, err = db.List([]byte("key"), nil, 0, 0) 52 assert.Nil(t, err) 53 assert.Equal(t, 3, len(data)) 54 assert.Equal(t, data[0], []byte("value3")) 55 assert.Equal(t, data[1], []byte("value2")) 56 assert.Equal(t, data[2], []byte("value1")) 57 58 //test delete 59 db1.Set([]byte("keyd1"), []byte("valued1")) 60 err = db.Set([]byte("keyd1"), nil) 61 assert.Nil(t, err) 62 value, err := db.Get([]byte("keyd1")) 63 assert.True(t, isdeleted(value)) 64 assert.True(t, isdeleted(nil)) 65 assert.Equal(t, types.ErrNotFound, err) 66 67 //test list 68 data, err = db.List([]byte("key"), nil, 0, 0) 69 assert.Nil(t, err) 70 assert.Equal(t, 3, len(data)) 71 assert.Equal(t, data[0], []byte("value3")) 72 assert.Equal(t, data[1], []byte("value2")) 73 assert.Equal(t, data[2], []byte("value1")) 74 }