mugit/internal/cache/in_memory_test.go(view raw)
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 |
package cache
import (
"fmt"
"sync"
"testing"
"testing/synctest"
"time"
"olexsmir.xyz/x/is"
)
func TestInMemory_Set(t *testing.T) {
c := NewInMemory[string](time.Minute)
t.Run("sets", func(t *testing.T) {
c.Set("asdf", "qwer")
is.Equal(t, c.data["asdf"].v, "qwer")
})
t.Run("overwrites prev value", func(t *testing.T) {
c.Set("asdf", "one")
c.Set("asdf", "two")
is.Equal(t, c.data["asdf"].v, "two")
})
}
func TestInMemory_Get(t *testing.T) {
c := NewInMemory[string](time.Minute)
t.Run("hit", func(t *testing.T) {
c.Set("asdf", "qwer")
v, found := c.Get("asdf")
is.Equal(t, true, found)
is.Equal(t, "qwer", v)
})
t.Run("miss", func(t *testing.T) {
_, found := c.Get("missing")
is.Equal(t, false, found)
})
t.Run("expired item", func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
c.Set("asdf", "qwer")
time.Sleep(2 * time.Minute)
v, found := c.Get("asdf")
is.Equal(t, false, found)
is.Equal(t, "", v)
})
})
}
func TestInMemory_ConcurrentSetGet(t *testing.T) {
c := NewInMemory[int](time.Minute)
synctest.Test(t, func(t *testing.T) {
var wg sync.WaitGroup
for i := range 50 {
key := fmt.Sprintf("key-%d", i)
wg.Go(func() { c.Set(key, i) })
wg.Go(func() { c.Get(key) })
}
wg.Wait()
})
}
|