1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- package cache
- import (
- "context"
- "testing"
- "time"
- )
- func TestMemorySetGetDelete(t *testing.T) {
- // 创建一个新的 memory Cache 实例
- memCache := NewMemory()
- // 设置一个键值对
- key := "testKey"
- val := "testValue"
- ttl := 1 * time.Minute
- _, err := memCache.Set(context.Background(), key, val, ttl)
- if err != nil {
- t.Errorf("Failed to set key-value pair: %v", err)
- }
- // 获取键对应的值
- result, err := memCache.Get(context.Background(), key)
- if err != nil {
- t.Errorf("Failed to get value for key: %v", err)
- }
- if result != val {
- t.Errorf("Expected value %s, but got %s", val, result)
- }
- // 删除键值对
- _, err = memCache.Delete(context.Background(), key)
- if err != nil {
- t.Errorf("Failed to delete key-value pair: %v", err)
- }
- // 再次尝试获取键对应的值,应该返回 ErrorCacheNotFound 错误
- _, err = memCache.Get(context.Background(), key)
- if err != ErrorCacheNotFound {
- t.Errorf("Expected error ErrorCacheNotFound, but got %v", err)
- }
- }
- func BenchmarkMemorySet(b *testing.B) {
- memCache := NewMemory()
- key := "testKey"
- val := "testValue"
- ttl := 1 * time.Minute
- for i := 0; i < b.N; i++ {
- _, _ = memCache.Set(context.Background(), key, val, ttl)
- }
- }
- func BenchmarkMemoryGet(b *testing.B) {
- memCache := NewMemory()
- key := "testKey"
- val := "testValue"
- ttl := 1 * time.Minute
- _, _ = memCache.Set(context.Background(), key, val, ttl)
- for i := 0; i < b.N; i++ {
- _, _ = memCache.Get(context.Background(), key)
- }
- }
- func BenchmarkMemoryDelete(b *testing.B) {
- memCache := NewMemory()
- key := "testKey"
- val := "testValue"
- ttl := 1 * time.Minute
- _, _ = memCache.Set(context.Background(), key, val, ttl)
- for i := 0; i < b.N; i++ {
- _, _ = memCache.Delete(context.Background(), key)
- }
- }
|