124 lines
2.4 KiB
Go
124 lines
2.4 KiB
Go
package memcache_test
|
|
|
|
import (
|
|
"math/rand"
|
|
"sandc/pkg/cache/memcache"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"sandc/pkg/cache/memcache/policy/clock"
|
|
"sandc/pkg/cache/memcache/policy/fifo"
|
|
"sandc/pkg/cache/memcache/policy/lfu"
|
|
"sandc/pkg/cache/memcache/policy/lru"
|
|
"sandc/pkg/cache/memcache/policy/mru"
|
|
)
|
|
|
|
func TestMultiThreadIncr(t *testing.T) {
|
|
nc := memcache.NewNumber[string, int]()
|
|
nc.Set("counter", 0)
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
for i := 0; i < 100; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
_ = nc.Increment("counter", 1)
|
|
wg.Done()
|
|
}()
|
|
}
|
|
|
|
wg.Wait()
|
|
|
|
if counter, _ := nc.Get("counter"); counter != 100 {
|
|
t.Errorf("want %v but got %v", 100, counter)
|
|
}
|
|
}
|
|
|
|
func TestMultiThreadDecr(t *testing.T) {
|
|
nc := memcache.NewNumber[string, int]()
|
|
nc.Set("counter", 100)
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
for i := 0; i < 100; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
_ = nc.Decrement("counter", 1)
|
|
wg.Done()
|
|
}()
|
|
}
|
|
|
|
wg.Wait()
|
|
|
|
if counter, _ := nc.Get("counter"); counter != 0 {
|
|
t.Errorf("want %v but got %v", 0, counter)
|
|
}
|
|
}
|
|
|
|
func TestMultiThread(t *testing.T) {
|
|
cases := []struct {
|
|
name string
|
|
policy memcache.Option[int, int]
|
|
}{
|
|
{
|
|
name: "LRU",
|
|
policy: memcache.AsLRU[int, int](lru.WithCapacity(10)),
|
|
},
|
|
{
|
|
name: "MRU",
|
|
policy: memcache.AsMRU[int, int](mru.WithCapacity(10)),
|
|
},
|
|
{
|
|
name: "FIFO",
|
|
policy: memcache.AsFIFO[int, int](fifo.WithCapacity(10)),
|
|
},
|
|
{
|
|
name: "Clock",
|
|
policy: memcache.AsClock[int, int](clock.WithCapacity(10)),
|
|
},
|
|
{
|
|
name: "LFU",
|
|
policy: memcache.AsLFU[int, int](lfu.WithCapacity(10)),
|
|
},
|
|
}
|
|
for _, tc := range cases {
|
|
tc := tc
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
c := memcache.New(tc.policy)
|
|
var wg sync.WaitGroup
|
|
for i := int64(0); i < 100; i++ {
|
|
wg.Add(1)
|
|
go func(i int64) {
|
|
defer wg.Done()
|
|
m := rand.New(rand.NewSource(i))
|
|
for n := 0; n < 100; n++ {
|
|
key := m.Intn(100000)
|
|
c.Set(key, m.Intn(100000))
|
|
c.Get(key)
|
|
}
|
|
}(i)
|
|
}
|
|
|
|
wg.Wait()
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestCallJanitor(t *testing.T) {
|
|
c := memcache.New(
|
|
memcache.WithJanitorInterval[string, int](100 * time.Millisecond),
|
|
)
|
|
|
|
c.Set("1", 10, memcache.WithExpiration(10*time.Millisecond))
|
|
c.Set("2", 20, memcache.WithExpiration(20*time.Millisecond))
|
|
c.Set("3", 30, memcache.WithExpiration(30*time.Millisecond))
|
|
|
|
<-time.After(300 * time.Millisecond)
|
|
|
|
keys := c.Keys()
|
|
if len(keys) != 0 {
|
|
t.Errorf("want items is empty but got %d", len(keys))
|
|
}
|
|
}
|