From 0ee8ea97ae613a10b0b26fbbf095be496c35fe0f Mon Sep 17 00:00:00 2001 From: Kacper Sawicki Date: Mon, 2 Feb 2026 10:58:36 +0000 Subject: [PATCH] fix: use WaitForCacheSync instead of time.Sleep in flaky test The Test_newPodEventLogger_multipleNamespaces test was flaky because informers might not have started watching before pods were created. - Add hasSyncedFuncs field to podEventLogger to track informer sync functions - Add WaitForCacheSync() method using cache.WaitForCacheSync - Replace time.Sleep with WaitForCacheSync in the test --- logger.go | 17 +++++++++++++++++ logger_test.go | 3 +++ 2 files changed, 20 insertions(+) diff --git a/logger.go b/logger.go index 6d9dec9..0f53ebc 100644 --- a/logger.go +++ b/logger.go @@ -116,6 +116,9 @@ type podEventLogger struct { logCh chan<- agentLog lq *logQueuer + + // hasSyncedFuncs tracks informer cache sync functions for testing + hasSyncedFuncs []cache.InformerSynced } // resolveEnvValue resolves the value of an environment variable, supporting both @@ -368,9 +371,23 @@ func (p *podEventLogger) initNamespace(namespace string) error { if podFactory != eventFactory { eventFactory.Start(p.stopChan) } + + // Track HasSynced functions for WaitForCacheSync + p.hasSyncedFuncs = append(p.hasSyncedFuncs, + podInformer.HasSynced, + replicaInformer.HasSynced, + eventInformer.HasSynced, + ) + return nil } +// WaitForCacheSync waits for all informer caches to sync. +// This is useful for testing to ensure informers are ready before creating resources. +func (p *podEventLogger) WaitForCacheSync(ctx context.Context) bool { + return cache.WaitForCacheSync(ctx.Done(), p.hasSyncedFuncs...) +} + var sourceUUID = uuid.MustParse("cabdacf8-7c90-425c-9815-cae3c75d1169") // loggerForToken returns a logger for the given pod name and agent token. diff --git a/logger_test.go b/logger_test.go index 416b2a8..ac26049 100644 --- a/logger_test.go +++ b/logger_test.go @@ -466,6 +466,9 @@ func Test_newPodEventLogger_multipleNamespaces(t *testing.T) { }) require.NoError(t, err) + // Wait for informer caches to sync before creating pods + require.True(t, reporter.WaitForCacheSync(ctx), "informer caches failed to sync") + // Create a pod in the test-namespace1 namespace pod1 := &corev1.Pod{ ObjectMeta: v1.ObjectMeta{