Skip to content

Commit df32ec1

Browse files
committed
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 <[email protected]>
1 parent 1a4b70a commit df32ec1

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

internal/cnpgi/instance/internal/client/client.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ type ExtendedClient struct {
5555
cachedObjects []cachedEntry
5656
mux *sync.Mutex
5757
cleanupInterval time.Duration
58+
cleanupDone chan struct{} // Signals when cleanup routine exits
5859
}
5960

6061
// NewExtendedClient returns an extended client capable of caching secrets on the 'Get' operation.
@@ -68,6 +69,7 @@ func NewExtendedClient(
6869
Client: baseClient,
6970
mux: &sync.Mutex{},
7071
cleanupInterval: DefaultCleanupIntervalSeconds * time.Second,
72+
cleanupDone: make(chan struct{}),
7173
}
7274

7375
// Start the background cleanup routine
@@ -225,6 +227,7 @@ func (e *ExtendedClient) Patch(
225227
// startCleanupRoutine periodically removes expired entries from the cache.
226228
// It runs until the context is cancelled.
227229
func (e *ExtendedClient) startCleanupRoutine(ctx context.Context) {
230+
defer close(e.cleanupDone)
228231
contextLogger := log.FromContext(ctx).WithName("extended_client_cleanup")
229232
ticker := time.NewTicker(e.cleanupInterval)
230233
defer ticker.Stop()

internal/cnpgi/instance/internal/client/client_test.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -302,10 +302,12 @@ var _ = Describe("ExtendedClient Cache Cleanup", func() {
302302
// Cancel the context immediately
303303
cancel()
304304

305-
// Give the goroutine time to stop
306-
time.Sleep(50 * time.Millisecond)
307-
308-
// The goroutine should have stopped gracefully (no panic or hanging)
309-
// This test mainly verifies the cleanup routine respects context cancellation
305+
// Verify the cleanup routine actually stops by waiting for the done channel
306+
select {
307+
case <-ec.cleanupDone:
308+
// Success: cleanup routine exited as expected
309+
case <-time.After(1 * time.Second):
310+
Fail("cleanup routine did not stop within timeout")
311+
}
310312
})
311313
})

0 commit comments

Comments
 (0)