107 lines
2.3 KiB
Go
107 lines
2.3 KiB
Go
package gocache
|
||
|
||
import (
|
||
"os"
|
||
"testing"
|
||
)
|
||
|
||
func TestNewKVStore(t *testing.T) {
|
||
store := NewKVStore("test.db")
|
||
if store == nil {
|
||
t.Error("Expected a new KVStore instance, got nil")
|
||
}
|
||
}
|
||
|
||
func TestPutAndGet(t *testing.T) {
|
||
store := NewKVStore("test.db")
|
||
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")
|
||
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")
|
||
store.Put("key1", "value1")
|
||
err := store.SaveToFile()
|
||
if err != nil {
|
||
t.Error("Failed to save store to file")
|
||
}
|
||
|
||
newStore := NewKVStore("test.db")
|
||
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")
|
||
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")
|
||
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")
|
||
}
|