From 6a55a361a36d09cfeff0bb61edadd1c4cdc6a553 Mon Sep 17 00:00:00 2001 From: Marco Nenciarini Date: Mon, 1 Dec 2025 18:46:34 +0100 Subject: [PATCH] test: replace sleep-based test with deterministic channel verification The cleanup routine test used time.Sleep() without actually verifying the goroutine stopped. Added a done channel to provide deterministic verification of goroutine termination. Signed-off-by: Marco Nenciarini --- internal/cnpgi/instance/internal/client/client.go | 3 +++ .../cnpgi/instance/internal/client/client_test.go | 12 +++++++----- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/internal/cnpgi/instance/internal/client/client.go b/internal/cnpgi/instance/internal/client/client.go index c436c05..3b990d8 100644 --- a/internal/cnpgi/instance/internal/client/client.go +++ b/internal/cnpgi/instance/internal/client/client.go @@ -55,6 +55,7 @@ type ExtendedClient struct { cachedObjects []cachedEntry mux *sync.Mutex cleanupInterval time.Duration + cleanupDone chan struct{} // Signals when cleanup routine exits } // NewExtendedClient returns an extended client capable of caching secrets on the 'Get' operation. @@ -68,6 +69,7 @@ func NewExtendedClient( Client: baseClient, mux: &sync.Mutex{}, cleanupInterval: DefaultCleanupIntervalSeconds * time.Second, + cleanupDone: make(chan struct{}), } // Start the background cleanup routine @@ -225,6 +227,7 @@ func (e *ExtendedClient) Patch( // startCleanupRoutine periodically removes expired entries from the cache. // It runs until the context is cancelled. func (e *ExtendedClient) startCleanupRoutine(ctx context.Context) { + defer close(e.cleanupDone) contextLogger := log.FromContext(ctx).WithName("extended_client_cleanup") ticker := time.NewTicker(e.cleanupInterval) defer ticker.Stop() diff --git a/internal/cnpgi/instance/internal/client/client_test.go b/internal/cnpgi/instance/internal/client/client_test.go index dc1c746..fb57173 100644 --- a/internal/cnpgi/instance/internal/client/client_test.go +++ b/internal/cnpgi/instance/internal/client/client_test.go @@ -302,10 +302,12 @@ var _ = Describe("ExtendedClient Cache Cleanup", func() { // Cancel the context immediately cancel() - // Give the goroutine time to stop - time.Sleep(50 * time.Millisecond) - - // The goroutine should have stopped gracefully (no panic or hanging) - // This test mainly verifies the cleanup routine respects context cancellation + // Verify the cleanup routine actually stops by waiting for the done channel + select { + case <-ec.cleanupDone: + // Success: cleanup routine exited as expected + case <-time.After(1 * time.Second): + Fail("cleanup routine did not stop within timeout") + } }) })