mugit/internal/cache/in_memory_test.go (view raw)
| 1 | package cache |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "sync" |
| 6 | "testing" |
| 7 | "testing/synctest" |
| 8 | "time" |
| 9 | |
| 10 | "olexsmir.xyz/x/is" |
| 11 | ) |
| 12 | |
| 13 | func TestInMemory_Set(t *testing.T) { |
| 14 | c := NewInMemory[string](time.Minute) |
| 15 | t.Run("sets", func(t *testing.T) { |
| 16 | c.Set("asdf", "qwer") |
| 17 | is.Equal(t, c.data["asdf"].v, "qwer") |
| 18 | }) |
| 19 | t.Run("overwrites prev value", func(t *testing.T) { |
| 20 | c.Set("asdf", "one") |
| 21 | c.Set("asdf", "two") |
| 22 | is.Equal(t, c.data["asdf"].v, "two") |
| 23 | }) |
| 24 | } |
| 25 | |
| 26 | func TestInMemory_Get(t *testing.T) { |
| 27 | c := NewInMemory[string](time.Minute) |
| 28 | |
| 29 | t.Run("hit", func(t *testing.T) { |
| 30 | c.Set("asdf", "qwer") |
| 31 | v, found := c.Get("asdf") |
| 32 | is.Equal(t, true, found) |
| 33 | is.Equal(t, "qwer", v) |
| 34 | }) |
| 35 | t.Run("miss", func(t *testing.T) { |
| 36 | _, found := c.Get("missing") |
| 37 | is.Equal(t, false, found) |
| 38 | }) |
| 39 | t.Run("expired item", func(t *testing.T) { |
| 40 | synctest.Test(t, func(t *testing.T) { |
| 41 | c.Set("asdf", "qwer") |
| 42 | time.Sleep(2 * time.Minute) |
| 43 | v, found := c.Get("asdf") |
| 44 | is.Equal(t, false, found) |
| 45 | is.Equal(t, "", v) |
| 46 | }) |
| 47 | }) |
| 48 | } |
| 49 | |
| 50 | func TestInMemory_ConcurrentSetGet(t *testing.T) { |
| 51 | c := NewInMemory[int](time.Minute) |
| 52 | synctest.Test(t, func(t *testing.T) { |
| 53 | var wg sync.WaitGroup |
| 54 | for i := range 50 { |
| 55 | key := fmt.Sprintf("key-%d", i) |
| 56 | wg.Go(func() { c.Set(key, i) }) |
| 57 | wg.Go(func() { c.Get(key) }) |
| 58 | } |
| 59 | wg.Wait() |
| 60 | }) |
| 61 | } |