-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweakcache_test.go
More file actions
83 lines (66 loc) · 1.53 KB
/
weakcache_test.go
File metadata and controls
83 lines (66 loc) · 1.53 KB
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
package weakcache
import (
"runtime"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestWeakCache(t *testing.T) {
w := NewWeakCache[int]()
r, err := w.Do("key1", func() (int, error) {
time.Sleep(time.Microsecond * 10)
return 9, nil
})
if err != nil {
t.Fatal("Got error")
}
var wg sync.WaitGroup
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
_, err := w.Do("key1", func() (int, error) {
return 10, nil
})
if err != nil {
t.Error("fail")
return
}
}()
}
wg.Wait()
if _, ok := w.c["key1"]; !ok {
t.Error("fail")
}
wcStats := w.Stats()
assert.Equal(t, int64(11), wcStats.NumCalls.Load())
assert.Equal(t, int64(10), wcStats.NumCacheHits.Load())
assert.Equal(t, int64(1), wcStats.NumCacheMisses.Load())
assert.Equal(t, int64(1), wcStats.SingleFlightStats.NumCalls.Load())
assert.Equal(t, int64(0), wcStats.SingleFlightStats.NumSuppressedCalls.Load())
runtime.GC()
wg.Add(10)
for i := 0; i < 10; i++ {
go func() {
defer wg.Done()
r1, err := w.Do("key1", func() (int, error) {
time.Sleep(time.Microsecond * 100)
return 10, nil
})
if err != nil {
t.Errorf("error: %v", err)
return
}
if r1 == r {
t.Errorf("fail mismatch %d != %d", r1, r)
}
}()
}
wg.Wait()
assert.Equal(t, int64(21), wcStats.NumCalls.Load())
sfCalls := wcStats.SingleFlightStats.NumCalls.Load()
cacheHit := 21 - sfCalls
assert.Equal(t, cacheHit, wcStats.NumCacheHits.Load())
assert.Equal(t, sfCalls, wcStats.NumCacheMisses.Load())
}