@@ -3,6 +3,8 @@ package utils
33import (
44 "context"
55 "fmt"
6+ "math"
7+ rand2 "math/rand"
68 "strconv"
79 "sync"
810 "testing"
@@ -40,12 +42,45 @@ func noopSync(_ context.Context, obj CacheItem) (CacheItem, CacheSyncAction, err
4042 return obj , Unchanged , nil
4143}
4244
45+ func sometimesUpdateOnSync (percentage float32 ) CacheSyncItem {
46+ r := rand2 .New (rand2 .NewSource (time .Now ().Unix ()))
47+ p := int (percentage * 100 )
48+ return func (_ context.Context , obj CacheItem ) (CacheItem , CacheSyncAction , error ) {
49+ if r .Int ()% 100 < p {
50+ return obj , Update , nil
51+ }
52+
53+ return obj , Unchanged , nil
54+ }
55+ }
56+
57+ func TestSometimesUpdateOnSync (t * testing.T ) {
58+ for expected := 1.0 ; expected <= 10 ; expected ++ {
59+ perc := float32 (expected / 100.0 )
60+ f := sometimesUpdateOnSync (perc )
61+ updateCount := 0
62+ for i := 0 ; i < 10000 ; i ++ {
63+ for j := 0 ; j < 100 ; j ++ {
64+ _ , action , err := f (nil , nil )
65+ assert .NoError (t , err )
66+ if action == Update {
67+ updateCount ++
68+ }
69+ }
70+ }
71+
72+ actual := float64 (updateCount / 10000.0 )
73+ assert .True (t , expected <= math .Ceil (actual )+ 1 && expected >= math .Floor (actual )- 1 ,
74+ "Expected: %v, Actual: %v" , expected , actual )
75+ }
76+ }
77+
4378func BenchmarkCache (b * testing.B ) {
44- testResyncPeriod := time .Millisecond
79+ testResyncPeriod := time .Second
4580 rateLimiter := NewRateLimiter ("mockLimiter" , 100 , 1 )
4681 // the size of the cache is at least as large as the number of items we're storing
4782 itemCount := b .N
48- cache , err := NewAutoRefreshCache (noopSync , rateLimiter , testResyncPeriod , itemCount * 2 , nil )
83+ cache , err := NewAutoRefreshCache (sometimesUpdateOnSync ( 1 ) , rateLimiter , testResyncPeriod , itemCount * 2 , nil )
4984 assert .NoError (b , err )
5085
5186 ctx , cancel := context .WithCancel (context .Background ())
0 commit comments