kefu/tools/go_cache_test.go

61 lines
1.4 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package tools
import (
"testing"
"time"
"github.com/patrickmn/go-cache"
)
func TestGoCache(t *testing.T) {
// 创建一个具有默认过期时间为5分钟和清理间隔为10分钟的缓存
c := cache.New(5*time.Minute, 10*time.Minute)
// 使用默认过期时间将键 "foo" 的值设置为 "bar"
c.Set("foo", "bar", cache.DefaultExpiration)
// 获取键 "foo" 的值
value, found := c.Get("foo")
if !found {
t.Error("缓存中未找到键 'foo'")
}
if value != "bar" {
t.Errorf("预期为 'bar',得到 '%s'", value)
}
// 删除键 "foo"
c.Delete("foo")
// 检查键 "foo" 是否已删除
_, found = c.Get("foo")
if found {
t.Error("键 'foo' 应该被删除")
}
}
// TestGoCacheWithExpiration 测试设置过期时间为3600秒的数据
func TestGoCacheWithExpiration(t *testing.T) {
// 创建一个具有默认过期时间为5分钟和清理间隔为10分钟的缓存
c := cache.New(5*time.Minute, 10*time.Minute)
// 将键 "foo" 的值设置为 "bar"过期时间为10秒
c.Set("foo", "bar", time.Duration(10)*time.Second)
// 获取键 "foo" 的值
value, found := c.Get("foo")
if !found {
t.Error("缓存中未找到键 'foo'")
}
if value != "bar" {
t.Errorf("预期为 'bar',得到 '%s'", value)
}
// 等待10秒后键 "foo" 应该过期
time.Sleep(10 * time.Second)
// 检查键 "foo" 是否已过期
_, found = c.Get("foo")
if found {
t.Error("键 'foo' 应该已过期")
}
}