Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 30 additions & 25 deletions pkg/serverutils/asynccache/asyncccache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,46 +24,51 @@ func (i *testItem) isContextCancelled() bool {
}

func TestAsyncCache(t *testing.T) {
// Override initialization settings before any NewAsyncCache call
// so they take effect for the error case test.
origRetryInterval := initializationRetryInterval
origTimeout := initializationTimeout
initializationRetryInterval = 5 * time.Millisecond
initializationTimeout = 10 * time.Millisecond
t.Cleanup(func() {
initializationRetryInterval = origRetryInterval
initializationTimeout = origTimeout
})

cacheTime := func(ctx context.Context) (*testItem, error) {
return &testItem{ctx: ctx, t: time.Now()}, nil
}

c, err := NewAsyncCache(context.Background(), 2*time.Second, cacheTime)
require.NoError(t, err)

initializationRetryInterval = 5 * time.Millisecond
initializationTimeout = 10 * time.Millisecond
// test that initialization was successful
item := c.GetItem()
if item.t.IsZero() {
t.Error("expected non-zero time")
}

time.Sleep(1 * time.Second)
if item.isContextCancelled() {
t.Error("expected usable context")
}
require.False(t, item.t.IsZero(), "expected non-zero time")
require.False(t, item.isContextCancelled(), "expected usable context")

timedCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
c.Run(timedCtx)

// test the values get properly changed
var matches int
var changed bool
for i := 0; i < 3; i++ {
newItem := c.GetItem()
if newItem == item {
matches++
} else {
changed = true
}

time.Sleep(1 * time.Second)
}
// wait.UntilWithContext fires runCache immediately; wait for the
// first refresh before capturing the baseline.
require.Eventually(t, func() bool {
return c.GetItem() != item
}, 5*time.Second, 10*time.Millisecond, "expected item to be refreshed after Run()")

// Re-grab the reference after the immediate reload
item = c.GetItem()

// Within the 2s refresh interval the cached item should stay the same
time.Sleep(500 * time.Millisecond)
require.Equal(t, item, c.GetItem(), "item should not change within refresh interval")

// After the refresh interval the item should be replaced
require.Eventually(t, func() bool {
return c.GetItem() != item
}, 5*time.Second, 100*time.Millisecond, "item should change after refresh interval")

require.Greater(t, matches, 0)
require.True(t, changed)
cancel()

// test that the cache returns error properly
Expand Down