all repos

mugit @ a02c4e8

🐮 git server that your cow will love

mugit/internal/cache/in_memory_test.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
test: add missing tests (#5)..., 2 months ago
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
20
	t.Run("overwrites prev value", func(t *testing.T) {
21
		c.Set("asdf", "one")
22
		c.Set("asdf", "two")
23
		is.Equal(t, c.data["asdf"].v, "two")
24
	})
25
}
26
27
func TestInMemory_Get(t *testing.T) {
28
	c := NewInMemory[string](time.Minute)
29
30
	t.Run("hit", func(t *testing.T) {
31
		c.Set("asdf", "qwer")
32
		v, found := c.Get("asdf")
33
		is.Equal(t, true, found)
34
		is.Equal(t, "qwer", v)
35
	})
36
37
	t.Run("miss", func(t *testing.T) {
38
		_, found := c.Get("missing")
39
		is.Equal(t, false, found)
40
	})
41
42
	t.Run("expired item", func(t *testing.T) {
43
		synctest.Test(t, func(t *testing.T) {
44
			c.Set("asdf", "qwer")
45
			time.Sleep(2 * time.Minute)
46
			v, found := c.Get("asdf")
47
			is.Equal(t, false, found)
48
			is.Equal(t, "", v)
49
		})
50
	})
51
}
52
53
func TestInMemory_ZeroTTL(t *testing.T) {
54
	c := NewInMemory[string](0)
55
	c.Set("key", "val")
56
57
	_, found := c.Get("key")
58
	is.Equal(t, false, found)
59
}
60
61
func TestInMemory_StructType(t *testing.T) {
62
	type testItem struct{ v string }
63
64
	c := NewInMemory[testItem](time.Minute)
65
	expected := testItem{v: "repo"}
66
	c.Set("k", expected)
67
68
	v, found := c.Get("k")
69
	is.Equal(t, expected, v)
70
	is.Equal(t, true, found)
71
}
72
73
func TestInMemory_EmptyKey(t *testing.T) {
74
	c := NewInMemory[string](time.Minute)
75
	c.Set("", "empty-key-val")
76
77
	v, found := c.Get("")
78
	is.Equal(t, "empty-key-val", v)
79
	is.Equal(t, true, found)
80
}
81
82
func TestInMemory_ConcurrentSetGet(t *testing.T) {
83
	c := NewInMemory[int](time.Minute)
84
	synctest.Test(t, func(t *testing.T) {
85
		var wg sync.WaitGroup
86
		for i := range 50 {
87
			key := fmt.Sprintf("key-%d", i)
88
			wg.Go(func() { c.Set(key, i) })
89
			wg.Go(func() { c.Get(key) })
90
		}
91
		wg.Wait()
92
	})
93
}