gocache/kvstore_test.go

133 lines
3.1 KiB
Go

package gocache
import (
"os"
"testing"
)
var mumlimit int64 = 1024 * 1024 * 1024
var bucketCount = 16
func TestNewKVStore(t *testing.T) {
store := NewKVStore("test.db", mumlimit, bucketCount)
if store == nil {
t.Error("Expected a new KVStore instance, got nil")
}
}
func TestPutAndGet(t *testing.T) {
store := NewKVStore("test.db", mumlimit, bucketCount)
// 测试字符串类型
store.Put("key1", "value1")
store.wg.Wait() // 等待异步操作完成
value, exists := store.Get("key1")
if !exists || value != "value1" {
t.Error("Expected value 'value1' for key 'key1'")
}
// 测试整数类型
store.Put("key2", 123)
store.wg.Wait() // 等待异步操作完成
value, exists = store.Get("key2")
if !exists || value != 123 {
t.Error("Expected value 123 for key 'key2'")
}
// 测试布尔类型
store.Put("key3", true)
store.wg.Wait() // 等待异步操作完成
value, exists = store.Get("key3")
if !exists || value != true {
t.Error("Expected value true for key 'key3'")
}
// 测试数组类型
store.Put("key4", []string{"a", "b", "c"})
store.wg.Wait() // 等待异步操作完成
value, exists = store.Get("key4")
if !exists {
t.Error("Expected value for key 'key4'")
}
}
func TestDelete(t *testing.T) {
store := NewKVStore("test.db", mumlimit, bucketCount)
store.Put("key1", "value1")
store.wg.Wait() // 等待异步操作完成
store.Delete("key1")
store.wg.Wait() // 等待异步操作完成
_, exists := store.Get("key1")
if exists {
t.Error("Expected key 'key1' to be deleted")
}
}
func TestLogOperation(t *testing.T) {
store := NewKVStore("test.db", mumlimit, bucketCount)
err := store.LogOperation("put", "key1", "value1")
if err != nil {
t.Error("Failed to log operation")
}
// Clean up
os.Remove("test.db.log")
}
func createDB() {
store := NewKVStore("test.db", mumlimit, bucketCount)
store.Put("key1", "value1")
store.Put("key2", 123)
store.Put("key3", true)
store.Put("key4", []string{"a", "b", "c"})
store.wg.Wait()
}
func TestRecoverFromLog(t *testing.T) {
createDB()
store2 := NewKVStore("test.db", mumlimit, bucketCount)
// store2.RecoverFromLog()
value, exists := store2.Get("key1")
if !exists || value != "value1" {
t.Error("Expected value 'value1' for key 'key1' after recovery")
}
}
func TestTransaction(t *testing.T) {
store := NewKVStore("test.db", mumlimit, bucketCount)
// 测试字符串类型
store.BeginTransaction()
store.PutInTransaction("key1", "value1")
store.Commit()
value, exists := store.Get("key1")
if !exists || value != "value1" {
t.Error("Expected value 'value1' for key 'key1' after commit")
}
// 测试整数类型
store.BeginTransaction()
store.PutInTransaction("key2", 123)
store.Commit()
value, exists = store.Get("key2")
if !exists || value != 123 {
t.Error("Expected value 123 for key 'key2' after commit")
}
// 测试回滚
store.BeginTransaction()
store.PutInTransaction("key3", "value3")
store.Rollback()
_, exists = store.Get("key3")
if exists {
t.Error("Expected key 'key3' to be rolled back")
}
// Clean up
os.Remove("test.db")
os.Remove("test.db.log")
}