2018-12-05 21:13:29 +08:00
|
|
|
package cache
|
|
|
|
|
|
|
|
import (
|
|
|
|
"runtime"
|
|
|
|
"testing"
|
|
|
|
"time"
|
2019-07-26 19:09:13 +08:00
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
2018-12-05 21:13:29 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestCache_Basic(t *testing.T) {
|
|
|
|
interval := 200 * time.Millisecond
|
|
|
|
ttl := 20 * time.Millisecond
|
2022-04-05 23:29:52 +08:00
|
|
|
c := New[string, int](interval)
|
2018-12-05 21:13:29 +08:00
|
|
|
c.Put("int", 1, ttl)
|
2022-04-05 23:29:52 +08:00
|
|
|
|
|
|
|
d := New[string, string](interval)
|
|
|
|
d.Put("string", "a", ttl)
|
2018-12-05 21:13:29 +08:00
|
|
|
|
|
|
|
i := c.Get("int")
|
2022-04-05 23:29:52 +08:00
|
|
|
assert.Equal(t, i, 1, "should recv 1")
|
2018-12-05 21:13:29 +08:00
|
|
|
|
2022-04-05 23:29:52 +08:00
|
|
|
s := d.Get("string")
|
|
|
|
assert.Equal(t, s, "a", "should recv 'a'")
|
2018-12-05 21:13:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestCache_TTL(t *testing.T) {
|
|
|
|
interval := 200 * time.Millisecond
|
|
|
|
ttl := 20 * time.Millisecond
|
2019-07-26 19:09:13 +08:00
|
|
|
now := time.Now()
|
2022-04-05 23:29:52 +08:00
|
|
|
c := New[string, int](interval)
|
2018-12-05 21:13:29 +08:00
|
|
|
c.Put("int", 1, ttl)
|
2019-07-26 19:09:13 +08:00
|
|
|
c.Put("int2", 2, ttl)
|
2018-12-05 21:13:29 +08:00
|
|
|
|
|
|
|
i := c.Get("int")
|
2019-07-26 19:09:13 +08:00
|
|
|
_, expired := c.GetWithExpire("int2")
|
2022-04-05 23:29:52 +08:00
|
|
|
assert.Equal(t, i, 1, "should recv 1")
|
2019-07-26 19:09:13 +08:00
|
|
|
assert.True(t, now.Before(expired))
|
2018-12-05 21:13:29 +08:00
|
|
|
|
|
|
|
time.Sleep(ttl * 2)
|
|
|
|
i = c.Get("int")
|
2019-07-26 19:09:13 +08:00
|
|
|
j, _ := c.GetWithExpire("int2")
|
2022-04-05 23:29:52 +08:00
|
|
|
assert.True(t, i == 0, "should recv 0")
|
|
|
|
assert.True(t, j == 0, "should recv 0")
|
2018-12-05 21:13:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestCache_AutoCleanup(t *testing.T) {
|
|
|
|
interval := 10 * time.Millisecond
|
|
|
|
ttl := 15 * time.Millisecond
|
2022-04-05 23:29:52 +08:00
|
|
|
c := New[string, int](interval)
|
2018-12-05 21:13:29 +08:00
|
|
|
c.Put("int", 1, ttl)
|
|
|
|
|
|
|
|
time.Sleep(ttl * 2)
|
|
|
|
i := c.Get("int")
|
2019-07-26 19:09:13 +08:00
|
|
|
j, _ := c.GetWithExpire("int")
|
2022-04-05 23:29:52 +08:00
|
|
|
assert.True(t, i == 0, "should recv 0")
|
|
|
|
assert.True(t, j == 0, "should recv 0")
|
2018-12-05 21:13:29 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func TestCache_AutoGC(t *testing.T) {
|
|
|
|
sign := make(chan struct{})
|
|
|
|
go func() {
|
|
|
|
interval := 10 * time.Millisecond
|
|
|
|
ttl := 15 * time.Millisecond
|
2022-04-05 23:29:52 +08:00
|
|
|
c := New[string, int](interval)
|
2018-12-05 21:13:29 +08:00
|
|
|
c.Put("int", 1, ttl)
|
|
|
|
sign <- struct{}{}
|
|
|
|
}()
|
|
|
|
|
|
|
|
<-sign
|
|
|
|
runtime.GC()
|
|
|
|
}
|