-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstats_test.go
More file actions
93 lines (81 loc) · 2.54 KB
/
stats_test.go
File metadata and controls
93 lines (81 loc) · 2.54 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
84
85
86
87
88
89
90
91
92
93
package loadingcache_test
import (
"context"
"testing"
"time"
"github.com/benbjohnson/clock"
"github.com/stretchr/testify/require"
"github.com/devzero-inc/loadingcache"
)
func TestStatsHitAndMiss(t *testing.T) {
type K int
type V string
matrixTest(t, matrixTestOptions[K, V]{}, func(t *testing.T, _ context.Context, cache loadingcache.Cache[K, V]) {
_, err := cache.Get(context.TODO(), 1)
require.Error(t, err)
require.Equal(t, int64(1), cache.Stats().MissCount())
cache.Put(1, "a")
_, err = cache.Get(context.TODO(), 1)
require.NoError(t, err)
require.Equal(t, int64(1), cache.Stats().HitCount())
require.Equal(t, float64(0.5), cache.Stats().HitRate())
require.Equal(t, float64(0.5), cache.Stats().MissRate())
require.Equal(t, int64(2), cache.Stats().RequestCount())
})
}
func TestLoadTimes(t *testing.T) {
type K int
type V int
mockClock := clock.NewMock()
loadTime := 100 * time.Millisecond
matrixTest(t, matrixTestOptions[K, V]{
cacheOptions: []loadingcache.CacheOption[K, V]{
loadingcache.WithClock[K, V](mockClock),
loadingcache.WithLoadFunc(func(_ context.Context, key K) (V, error) {
// Simulating that the loading takes 100ms
mockClock.Add(loadTime)
return V(key), nil
}),
},
},
func(t *testing.T, ctx context.Context, cache loadingcache.Cache[K, V]) {
for i := 1; i <= 10; i++ {
_, err := cache.Get(context.TODO(), K(i))
require.NoError(t, err)
require.Equal(t, time.Duration(i)*loadTime, cache.Stats().LoadTotalTime())
}
// Since there were no misses, the average load time should match the individual load time
require.Equal(t, loadTime, cache.Stats().AverageLoadPenalty())
})
}
func TestLoadSuccessAndError(t *testing.T) {
type K int
type V string
loadFunc := &testLoadFunc[K, V]{}
matrixTest(t, matrixTestOptions[K, V]{
cacheOptions: []loadingcache.CacheOption[K, V]{
loadingcache.WithLoadFunc(loadFunc.LoadFunc),
},
},
func(t *testing.T, _ context.Context, cache loadingcache.Cache[K, V]) {
// Clean up after ourselves
defer func() {
loadFunc.fail = false
}()
// Doing 10 successful loads
i := 0
for ; i < 10; i++ {
_, err := cache.Get(context.TODO(), K(i))
require.NoError(t, err)
}
// Doing 6 error loads
loadFunc.fail = true
for ; i < 16; i++ {
_, err := cache.Get(context.TODO(), K(i))
require.Error(t, err)
}
require.Equal(t, int64(10), cache.Stats().LoadSuccessCount())
require.Equal(t, int64(6), cache.Stats().LoadErrorCount())
require.Equal(t, float64(0.375), cache.Stats().LoadErrorRate())
})
}