From fc55fecd4507a435e18b7263d26f6cc567669ff9 Mon Sep 17 00:00:00 2001 From: Patrick Ohly Date: Tue, 25 Jun 2024 17:10:13 +0200 Subject: [PATCH] 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. --- test/utils/ktesting/initoption/initoption.go | 10 ++++++++++ test/utils/ktesting/internal/config.go | 1 + test/utils/ktesting/tcontext.go | 4 +++- 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/test/utils/ktesting/initoption/initoption.go b/test/utils/ktesting/initoption/initoption.go index cdac2be3950..d65aa515e50 100644 --- a/test/utils/ktesting/initoption/initoption.go +++ b/test/utils/ktesting/initoption/initoption.go @@ -28,3 +28,13 @@ func PerTestOutput(enabled bool) InitOption { c.PerTestOutput = enabled } } + +// BufferLogs controls whether log entries are captured in memory in addition +// to being printed. Off by default. Unit tests that want to verify that +// log entries are emitted as expected can turn this on and then retrieve +// the captured log through the Underlier LogSink interface. +func BufferLogs(enabled bool) InitOption { + return func(c *internal.InitConfig) { + c.BufferLogs = enabled + } +} diff --git a/test/utils/ktesting/internal/config.go b/test/utils/ktesting/internal/config.go index 22f7560aedf..88403a00e88 100644 --- a/test/utils/ktesting/internal/config.go +++ b/test/utils/ktesting/internal/config.go @@ -18,4 +18,5 @@ package internal type InitConfig struct { PerTestOutput bool + BufferLogs bool } diff --git a/test/utils/ktesting/tcontext.go b/test/utils/ktesting/tcontext.go index 055ced48a87..dac8a8affc6 100644 --- a/test/utils/ktesting/tcontext.go +++ b/test/utils/ktesting/tcontext.go @@ -36,7 +36,8 @@ import ( ) // Underlier is the additional interface implemented by the per-test LogSink -// behind [TContext.Logger]. +// behind [TContext.Logger]. Together with [initoption.BufferLogs] it can be +// used to capture log output in memory to check it in tests. type Underlier = ktesting.Underlier // CleanupGracePeriod is the time that a [TContext] gets canceled before the @@ -245,6 +246,7 @@ func Init(tb TB, opts ...InitOption) TContext { }), ktesting.VerbosityFlagName("v"), ktesting.VModuleFlagName("vmodule"), + ktesting.BufferLogs(c.BufferLogs), ) // Copy klog settings instead of making the ktesting logger