Skip to content

Commit 9dc8a2a

Browse files
committed
add t.Output
1 parent b9c78bf commit 9dc8a2a

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

engine.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"encoding/binary"
1313
"flag"
1414
"fmt"
15+
"io"
1516
"log"
1617
"os"
1718
"path/filepath"
@@ -778,6 +779,39 @@ func (t *T) Log(args ...any) {
778779
}
779780
}
780781

782+
// Output returns a Writer that writes to the same test output stream as T.Log.
783+
// The output is indented like T.Log lines, but Output does not
784+
// add source locations or newlines. The output is internally line
785+
// buffered, and a call to T.Log or the end of the test will implicitly
786+
// flush the buffer, followed by a newline. After a test function and all its
787+
// parents return, neither Output nor the Write method may be called.
788+
//
789+
// If running on Go <= 1.25, where testing's t.Output is not available,
790+
// it falls back to using t.Log.
791+
func (t *T) Output() io.Writer {
792+
if t.rawLog != nil {
793+
return t.rawLog.Writer()
794+
} else if t.tbLog {
795+
if tout, ok := t.tb.(interface{ Output() io.Writer }); ok {
796+
return tout.Output()
797+
} else {
798+
return &tbWriter{t.tb}
799+
}
800+
} else {
801+
return io.Discard
802+
}
803+
}
804+
805+
type tbWriter struct {
806+
tb
807+
}
808+
809+
func (w *tbWriter) Write(b []byte) (int, error) {
810+
w.tb.Helper()
811+
w.tb.Logf("%s", b)
812+
return len(b), nil
813+
}
814+
781815
// Skipf is equivalent to [T.Logf] followed by [T.SkipNow].
782816
func (t *T) Skipf(format string, args ...any) {
783817
if t.tbLog {

engine_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
package rapid
88

99
import (
10+
"bytes"
1011
"context"
1112
"errors"
1213
"reflect"
@@ -259,3 +260,17 @@ func (ignoreErrorsTB) Errorf(string, ...interface{}) {}
259260
func (ignoreErrorsTB) Fatal(...interface{}) {}
260261
func (ignoreErrorsTB) Fatalf(string, ...interface{}) {}
261262
func (ignoreErrorsTB) Fail() {}
263+
264+
func TestOutputRawLog(t *testing.T) {
265+
t.Parallel()
266+
267+
msg := []byte("Hello World")
268+
269+
out := captureTestOutput(t, func(t *T) {
270+
t.Output().Write(msg)
271+
}, nil)
272+
273+
if !bytes.Contains(out, msg) {
274+
t.Errorf("expected output to contain %q, got: %q", msg, out)
275+
}
276+
}

0 commit comments

Comments
 (0)