Debian Codegraph @

cache_test.go

raw symbols SCIP
1 package cache_test
2
3 import (
4 "math/rand"
5 "sync"
6 "testing"
7 "time"
8
9 cache "github.com/Code-Hex/go-generics-cache"
10 "github.com/Code-Hex/go-generics-cache/policy/clock"
11 "github.com/Code-Hex/go-generics-cache/policy/fifo"
12 "github.com/Code-Hex/go-generics-cache/policy/lfu"
13 "github.com/Code-Hex/go-generics-cache/policy/lru"
14 "github.com/Code-Hex/go-generics-cache/policy/mru"
15 )
16
17 func TestMultiThreadIncr(t *testing.T) {
18 nc := cache.NewNumber[string, int]()
19 nc.Set("counter", 0)
20
21 var wg sync.WaitGroup
22
23 for i := 0; i < 100; i++ {
24 wg.Add(1)
25 go func() {
26 _ = nc.Increment("counter", 1)
27 wg.Done()
28 }()
29 }
30
31 wg.Wait()
32
33 if counter, _ := nc.Get("counter"); counter != 100 {
34 t.Errorf("want %v but got %v", 100, counter)
35 }
36 }
37
38 func TestMultiThreadDecr(t *testing.T) {
39 nc := cache.NewNumber[string, int]()
40 nc.Set("counter", 100)
41
42 var wg sync.WaitGroup
43
44 for i := 0; i < 100; i++ {
45 wg.Add(1)
46 go func() {
47 _ = nc.Decrement("counter", 1)
48 wg.Done()
49 }()
50 }
51
52 wg.Wait()
53
54 if counter, _ := nc.Get("counter"); counter != 0 {
55 t.Errorf("want %v but got %v", 0, counter)
56 }
57 }
58
59 func TestMultiThread(t *testing.T) {
60 cases := []struct {
61 name string
62 policy cache.Option[int, int]
63 }{
64 {
65 name: "LRU",
66 policy: cache.AsLRU[int, int](lru.WithCapacity(10)),
67 },
68 {
69 name: "MRU",
70 policy: cache.AsMRU[int, int](mru.WithCapacity(10)),
71 },
72 {
73 name: "FIFO",
74 policy: cache.AsFIFO[int, int](fifo.WithCapacity(10)),
75 },
76 {
77 name: "Clock",
78 policy: cache.AsClock[int, int](clock.WithCapacity(10)),
79 },
80 {
81 name: "LFU",
82 policy: cache.AsLFU[int, int](lfu.WithCapacity(10)),
83 },
84 }
85 for _, tc := range cases {
86 tc := tc
87 t.Run(tc.name, func(t *testing.T) {
88 c := cache.New(tc.policy)
89 var wg sync.WaitGroup
90 for i := int64(0); i < 100; i++ {
91 wg.Add(1)
92 go func(i int64) {
93 defer wg.Done()
94 m := rand.New(rand.NewSource(i))
95 for n := 0; n < 100; n++ {
96 key := m.Intn(100000)
97 c.Set(key, m.Intn(100000))
98 c.Get(key)
99 }
100 }(i)
101 }
102
103 wg.Wait()
104 })
105 }
106 }
107
108 func TestCallJanitor(t *testing.T) {
109 c := cache.New(
110 cache.WithJanitorInterval[string, int](100 * time.Millisecond),
111 )
112
113 c.Set("1", 10, cache.WithExpiration(10*time.Millisecond))
114 c.Set("2", 20, cache.WithExpiration(20*time.Millisecond))
115 c.Set("3", 30, cache.WithExpiration(30*time.Millisecond))
116
117 <-time.After(300 * time.Millisecond)
118
119 keys := c.Keys()
120 if len(keys) != 0 {
121 t.Errorf("want items is empty but got %d", len(keys))
122 }
123 }