package counter import ( "sync" "testing" ) func TestIncrConcurrent(t *testing.T) { var c Counter c.Init() var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) go func() { defer wg.Done() c.Incr("pv", 1) }() } wg.Wait() if got := c.Get("pv"); got != 100 { t.Errorf("并发 100 次 Incr 后 = %d, want 100", got) } } func TestSet(t *testing.T) { var c Counter c.Init() c.Set("k", 10) old := c.Set("k", 20) if old != 10 { t.Errorf("Set 返回旧值 = %d, want 10", old) } if got := c.Get("k"); got != 20 { t.Errorf("Set 后 Get = %d, want 20", got) } } func TestGetMissing(t *testing.T) { var c Counter c.Init() if got := c.Get("not-exist"); got != 0 { t.Errorf("不存在的 key Get = %d, want 0", got) } } func TestKeysIndependent(t *testing.T) { var c Counter c.Init() c.Incr("a", 1) c.Incr("b", 2) if c.Get("a") != 1 || c.Get("b") != 2 { t.Errorf("不同 key 应相互独立: a=%d b=%d", c.Get("a"), c.Get("b")) } }