80 lines
1.6 KiB
Go
80 lines
1.6 KiB
Go
package track1
|
|
|
|
import (
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
func TestInMemoryCache_GetSet(t *testing.T) {
|
|
cache := NewInMemoryCache()
|
|
|
|
key := "test-key"
|
|
value := []byte("test-value")
|
|
ttl := 5 * time.Minute
|
|
|
|
// Test Set
|
|
err := cache.Set(key, value, ttl)
|
|
require.NoError(t, err)
|
|
|
|
// Test Get
|
|
retrieved, err := cache.Get(key)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, value, retrieved)
|
|
}
|
|
|
|
func TestInMemoryCache_Expiration(t *testing.T) {
|
|
cache := NewInMemoryCache()
|
|
|
|
key := "test-key"
|
|
value := []byte("test-value")
|
|
ttl := 100 * time.Millisecond
|
|
|
|
err := cache.Set(key, value, ttl)
|
|
require.NoError(t, err)
|
|
|
|
// Should be available immediately
|
|
retrieved, err := cache.Get(key)
|
|
require.NoError(t, err)
|
|
assert.Equal(t, value, retrieved)
|
|
|
|
// Wait for expiration
|
|
time.Sleep(150 * time.Millisecond)
|
|
|
|
// Should be expired
|
|
_, err = cache.Get(key)
|
|
assert.Error(t, err)
|
|
assert.Equal(t, ErrCacheMiss, err)
|
|
}
|
|
|
|
func TestInMemoryCache_Miss(t *testing.T) {
|
|
cache := NewInMemoryCache()
|
|
|
|
_, err := cache.Get("non-existent-key")
|
|
assert.Error(t, err)
|
|
assert.Equal(t, ErrCacheMiss, err)
|
|
}
|
|
|
|
func TestInMemoryCache_Cleanup(t *testing.T) {
|
|
cache := NewInMemoryCache()
|
|
|
|
// Set multiple keys with short TTL
|
|
for i := 0; i < 10; i++ {
|
|
key := "test-key-" + string(rune(i))
|
|
cache.Set(key, []byte("value"), 50*time.Millisecond)
|
|
}
|
|
|
|
// Wait for expiration
|
|
time.Sleep(200 * time.Millisecond)
|
|
|
|
// All should be expired after cleanup
|
|
for i := 0; i < 10; i++ {
|
|
key := "test-key-" + string(rune(i))
|
|
_, err := cache.Get(key)
|
|
assert.Error(t, err)
|
|
}
|
|
}
|
|
|