dkforest

A forum and chat platform (onion)
git clone https://git.dasho.dev/n0tr1v/dkforest.git
Log | Files | Refs | LICENSE

cache_test.go (1736B)


      1 package cache
      2 
      3 import (
      4 	"testing"
      5 	"time"
      6 
      7 	"dkforest/pkg/clockwork"
      8 	"github.com/stretchr/testify/assert"
      9 )
     10 
     11 func TestNew(t *testing.T) {
     12 	c := New[int](time.Minute, time.Minute)
     13 	c.Set("key1", 1, DefaultExpiration)
     14 	v, found := c.Get("key1")
     15 	assert.True(t, found)
     16 	assert.Equal(t, v, 1)
     17 }
     18 
     19 func TestNewWithKey(t *testing.T) {
     20 	c := NewWithKey[int, int](time.Minute, time.Minute)
     21 	c.Set(1, 1, DefaultExpiration)
     22 	v, found := c.Get(1)
     23 	assert.True(t, found)
     24 	assert.Equal(t, v, 1)
     25 	v, found = c.Get(2)
     26 	assert.False(t, found)
     27 	assert.Equal(t, v, 0)
     28 }
     29 
     30 func TestItemIsExpired(t *testing.T) {
     31 	clock := clockwork.NewFakeClock()
     32 	i := Item[int]{value: 1, expiration: clock.Now().Add(time.Minute).UnixNano()}
     33 	assert.False(t, i.isExpired(clock.Now().UnixNano()))
     34 	clock.Advance(59 * time.Second)
     35 	assert.False(t, i.isExpired(clock.Now().UnixNano()))
     36 	clock.Advance(time.Second)
     37 	assert.False(t, i.isExpired(clock.Now().UnixNano()))
     38 	clock.Advance(time.Second)
     39 	assert.True(t, i.isExpired(clock.Now().UnixNano()))
     40 }
     41 
     42 func TestGetExpiredItem(t *testing.T) {
     43 	clock := clockwork.NewFakeClock()
     44 	c := New[string](time.Minute, time.Minute)
     45 	c.SetClock(clock)
     46 	c.Set("key1", "val1", DefaultExpiration)
     47 	_, found := c.Get("key1")
     48 	assert.True(t, found)
     49 	clock.Advance(61 * time.Second)
     50 	_, found = c.Get("key1")
     51 	assert.False(t, found)
     52 }
     53 
     54 type TestStruct struct {
     55 	Num      int
     56 	Children []*TestStruct
     57 }
     58 
     59 func TestStorePointerToStruct(t *testing.T) {
     60 	c := New[*TestStruct](time.Minute, time.Minute)
     61 	c.Set("key1", &TestStruct{Num: 1}, DefaultExpiration)
     62 	value1, found := c.Get("key1")
     63 	assert.True(t, found)
     64 	assert.Equal(t, 1, value1.Num)
     65 	value1.Num++
     66 	value2, found := c.Get("key1")
     67 	assert.True(t, found)
     68 	assert.Equal(t, 2, value2.Num)
     69 }