package cache import ( "fmt" "hash/fnv" "testing" ) var c *Cache type cacheableT struct { Name string } func (ct *cacheableT) Hash() uint64 { s := fnv.New64() s.Sum([]byte(ct.Name)) return s.Sum64() } var ( key = cacheableT{"foo"} value = "bar" ) func TestNewCache(t *testing.T) { c = NewCache() if c == nil { t.Fatal("Expecting a new cache object.") } } func TestCacheReadNonExistentValue(t *testing.T) { if _, ok := c.Read(&key); ok { t.Fatal("Expecting false.") } } func TestCacheWritingValue(t *testing.T) { c.Write(&key, value) c.Write(&key, value) } func TestCacheReadExistentValue(t *testing.T) { s, ok := c.Read(&key) if !ok { t.Fatal("Expecting true.") } if s != value { t.Fatal("Expecting value.") } } func BenchmarkNewCache(b *testing.B) { for i := 0; i < b.N; i++ { NewCache() } } func BenchmarkNewCacheAndClear(b *testing.B) { for i := 0; i < b.N; i++ { c := NewCache() c.Clear() } } func BenchmarkReadNonExistentValue(b *testing.B) { z := NewCache() for i := 0; i < b.N; i++ { z.Read(&key) } } func BenchmarkWriteSameValue(b *testing.B) { z := NewCache() for i := 0; i < b.N; i++ { z.Write(&key, value) } } func BenchmarkWriteNewValue(b *testing.B) { z := NewCache() for i := 0; i < b.N; i++ { key := cacheableT{fmt.Sprintf("item-%d", i)} z.Write(&key, value) } } func BenchmarkReadExistentValue(b *testing.B) { z := NewCache() z.Write(&key, value) for i := 0; i < b.N; i++ { z.Read(&key) } }