package cache_test import ( "testing" "time" "github.com/stretchr/testify/assert" "code.bcarlin.net/go/cache" ) func TestCache(t *testing.T) { t.Parallel() const key = "test" t.Run("simple put and get", func(t *testing.T) { t.Parallel() c := cache.New[string, string]() value := "foo" c.Put(key, value) n := c.Count() assert.Equal(t, 1, n, "Expected %d entries in the cache, got %d", 1, n) got, ok := c.Get(key) assert.True(t, ok, "Expected cache to have an entry for key %q, but it did not", key) assert.Equal(t, value, got) }) t.Run("Using the same key overwrites the value", func(t *testing.T) { t.Parallel() c := cache.New[string, string]() c.Put(key, "foo") value := "bar" c.Put(key, value) n := c.Count() assert.Equal(t, 1, n, "Expected %d entries in the cache, got %d", 1, n) got, ok := c.Get(key) assert.True(t, ok, "Expected cache to have an entry for key %q, but it did not", key) assert.Equal(t, value, got) }) t.Run("cache is missed", func(t *testing.T) { t.Parallel() c := cache.New[string, string]() val, ok := c.Get("does-not-exist") assert.False(t, ok, "Expected cache to not have an entry for key 'does-not-exist', but it did") assert.Zero(t, val) }) } func TestCacheTTL(t *testing.T) { t.Parallel() const ( key = "test" value = "foo" ) t.Run("simple put and get a non-expired entry", func(t *testing.T) { t.Parallel() c := cache.New[string, string]() c.PutTTL(key, value, 1*time.Hour) n := c.Count() assert.Equal(t, 1, n, "Expected %d entries in the cache, got %d", 1, n) _, ok := c.Get(key) assert.True(t, ok, "Expected cache to have an entry for key %q, but it did not", key) }) t.Run("simple put and get a 0 TTL", func(t *testing.T) { t.Parallel() c := cache.New[string, string]() c.PutTTL(key, value, 0) n := c.Count() assert.Equal(t, 1, n, "Expected %d entries in the cache, got %d", 1, n) _, ok := c.Get(key) assert.True(t, ok, "Expected cache to have an entry for key %q, but it did not", key) }) t.Run("simple put and get an expired entry", func(t *testing.T) { t.Parallel() c := cache.New[string, string]() c.PutTTL(key, value, -1*time.Hour) n := c.Count() assert.Equal(t, 1, n, "Expected %d entries in the cache, got %d", 1, n) _, ok := c.Get(key) assert.False(t, ok, "Expected cache to not have an entry for key %q, but it did", key) n = c.Count() assert.Equal(t, 0, n, "Expected %d entries in the cache, got %d", 0, n) }) } func TestCacheDel(t *testing.T) { t.Parallel() const ( key = "test" value = "foo" ) t.Run("delete an existing key", func(t *testing.T) { t.Parallel() c := cache.New[string, string]() c.Put(key, value) n := c.Count() assert.Equal(t, 1, n, "Expected %d entries in the cache, got %d", 1, n) c.Del(key) n = c.Count() assert.Equal(t, 0, n, "Expected %d entries in the cache, got %d", 0, n) }) t.Run("delete a non-existing key", func(t *testing.T) { t.Parallel() c := cache.New[string, string]() c.Put(key, value) c.Del("does-not-exist") n := c.Count() assert.Equal(t, 1, n, "Expected %d entries in the cache, got %d", 1, n) }) }