From 0bf16f704d699b9b257c37760e756ea88753fc5e Mon Sep 17 00:00:00 2001 From: Haytham AbuelFutuh Date: Fri, 12 Jul 2019 13:41:04 -0700 Subject: [PATCH] WIP --- utils/auto_refresh_cache_test.go | 39 ++++++++++++++++++++++++++++++-- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/utils/auto_refresh_cache_test.go b/utils/auto_refresh_cache_test.go index 53b5167..598774f 100644 --- a/utils/auto_refresh_cache_test.go +++ b/utils/auto_refresh_cache_test.go @@ -3,6 +3,8 @@ package utils import ( "context" "fmt" + "math" + rand2 "math/rand" "strconv" "sync" "testing" @@ -40,12 +42,45 @@ func noopSync(_ context.Context, obj CacheItem) (CacheItem, CacheSyncAction, err return obj, Unchanged, nil } +func sometimesUpdateOnSync(percentage float32) CacheSyncItem { + r := rand2.New(rand2.NewSource(time.Now().Unix())) + p := int(percentage * 100) + return func(_ context.Context, obj CacheItem) (CacheItem, CacheSyncAction, error) { + if r.Int()%100 < p { + return obj, Update, nil + } + + return obj, Unchanged, nil + } +} + +func TestSometimesUpdateOnSync(t *testing.T) { + for expected := 1.0; expected <= 10; expected++ { + perc := float32(expected / 100.0) + f := sometimesUpdateOnSync(perc) + updateCount := 0 + for i := 0; i < 10000; i++ { + for j := 0; j < 100; j++ { + _, action, err := f(nil, nil) + assert.NoError(t, err) + if action == Update { + updateCount++ + } + } + } + + actual := float64(updateCount / 10000.0) + assert.True(t, expected <= math.Ceil(actual)+1 && expected >= math.Floor(actual)-1, + "Expected: %v, Actual: %v", expected, actual) + } +} + func BenchmarkCache(b *testing.B) { - testResyncPeriod := time.Millisecond + testResyncPeriod := time.Second rateLimiter := NewRateLimiter("mockLimiter", 100, 1) // the size of the cache is at least as large as the number of items we're storing itemCount := b.N - cache, err := NewAutoRefreshCache(noopSync, rateLimiter, testResyncPeriod, itemCount*2, nil) + cache, err := NewAutoRefreshCache(sometimesUpdateOnSync(1), rateLimiter, testResyncPeriod, itemCount*2, nil) assert.NoError(b, err) ctx, cancel := context.WithCancel(context.Background())