99 lines
1.6 KiB
Go
99 lines
1.6 KiB
Go
package kvmemcache
|
|
|
|
import (
|
|
"fmt"
|
|
"math/rand"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func testRunner(c *Cache, t *testing.T, done chan bool) {
|
|
rand.Seed(time.Now().UnixNano())
|
|
for i := 0; i < 200001; i++ {
|
|
x := rand.Int31n(50)
|
|
if rand.Float64() < 0.01 {
|
|
x = rand.Int31n(9999)
|
|
}
|
|
|
|
key := fmt.Sprintf("key-%v", x)
|
|
expectedVal := "value for " + key
|
|
|
|
val, err := c.Get(key)
|
|
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
if val.(string) != expectedVal {
|
|
t.Fatal(val)
|
|
}
|
|
}
|
|
done <- true
|
|
}
|
|
|
|
func testCache(name string, c *Cache, t *testing.T) {
|
|
N := 8
|
|
done := make(chan bool, N)
|
|
|
|
for i := 0; i < N; i++ {
|
|
go testRunner(c, t, done)
|
|
}
|
|
|
|
for i := 0; i < N; i++ {
|
|
<-done
|
|
}
|
|
|
|
stats := c.Stats()
|
|
|
|
fmt.Println(name)
|
|
fmt.Printf(" Hits: %d\n", stats.Hits)
|
|
fmt.Printf(" Misses: %d\n", stats.Misses)
|
|
fmt.Printf(" Expired: %d\n", stats.Expired)
|
|
fmt.Printf(" Hit-rate: %.2f%%\n",
|
|
100*float64(stats.Hits)/float64(stats.Hits+stats.Misses))
|
|
}
|
|
|
|
func TestCache(t *testing.T) {
|
|
c := New(Config{
|
|
MaxSize: 2048,
|
|
TTL: 100 * time.Millisecond,
|
|
Src: func(key string) (interface{}, error) {
|
|
return fmt.Sprintf("value for %s", key), nil
|
|
},
|
|
})
|
|
testCache("LRUTimeout", c, t)
|
|
}
|
|
|
|
func TestCacheTTL(t *testing.T) {
|
|
c := New(Config{
|
|
MaxSize: 2048,
|
|
TTL: 100 * time.Millisecond,
|
|
Src: func(key string) (interface{}, error) {
|
|
return key, nil
|
|
},
|
|
})
|
|
|
|
c.Get("a")
|
|
c.Get("b")
|
|
time.Sleep(50 * time.Millisecond)
|
|
c.Get("a")
|
|
c.Get("b")
|
|
c.Get("c")
|
|
|
|
stats := c.Stats()
|
|
if stats.Expired != 0 {
|
|
t.Fatal(stats.Expired)
|
|
}
|
|
|
|
time.Sleep(50 * time.Millisecond)
|
|
c.Get("a")
|
|
c.Get("b")
|
|
c.Get("c")
|
|
|
|
stats = c.Stats()
|
|
if stats.Expired != 2 {
|
|
t.Fatal(stats.Expired)
|
|
}
|
|
|
|
}
|