65 lines
1.3 KiB
Go
65 lines
1.3 KiB
Go
package pokecache_test
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"testing"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"github.com/StevanFreeborn/pokedexcli/internal/pokecache"
|
||
|
|
)
|
||
|
|
|
||
|
|
func TestNewCache(t *testing.T) {
|
||
|
|
t.Run("it should return new initialized cache", func(t *testing.T) {
|
||
|
|
cache := pokecache.NewCache(5 * time.Second)
|
||
|
|
defer cache.Stop()
|
||
|
|
|
||
|
|
if cache == nil {
|
||
|
|
t.Errorf("expected result to be non nil value")
|
||
|
|
}
|
||
|
|
})
|
||
|
|
|
||
|
|
t.Run("it should start reaping loop", func(t *testing.T) {
|
||
|
|
interval := 1 * time.Second
|
||
|
|
wait := interval + 1
|
||
|
|
key := "key"
|
||
|
|
bytes := []byte("Hello World")
|
||
|
|
|
||
|
|
cache := pokecache.NewCache(1 * time.Second)
|
||
|
|
defer cache.Stop()
|
||
|
|
|
||
|
|
cache.Add(key, bytes)
|
||
|
|
|
||
|
|
time.Sleep(wait)
|
||
|
|
|
||
|
|
_, found := cache.Get(key)
|
||
|
|
|
||
|
|
if found {
|
||
|
|
t.Errorf("expected entry for key %s to have been reaped", key)
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
func TestAdd(t *testing.T) {
|
||
|
|
t.Run("it should add entry to cache and allow retrieving entry", func(t *testing.T) {
|
||
|
|
key := "key"
|
||
|
|
bytes := []byte("Hello World")
|
||
|
|
|
||
|
|
cache := pokecache.NewCache(5 * time.Second)
|
||
|
|
defer cache.Stop()
|
||
|
|
|
||
|
|
cache.Add(key, bytes)
|
||
|
|
|
||
|
|
result, found := cache.Get(key)
|
||
|
|
|
||
|
|
if !found {
|
||
|
|
t.Errorf("expected to find entry for key %s", key)
|
||
|
|
}
|
||
|
|
|
||
|
|
expected := string(bytes)
|
||
|
|
strResult := string(result)
|
||
|
|
|
||
|
|
if strResult != expected {
|
||
|
|
t.Errorf("expected to find value %s for key %s but received %s", expected, key, strResult)
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}
|