Skip to content

Commit 0ee8ea9

Browse files
committed
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
1 parent 56e0d59 commit 0ee8ea9

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

logger.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,9 @@ type podEventLogger struct {
116116

117117
logCh chan<- agentLog
118118
lq *logQueuer
119+
120+
// hasSyncedFuncs tracks informer cache sync functions for testing
121+
hasSyncedFuncs []cache.InformerSynced
119122
}
120123

121124
// resolveEnvValue resolves the value of an environment variable, supporting both
@@ -368,9 +371,23 @@ func (p *podEventLogger) initNamespace(namespace string) error {
368371
if podFactory != eventFactory {
369372
eventFactory.Start(p.stopChan)
370373
}
374+
375+
// Track HasSynced functions for WaitForCacheSync
376+
p.hasSyncedFuncs = append(p.hasSyncedFuncs,
377+
podInformer.HasSynced,
378+
replicaInformer.HasSynced,
379+
eventInformer.HasSynced,
380+
)
381+
371382
return nil
372383
}
373384

385+
// WaitForCacheSync waits for all informer caches to sync.
386+
// This is useful for testing to ensure informers are ready before creating resources.
387+
func (p *podEventLogger) WaitForCacheSync(ctx context.Context) bool {
388+
return cache.WaitForCacheSync(ctx.Done(), p.hasSyncedFuncs...)
389+
}
390+
374391
var sourceUUID = uuid.MustParse("cabdacf8-7c90-425c-9815-cae3c75d1169")
375392

376393
// loggerForToken returns a logger for the given pod name and agent token.

logger_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,9 @@ func Test_newPodEventLogger_multipleNamespaces(t *testing.T) {
466466
})
467467
require.NoError(t, err)
468468

469+
// Wait for informer caches to sync before creating pods
470+
require.True(t, reporter.WaitForCacheSync(ctx), "informer caches failed to sync")
471+
469472
// Create a pod in the test-namespace1 namespace
470473
pod1 := &corev1.Pod{
471474
ObjectMeta: v1.ObjectMeta{

0 commit comments

Comments
 (0)