cache/cache_test.go

157 lines
2.9 KiB
Go
Raw Normal View History

2021-11-19 13:21:46 +01:00
package cache
import (
"testing"
"time"
)
func TestCache(t *testing.T) {
key := "test"
c := New()
t.Log("simple put and get")
value := "foo"
c.Put(key, value)
if n := c.Count(); n != 1 {
t.Fatalf("Expected %d entries in the cache, got %d", 1, n)
}
val, ok := c.Get(key)
if !ok {
t.Fatalf("Expected cache to have an entry for key %q, but it did not", key)
}
val2, ok := val.(string)
if !ok {
t.Fatalf("Expected '%v' to have type string, but it has type %T", val, val)
}
if val2 != value {
t.Fatalf("Expected '%v' to equal 'foo', but it does not", val2)
}
t.Log("Using the same key overwrites the value")
value = "bar"
c.Put(key, value)
if n := c.Count(); n != 1 {
t.Fatalf("Expected %d entries in the cache, got %d", 1, n)
}
val, ok = c.Get(key)
if !ok {
t.Fatalf("Expected cache to have an entry for key %q, but it did not", key)
}
val2, ok = val.(string)
if !ok {
t.Fatalf("Expected '%v' to have type string, but it has type %T", val, val)
}
if val2 != value {
t.Fatalf("Expected '%v' to equal 'foo', but it does not", val2)
}
t.Log("It should tell if the cache is missed")
val, ok = c.Get("does-not-exist")
if ok {
t.Fatalf("Expected cache to not have an entry for key %q, but it did", key)
}
if val != nil {
t.Fatalf("Expected '%v' to be nil, but it was not", val2)
}
}
func TestCacheTTL(t *testing.T) {
key := "test"
value := "foo"
c := New()
t.Log("Simple put and get a non-expired entry")
c.PutTTL(key, value, 1*time.Hour)
if n := c.Count(); n != 1 {
t.Fatalf("Expected %d entries in the cache, got %d", 1, n)
}
_, ok := c.Get(key)
if !ok {
t.Fatalf("Expected cache to have an entry for key %q, but it did not", key)
}
t.Log("Simple put and get a 0 TTL")
c.PutTTL(key, value, 0)
if n := c.Count(); n != 1 {
t.Fatalf("Expected %d entries in the cache, got %d", 1, n)
}
_, ok = c.Get(key)
if !ok {
t.Fatalf("Expected cache to have an entry for key %q, but it did not", key)
}
t.Log("Simple put and get an expired entry")
c.PutTTL(key, value, -1*time.Hour)
if n := c.Count(); n != 1 {
t.Fatalf("Expected %d entries in the cache, got %d", 1, n)
}
_, ok = c.Get(key)
if ok {
t.Fatalf("Expected cache to not have an entry for key %q, but it did", key)
}
if n := c.Count(); n != 0 {
t.Fatalf("Expected %d entries in the cache, got %d", 0, n)
}
}
func TestCacheDel(t *testing.T) {
key := "test"
value := "foo"
c := New()
c.Put(key, value)
if n := c.Count(); n != 1 {
t.Fatalf("Expected %d entries in the cache, got %d", 1, n)
}
t.Log("Delete an existing key from the cache")
c.Del(key)
if n := c.Count(); n != 0 {
t.Fatalf("Expected %d entries in the cache, got %d", 0, n)
}
c.Put(key, value)
if n := c.Count(); n != 1 {
t.Fatalf("Expected %d entries in the cache, got %d", 1, n)
}
t.Log("Delete an existing key from the cache")
c.Del("does-not-exist")
if n := c.Count(); n != 1 {
t.Fatalf("Expected %d entries in the cache, got %d", 1, n)
}
}