package cache import ( "context" "testing" "time" ) func TestMemCache_SetGetRoundTrip(t *testing.T) { c := NewMemory() ctx := context.Background() in := []map[string]any{{"id": "1", "name": "测试"}} c.SetJSON(ctx, "k", in, time.Minute) var out []map[string]any if !c.GetJSON(ctx, "k", &out) { t.Fatal("应命中") } if len(out) != 1 || out[0]["name"] != "测试" { t.Fatalf("JSON 往返不一致: %v", out) } } func TestMemCache_MissOnAbsent(t *testing.T) { var out []map[string]any if NewMemory().GetJSON(context.Background(), "none", &out) { t.Fatal("不存在的键应未命中") } } func TestMemCache_Expiry(t *testing.T) { c := NewMemory() ctx := context.Background() c.SetJSON(ctx, "k", map[string]any{"a": 1}, 10*time.Millisecond) time.Sleep(25 * time.Millisecond) var out map[string]any if c.GetJSON(ctx, "k", &out) { t.Fatal("过期键应未命中") } } func TestMemCache_Delete(t *testing.T) { c := NewMemory() ctx := context.Background() c.SetJSON(ctx, "k", map[string]any{"a": 1}, time.Minute) c.Delete(ctx, "k") var out map[string]any if c.GetJSON(ctx, "k", &out) { t.Fatal("删除后应未命中") } } // nil 客户端的 Redis 实现应安全降级,不 panic、不命中。 func TestRedisCache_NilClientGraceful(t *testing.T) { c := NewRedis(nil) ctx := context.Background() c.SetJSON(ctx, "k", map[string]any{"a": 1}, time.Minute) // 不应 panic c.Delete(ctx, "k") // 不应 panic var out map[string]any if c.GetJSON(ctx, "k", &out) { t.Fatal("nil 客户端应始终未命中") } }