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") value, exists := store.Get("key1") if !exists || value != "value1" { t.Error("Expected value 'value1' for key 'key1'") } } func TestDelete(t *testing.T) { store := NewKVStore("test.db", mumlimit, bucketCount) store.Put("key1", "value1") store.Delete("key1") _, exists := store.Get("key1") if exists { t.Error("Expected key 'key1' to be deleted") } } func TestSaveAndLoadFromFile(t *testing.T) { store := NewKVStore("test.db", mumlimit, bucketCount) store.Put("key1", "value1") err := store.SaveToFile() if err != nil { t.Error("Failed to save store to file") } newStore := NewKVStore("test.db", mumlimit, bucketCount) err = newStore.LoadFromFile() if err != nil { t.Error("Failed to load store from file") } value, exists := newStore.Get("key1") if !exists || value != "value1" { t.Error("Expected value 'value1' for key 'key1' after loading from file") } // Clean up os.Remove("test.db") os.Remove("test.db.log") } 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 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", "value2") store.Rollback() _, exists = store.Get("key2") if exists { t.Error("Expected key 'key2' to be rolled back") } // 新增测试:验证事务中的PutInTransaction store.BeginTransaction() store.PutInTransaction("key3", "value3") value, exists = store.Get("key3") if !exists || value != "value3" { t.Error("Expected value 'value3' for key 'key3' during transaction") } store.Commit() value, exists = store.Get("key3") if !exists || value != "value3" { t.Error("Expected value 'value3' for key 'key3' after commit") } // Clean up os.Remove("test.db") os.Remove("test.db.log") }