UXInteract / task_014 /environment /code /lru_ttl_test.go
DojiSum's picture
Publish the current 141-task UXInteract release
ef987bb verified
Raw History Blame Contribute Delete
2.22 kB
package lru
import (
"testing"
"time"
)
type ttlTestClock struct{ now time.Time }
func (c *ttlTestClock) Now() time.Time { return c.now }
func (c *ttlTestClock) Advance(d time.Duration) { c.now = c.now.Add(d) }
func TestGetAndRenewTTLResetsExpiration(t *testing.T) {
clock := &ttlTestClock{now: time.Unix(1000, 0)}
cache := NewCacheWithClock(2, clock.Now)
cache.SetWithTTL("token", "abc", 120*time.Millisecond)
clock.Advance(70 * time.Millisecond)
value, ok := cache.GetAndRenewTTL("token")
if !ok || value != "abc" {
t.Fatalf("GetAndRenewTTL should return non-expired value, got %q ok=%v", value, ok)
}
clock.Advance(80 * time.Millisecond)
value, ok = cache.Get("token")
if !ok || value != "abc" {
t.Fatalf("TTL should have been renewed from original duration")
}
clock.Advance(60 * time.Millisecond)
if value, ok = cache.Get("token"); ok {
t.Fatalf("entry should expire after renewed TTL, got %q", value)
}
}
func TestExpiredEntryIsNotRenewed(t *testing.T) {
clock := &ttlTestClock{now: time.Unix(1000, 0)}
cache := NewCacheWithClock(2, clock.Now)
cache.SetWithTTL("short", "gone", 30*time.Millisecond)
clock.Advance(50 * time.Millisecond)
if value, ok := cache.GetAndRenewTTL("short"); ok {
t.Fatalf("expired entry should not be renewed, got %q", value)
}
}
func TestNormalGetDoesNotRenewTTL(t *testing.T) {
clock := &ttlTestClock{now: time.Unix(1000, 0)}
cache := NewCacheWithClock(2, clock.Now)
cache.SetWithTTL("plain", "value", 80*time.Millisecond)
clock.Advance(50 * time.Millisecond)
if value, ok := cache.Get("plain"); !ok || value != "value" {
t.Fatalf("normal Get should return before expiration")
}
clock.Advance(50 * time.Millisecond)
if value, ok := cache.Get("plain"); ok {
t.Fatalf("normal Get must not renew TTL, got %q", value)
}
}
func TestLRUEvictionStillWorks(t *testing.T) {
cache := NewCache(2)
cache.Set("a", "1")
cache.Set("b", "2")
if _, ok := cache.Get("a"); !ok {
t.Fatalf("expected a before eviction")
}
cache.Set("c", "3")
if _, ok := cache.Get("b"); ok {
t.Fatalf("least recently used key b should be evicted")
}
if value, ok := cache.Get("a"); !ok || value != "1" {
t.Fatalf("recently used key a should remain")
}
}