-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmemoize_with_cache_test.go
97 lines (72 loc) · 1.38 KB
/
memoize_with_cache_test.go
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package memoize
import (
"sync"
"testing"
"github.com/emad-elsaid/memoize/cache"
)
func TestMemoizerWithCache(t *testing.T) {
counters := map[string]int{}
var l sync.Mutex
inc := func(k string) int {
l.Lock()
defer l.Unlock()
counters[k]++
return counters[k]
}
mem := NewWithCache(cache.New[string, int](), inc)
concurrency := 100
var wg sync.WaitGroup
wg.Add(concurrency)
routine := func() {
r := mem("key1")
assertEqual(t, 1, r)
r = mem("key2")
assertEqual(t, 1, r)
r = mem("key3")
assertEqual(t, 1, r)
wg.Done()
}
for range concurrency {
go routine()
}
wg.Wait()
expected := map[string]int{
"key1": 1,
"key2": 1,
"key3": 1,
}
assertEqualMaps(t, expected, counters)
}
func TestMemoizerWithCacheErr(t *testing.T) {
counters := map[string]int{}
var l sync.Mutex
inc := func(k string) (int, error) {
l.Lock()
defer l.Unlock()
counters[k]++
return counters[k], nil
}
mem := NewWithCacheErr(cache.New[string, Pair[int]](), inc)
concurrency := 100
var wg sync.WaitGroup
wg.Add(concurrency)
routine := func() {
r, _ := mem("key1")
assertEqual(t, 1, r)
r, _ = mem("key2")
assertEqual(t, 1, r)
r, _ = mem("key3")
assertEqual(t, 1, r)
wg.Done()
}
for range concurrency {
go routine()
}
wg.Wait()
expected := map[string]int{
"key1": 1,
"key2": 1,
"key3": 1,
}
assertEqualMaps(t, expected, counters)
}