Skip to content
This repository has been archived by the owner on Oct 9, 2023. It is now read-only.

Commit

Permalink
WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
EngHabu committed Jul 12, 2019
1 parent 67ca254 commit 0bf16f7
Showing 1 changed file with 37 additions and 2 deletions.
39 changes: 37 additions & 2 deletions utils/auto_refresh_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package utils
import (
"context"
"fmt"
"math"
rand2 "math/rand"
"strconv"
"sync"
"testing"
Expand Down Expand Up @@ -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())
Expand Down

0 comments on commit 0bf16f7

Please sign in to comment.