From 977d899afd47d18837e437e8bbbd994fff06d27a Mon Sep 17 00:00:00 2001 From: Jakub Hadvig Date: Tue, 26 May 2026 16:22:27 +0200 Subject: [PATCH] OCPBUGS-86511: Fix flaky TestAsyncCache backend test Replace timing-dependent sleep loop with require.Eventually and re-grab the reference item after Run() fires its immediate reload. Co-Authored-By: Claude Opus 4.6 (1M context) --- .../asynccache/asyncccache_test.go | 43 ++++++++----------- 1 file changed, 17 insertions(+), 26 deletions(-) diff --git a/pkg/serverutils/asynccache/asyncccache_test.go b/pkg/serverutils/asynccache/asyncccache_test.go index cca45c80f13..a6e0c8cae67 100644 --- a/pkg/serverutils/asynccache/asyncccache_test.go +++ b/pkg/serverutils/asynccache/asyncccache_test.go @@ -28,49 +28,40 @@ func TestAsyncCache(t *testing.T) { return &testItem{ctx: ctx, t: time.Now()}, nil } + initializationRetryInterval = 5 * time.Millisecond + initializationTimeout = 10 * time.Millisecond + 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") - } + require.False(t, item.t.IsZero(), "expected non-zero time") time.Sleep(1 * time.Second) - if item.isContextCancelled() { - t.Error("expected usable context") - } + require.False(t, item.isContextCancelled(), "expected usable context") - timedCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + timedCtx, cancel := context.WithTimeout(context.Background(), 10*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 - } + // wait.UntilWithContext fires runCache immediately — let it settle + time.Sleep(100 * time.Millisecond) + item = c.GetItem() - time.Sleep(1 * time.Second) - } + // Cache should return the same item between reloads + require.Equal(t, item, c.GetItem(), "expected same item before next reload") + + // Cache should eventually return a different item after a reload cycle + require.Eventually(t, func() bool { + return c.GetItem() != item + }, 5*time.Second, 200*time.Millisecond, "expected cache to refresh") - require.Greater(t, matches, 0) - require.True(t, changed) cancel() - // test that the cache returns error properly + // Initialization returns error when caching func fails errorCaching := func(ctx context.Context) (bool, error) { return false, fmt.Errorf("test error") } - _, err = NewAsyncCache(context.Background(), 2*time.Second, errorCaching) require.Error(t, err) }