Merge pull request #137255 from pohly/ktesting-contexthelper-test-fix

Ktesting: contexthelper panic + test fix
This commit is contained in:
Kubernetes Prow Robot
2026-02-26 14:04:26 +05:30
committed by GitHub
2 changed files with 10 additions and 0 deletions

View File

@@ -48,11 +48,17 @@ func withTimeout(ctx context.Context, tb TB, timeout time.Duration, timeoutCause
cancelCtx, cancel := context.WithCancelCause(ctx)
after := time.NewTimer(timeout)
stopCtx, stop := context.WithCancel(ctx) // Only used internally, doesn't need a cause.
done := make(chan struct{})
tb.Cleanup(func() {
cancel(cleanupErr(tb.Name()))
stop()
// Wait for goroutine termination. This is important because
// otherwise the goroutine might log through tb *after* the
// test has already finished, which causes a panic.
<-done
})
go func() {
defer close(done)
select {
case <-stopCtx.Done():
after.Stop()

View File

@@ -119,7 +119,11 @@ func TestCause(t *testing.T) {
assert.Equal(t, tt.expectDeadline, time.Until(actualDeadline), "remaining time till Deadline()")
}
}
// Unblock background goroutines.
time.Sleep(tt.sleep)
// Wait for them to do their work.
synctest.Wait()
// Now check.
actualErr := ctx.Err()
actualCause := context.Cause(ctx)
assert.Equal(t, tt.expectErr, actualErr, "ctx.Err()")