File size: 2,224 Bytes
ef987bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | 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")
}
}
|