86 lines
2.2 KiB
Go
86 lines
2.2 KiB
Go
package ctxmgr_test
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"chat-agent-system/internal/ctxmgr"
|
|
)
|
|
|
|
func TestMultiLevelCache_BasicOpsAndStats(t *testing.T) {
|
|
cache := ctxmgr.NewMultiLevelCache()
|
|
cache.Clear()
|
|
|
|
key := ctxmgr.HashKey("test_user", "test_query")
|
|
|
|
// 1. 首次读取未命中
|
|
val, ok := cache.Get(ctxmgr.LayerC1Search, key)
|
|
if ok || val != nil {
|
|
t.Fatalf("expected cache miss, got %v", val)
|
|
}
|
|
|
|
// 2. 写入并读取命中
|
|
cache.Set(ctxmgr.LayerC1Search, key, "result_items", 45)
|
|
val, ok = cache.Get(ctxmgr.LayerC1Search, key)
|
|
if !ok || val.(string) != "result_items" {
|
|
t.Fatalf("expected cache hit with 'result_items', got %v", val)
|
|
}
|
|
|
|
// 3. 校验统计指标
|
|
stats := cache.Stats()
|
|
if stats.Hits != 1 || stats.Misses != 1 {
|
|
t.Errorf("unexpected stats: hits=%d, misses=%d", stats.Hits, stats.Misses)
|
|
}
|
|
if stats.SavedMs != 45 {
|
|
t.Errorf("expected savedMs=45, got %d", stats.SavedMs)
|
|
}
|
|
if stats.HitRate != 0.5 {
|
|
t.Errorf("expected hitRate=0.5, got %f", stats.HitRate)
|
|
}
|
|
|
|
// 4. 单条 Key 失效
|
|
cache.Invalidate(ctxmgr.LayerC1Search, key)
|
|
_, ok = cache.Get(ctxmgr.LayerC1Search, key)
|
|
if ok {
|
|
t.Errorf("expected cache miss after invalidation")
|
|
}
|
|
}
|
|
|
|
func TestMultiLevelCache_LayerInvalidation(t *testing.T) {
|
|
cache := ctxmgr.NewMultiLevelCache()
|
|
cache.Clear()
|
|
|
|
k1 := ctxmgr.HashKey("u1", "p1")
|
|
k2 := ctxmgr.HashKey("u2", "p2")
|
|
|
|
cache.Set(ctxmgr.LayerC4Context, k1, "ctx_1", 20)
|
|
cache.Set(ctxmgr.LayerC4Context, k2, "ctx_2", 20)
|
|
|
|
// 整体清空 C4 层
|
|
cache.InvalidateLayer(ctxmgr.LayerC4Context)
|
|
|
|
if _, ok := cache.Get(ctxmgr.LayerC4Context, k1); ok {
|
|
t.Errorf("expected k1 in C4 to be cleared")
|
|
}
|
|
if _, ok := cache.Get(ctxmgr.LayerC4Context, k2); ok {
|
|
t.Errorf("expected k2 in C4 to be cleared")
|
|
}
|
|
}
|
|
|
|
func TestMultiLevelCache_DisabledToggle(t *testing.T) {
|
|
cache := ctxmgr.NewMultiLevelCache()
|
|
cache.SetEnabled(false)
|
|
|
|
key := ctxmgr.HashKey("k_disabled")
|
|
cache.Set(ctxmgr.LayerC2Rewrite, key, "rewritten", 10)
|
|
|
|
if _, ok := cache.Get(ctxmgr.LayerC2Rewrite, key); ok {
|
|
t.Errorf("expected cache to be inactive when disabled")
|
|
}
|
|
|
|
cache.SetEnabled(true)
|
|
cache.Set(ctxmgr.LayerC2Rewrite, key, "rewritten", 10)
|
|
if _, ok := cache.Get(ctxmgr.LayerC2Rewrite, key); !ok {
|
|
t.Errorf("expected cache to be active when enabled")
|
|
}
|
|
}
|