From 1605aed075cbf14f08c8612c3901396320ebebcc Mon Sep 17 00:00:00 2001 From: Brandur Date: Sun, 8 Jun 2025 12:36:19 +0200 Subject: [PATCH] Have `PanicTB` respond to `RIVER_DEBUG` en var Just a small one, but I was trying to debug an example test and found it to be quite annoying because test output is hidden by necessity so as not to mess with stdout for purposes of the example out matching. I'd previously added a special `WithLog` helper to `PanicTB` to add a logger for this sort of debugging, but it's easy to forget it exists. Here, modify things a bit to try an alternative so that when `RIVER_DEBUG is enabled, `PanicTB` sends logging to stderr (so it doesn't mess with stdout for the example). It might be easy to forget this exists too, but at least it's a convention that exists elsewhere for the test suite already and can be triggered without any code changes. --- rivershared/util/testutil/test_util.go | 28 +++++++++++++++++--------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/rivershared/util/testutil/test_util.go b/rivershared/util/testutil/test_util.go index e2b243b2..a2d4c353 100644 --- a/rivershared/util/testutil/test_util.go +++ b/rivershared/util/testutil/test_util.go @@ -4,17 +4,19 @@ import ( "bytes" "fmt" "io" + "os" ) // See docs on PanicTB. -type panicTB struct { - logOut io.Writer -} +type panicTB struct{} // PanicTB is an implementation for testing.TB that panics when an error is // logged or FailNow is called. This is useful to inject into test helpers in // example tests where no *testing.T is available. // +// If env is set with `RIVER_DEBUG=true`, output is logged to os.Stderr (Stderr +// instead of Stdout to not interfere with example test output). +// // Doesn't fully implement testing.TB. Functions where it's used should take the // more streamlined TestingTB instead. func PanicTB() *panicTB { @@ -32,22 +34,28 @@ func (tb *panicTB) FailNow() { func (tb *panicTB) Helper() {} func (tb *panicTB) Log(args ...any) { - if tb.logOut != nil { - fmt.Fprintln(tb.logOut, args...) + logOut := tb.maybeDebugOut() + if logOut != nil { + fmt.Fprintln(logOut, args...) } } func (tb *panicTB) Logf(format string, args ...any) { - if tb.logOut != nil { - fmt.Fprintf(tb.logOut, format+"\n", args...) + logOut := tb.maybeDebugOut() + if logOut != nil { + fmt.Fprintf(logOut, format+"\n", args...) } } func (tb *panicTB) Name() string { return "panicTB" } -func (tb *panicTB) WithLog(out io.Writer) *panicTB { - tb.logOut = out - return tb +func (tb *panicTB) maybeDebugOut() io.Writer { + if os.Getenv("RIVER_DEBUG") == "1" || os.Getenv("RIVER_DEBUG") == "true" { + // Send output to stderr so it doesn't interfere with example tests. + return os.Stderr + } + + return nil } // MockT mocks TestingTB. It's used to let us verify our test helpers.