driftctl/pkg/remote/cache/cache_test.go

73 lines
1.8 KiB
Go
Raw Normal View History

package cache
import (
"fmt"
"testing"
2021-06-03 10:39:33 +00:00
"github.com/cloudskiff/driftctl/test/resource"
"github.com/stretchr/testify/assert"
)
func BenchmarkCache(b *testing.B) {
2021-06-03 10:39:33 +00:00
cache := New(500)
for i := 0; i < b.N; i++ {
key := fmt.Sprintf("test-key-%d", i)
2021-06-03 10:39:33 +00:00
data := make([]*resource.FakeResource, 1024)
2021-05-25 10:36:48 +00:00
assert.Equal(b, false, cache.Put(key, data))
assert.Equal(b, data, cache.Get(key))
}
}
func TestCache(t *testing.T) {
t.Run("should return nil on non-existing key", func(t *testing.T) {
2021-05-25 10:36:48 +00:00
cache := New(5)
assert.Equal(t, nil, cache.Get("test"))
2021-05-25 10:36:48 +00:00
assert.Equal(t, 0, cache.Len())
})
t.Run("should retrieve newly added key", func(t *testing.T) {
2021-05-25 10:36:48 +00:00
cache := New(5)
assert.Equal(t, false, cache.Put("s3", []string{}))
assert.Equal(t, []string{}, cache.Get("s3"))
2021-05-25 10:36:48 +00:00
assert.Equal(t, 1, cache.Len())
})
t.Run("should override existing key", func(t *testing.T) {
2021-05-25 10:36:48 +00:00
cache := New(5)
assert.Equal(t, false, cache.Put("s3", []string{}))
assert.Equal(t, []string{}, cache.Get("s3"))
2021-05-25 10:36:48 +00:00
assert.Equal(t, true, cache.Put("s3", []string{"test"}))
assert.Equal(t, []string{"test"}, cache.Get("s3"))
2021-05-25 10:36:48 +00:00
assert.Equal(t, 1, cache.Len())
})
t.Run("should delete the least used keys", func(t *testing.T) {
2021-05-28 09:26:02 +00:00
keys := []struct {
key string
value interface{}
}{
{key: "test-0", value: nil},
{key: "test-1", value: nil},
{key: "test-2", value: nil},
{key: "test-3", value: nil},
{key: "test-4", value: nil},
{key: "test-5", value: nil},
{key: "test-6", value: "value"},
{key: "test-7", value: "value"},
{key: "test-8", value: "value"},
{key: "test-9", value: "value"},
{key: "test-10", value: "value"},
}
2021-05-25 10:36:48 +00:00
2021-05-28 09:26:02 +00:00
cache := New(5)
2021-05-25 10:36:48 +00:00
for i := 0; i <= 10; i++ {
cache.Put(fmt.Sprintf("test-%d", i), "value")
}
2021-05-28 09:26:02 +00:00
for _, k := range keys {
assert.Equal(t, k.value, cache.Get(k.key))
}
2021-05-25 10:36:48 +00:00
assert.Equal(t, 5, cache.Len())
})
}