Skip to content

Commit da9d7db

Browse files
committed
add t.Output
1 parent 011e717 commit da9d7db

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

engine.go

Lines changed: 26 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,31 @@ 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+
// Only available on Go >= 1.25
790+
func (t *T) Output() io.Writer {
791+
t.Helper()
792+
793+
if t.rawLog != nil {
794+
return t.rawLog.Writer()
795+
} else if t.tbLog {
796+
if tout, ok := t.tb.(interface{ Output() io.Writer }); ok {
797+
return tout.Output()
798+
} else {
799+
t.Fatal("[rapid] Output requires Go 1.25 or newer")
800+
return nil
801+
}
802+
} else {
803+
return io.Discard
804+
}
805+
}
806+
781807
// Skipf is equivalent to [T.Logf] followed by [T.SkipNow].
782808
func (t *T) Skipf(format string, args ...any) {
783809
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"
@@ -251,6 +252,20 @@ func TestCheckCleanupContextCreatedInCleanup(t *testing.T) {
251252
})
252253
}
253254

255+
func TestOutputRawLog(t *testing.T) {
256+
t.Parallel()
257+
258+
msg := []byte("Hello World")
259+
260+
out := captureTestOutput(t, func(t *T) {
261+
t.Output().Write(msg)
262+
}, nil)
263+
264+
if !bytes.Contains(out, msg) {
265+
t.Errorf("expected output to contain %q, got: %q", msg, out)
266+
}
267+
}
268+
254269
// ignoreErrorsTB is a TB that ignores all errors posted to it.
255270
type ignoreErrorsTB struct{ TB }
256271

0 commit comments

Comments
 (0)