github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/ttlcache/item_test.go (about) 1 package ttlcache 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/stretchr/testify/assert" 8 "github.com/stretchr/testify/require" 9 ) 10 11 func Test_newItem(t *testing.T) { 12 item := newItem("key", 123, time.Hour) 13 require.NotNil(t, item) 14 assert.Equal(t, "key", item.key) 15 assert.Equal(t, 123, item.value) 16 assert.Equal(t, time.Hour, item.ttl) 17 assert.WithinDuration(t, time.Now().Add(time.Hour), item.expiresAt, time.Minute) 18 } 19 20 func Test_Item_update(t *testing.T) { 21 item := Item[string, string]{ 22 expiresAt: time.Now().Add(-time.Hour), 23 value: "hello", 24 } 25 26 item.update("test", time.Hour) 27 assert.Equal(t, "test", item.value) 28 assert.Equal(t, time.Hour, item.ttl) 29 assert.WithinDuration(t, time.Now().Add(time.Hour), item.expiresAt, time.Minute) 30 31 item.update("hi", NoTTL) 32 assert.Equal(t, "hi", item.value) 33 assert.Equal(t, NoTTL, item.ttl) 34 assert.Zero(t, item.expiresAt) 35 } 36 37 func Test_Item_touch(t *testing.T) { 38 var item Item[string, string] 39 item.touch() 40 assert.Zero(t, item.expiresAt) 41 42 item.ttl = time.Hour 43 item.touch() 44 assert.WithinDuration(t, time.Now().Add(time.Hour), item.expiresAt, time.Minute) 45 } 46 47 func Test_Item_IsExpired(t *testing.T) { 48 // no ttl 49 item := Item[string, string]{ 50 expiresAt: time.Now().Add(-time.Hour), 51 } 52 53 assert.False(t, item.IsExpired()) 54 55 // expired 56 item.ttl = time.Hour 57 assert.True(t, item.IsExpired()) 58 59 // not expired 60 item.expiresAt = time.Now().Add(time.Hour) 61 assert.False(t, item.IsExpired()) 62 } 63 64 func Test_Item_Key(t *testing.T) { 65 item := Item[string, string]{ 66 key: "test", 67 } 68 69 assert.Equal(t, "test", item.Key()) 70 } 71 72 func Test_Item_Value(t *testing.T) { 73 item := Item[string, string]{ 74 value: "test", 75 } 76 77 assert.Equal(t, "test", item.Value()) 78 } 79 80 func Test_Item_TTL(t *testing.T) { 81 item := Item[string, string]{ 82 ttl: time.Hour, 83 } 84 85 assert.Equal(t, time.Hour, item.TTL()) 86 } 87 88 func Test_Item_ExpiresAt(t *testing.T) { 89 now := time.Now() 90 item := Item[string, string]{ 91 expiresAt: now, 92 } 93 94 assert.Equal(t, now, item.ExpiresAt()) 95 }