Skip to content

Commit fc55fec

Browse files
committed
ktesting: support capturing log output
This is a feature of the underlying k8s.io/klog/v2/ktesting which is useful also when using the Kubernetes ktesting.
1 parent 8cf93c8 commit fc55fec

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

test/utils/ktesting/initoption/initoption.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,13 @@ func PerTestOutput(enabled bool) InitOption {
2828
c.PerTestOutput = enabled
2929
}
3030
}
31+
32+
// BufferLogs controls whether log entries are captured in memory in addition
33+
// to being printed. Off by default. Unit tests that want to verify that
34+
// log entries are emitted as expected can turn this on and then retrieve
35+
// the captured log through the Underlier LogSink interface.
36+
func BufferLogs(enabled bool) InitOption {
37+
return func(c *internal.InitConfig) {
38+
c.BufferLogs = enabled
39+
}
40+
}

test/utils/ktesting/internal/config.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,5 @@ package internal
1818

1919
type InitConfig struct {
2020
PerTestOutput bool
21+
BufferLogs bool
2122
}

test/utils/ktesting/tcontext.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@ import (
3636
)
3737

3838
// Underlier is the additional interface implemented by the per-test LogSink
39-
// behind [TContext.Logger].
39+
// behind [TContext.Logger]. Together with [initoption.BufferLogs] it can be
40+
// used to capture log output in memory to check it in tests.
4041
type Underlier = ktesting.Underlier
4142

4243
// CleanupGracePeriod is the time that a [TContext] gets canceled before the
@@ -245,6 +246,7 @@ func Init(tb TB, opts ...InitOption) TContext {
245246
}),
246247
ktesting.VerbosityFlagName("v"),
247248
ktesting.VModuleFlagName("vmodule"),
249+
ktesting.BufferLogs(c.BufferLogs),
248250
)
249251

250252
// Copy klog settings instead of making the ktesting logger

0 commit comments

Comments
 (0)