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 <marco.nenciarini@enterprisedb.com>
This commit is contained in:
Marco Nenciarini 2025-12-01 18:46:34 +01:00
parent 62b579101f
commit 6a55a361a3
2 changed files with 10 additions and 5 deletions

View File

@ -55,6 +55,7 @@ type ExtendedClient struct {
cachedObjects []cachedEntry cachedObjects []cachedEntry
mux *sync.Mutex mux *sync.Mutex
cleanupInterval time.Duration cleanupInterval time.Duration
cleanupDone chan struct{} // Signals when cleanup routine exits
} }
// NewExtendedClient returns an extended client capable of caching secrets on the 'Get' operation. // NewExtendedClient returns an extended client capable of caching secrets on the 'Get' operation.
@ -68,6 +69,7 @@ func NewExtendedClient(
Client: baseClient, Client: baseClient,
mux: &sync.Mutex{}, mux: &sync.Mutex{},
cleanupInterval: DefaultCleanupIntervalSeconds * time.Second, cleanupInterval: DefaultCleanupIntervalSeconds * time.Second,
cleanupDone: make(chan struct{}),
} }
// Start the background cleanup routine // Start the background cleanup routine
@ -225,6 +227,7 @@ func (e *ExtendedClient) Patch(
// startCleanupRoutine periodically removes expired entries from the cache. // startCleanupRoutine periodically removes expired entries from the cache.
// It runs until the context is cancelled. // It runs until the context is cancelled.
func (e *ExtendedClient) startCleanupRoutine(ctx context.Context) { func (e *ExtendedClient) startCleanupRoutine(ctx context.Context) {
defer close(e.cleanupDone)
contextLogger := log.FromContext(ctx).WithName("extended_client_cleanup") contextLogger := log.FromContext(ctx).WithName("extended_client_cleanup")
ticker := time.NewTicker(e.cleanupInterval) ticker := time.NewTicker(e.cleanupInterval)
defer ticker.Stop() defer ticker.Stop()

View File

@ -302,10 +302,12 @@ var _ = Describe("ExtendedClient Cache Cleanup", func() {
// Cancel the context immediately // Cancel the context immediately
cancel() cancel()
// Give the goroutine time to stop // Verify the cleanup routine actually stops by waiting for the done channel
time.Sleep(50 * time.Millisecond) select {
case <-ec.cleanupDone:
// The goroutine should have stopped gracefully (no panic or hanging) // Success: cleanup routine exited as expected
// This test mainly verifies the cleanup routine respects context cancellation case <-time.After(1 * time.Second):
Fail("cleanup routine did not stop within timeout")
}
}) })
}) })