ktesting: fix per-test logging in TContext.Run and WithTB

WithTB was originally defined as "uses the existing logger". But what we want
there and in the newer TContext.Run is the usual per-test logging, now for the
sub-test.
This commit is contained in:
Patrick Ohly 2025-03-07 15:13:14 +01:00
parent 939c9c0c6b
commit 6478ca5859

View File

@ -259,6 +259,28 @@ func Init(tb TB, opts ...InitOption) TContext {
ctx := interruptCtx
if c.PerTestOutput {
logger := newLogger(tb, c.BufferLogs)
ctx = klog.NewContext(interruptCtx, logger)
tb = withKlogHeader(tb)
}
if deadlineOK {
if deadline, ok := deadlineTB.Deadline(); ok {
timeLeft := time.Until(deadline)
timeLeft -= CleanupGracePeriod
ctx, cancel := withTimeout(ctx, tb, timeLeft, fmt.Sprintf("test suite deadline (%s) is close, need to clean up before the %s cleanup grace period", deadline.Truncate(time.Second), CleanupGracePeriod))
tCtx := tContext{
Context: ctx,
testingTB: testingTB{TB: tb},
cancel: cancel,
}
return tCtx
}
}
return WithCancel(InitCtx(ctx, tb))
}
func newLogger(tb TB, bufferLogs bool) klog.Logger {
config := ktesting.NewConfig(
ktesting.AnyToString(func(v interface{}) string {
// For basic types where the string
@ -277,7 +299,7 @@ func Init(tb TB, opts ...InitOption) TContext {
}),
ktesting.VerbosityFlagName("v"),
ktesting.VModuleFlagName("vmodule"),
ktesting.BufferLogs(c.BufferLogs),
ktesting.BufferLogs(bufferLogs),
)
// Copy klog settings instead of making the ktesting logger
@ -296,25 +318,7 @@ func Init(tb TB, opts ...InitOption) TContext {
// date/time header, and our own wrapper emulates that behavior for
// Log/Logf/...
logger := ktesting.NewLogger(tb, config)
ctx = klog.NewContext(interruptCtx, logger)
tb = withKlogHeader(tb)
}
if deadlineOK {
if deadline, ok := deadlineTB.Deadline(); ok {
timeLeft := time.Until(deadline)
timeLeft -= CleanupGracePeriod
ctx, cancel := withTimeout(ctx, tb, timeLeft, fmt.Sprintf("test suite deadline (%s) is close, need to clean up before the %s cleanup grace period", deadline.Truncate(time.Second), CleanupGracePeriod))
tCtx := tContext{
Context: ctx,
testingTB: testingTB{TB: tb},
cancel: cancel,
}
return tCtx
}
}
return WithCancel(InitCtx(ctx, tb))
return logger
}
type InitOption = initoption.InitOption
@ -345,12 +349,13 @@ func InitCtx(ctx context.Context, tb TB, _ ...InitOption) TContext {
// ...
// })
//
// WithTB sets up cancellation for the sub-test.
// WithTB sets up cancellation for the sub-test and uses per-test output.
//
// A simpler API is to use TContext.Run as replacement
// for [testing.T.Run].
func WithTB(parentCtx TContext, tb TB) TContext {
tCtx := InitCtx(parentCtx, tb)
tCtx := InitCtx(klog.NewContext(parentCtx, newLogger(tb, false /* don't buffer log output */)), tb)
tCtx = WithCancel(tCtx)
tCtx = WithClients(tCtx,
parentCtx.RESTConfig(),