blob: fe690175af92ea39f3d2881014b65bb896c86c3b [file] [log] [blame]
Serge Bazanskif8a8e652021-07-06 16:23:43 +02001package logtree
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "testing"
8)
9
10// PipeAllToStderr starts a goroutine that will forward all logtree entries
11// into stderr, in the canonical logtree payload representation.
12//
13// It's designed to be used in tests, and will automatically stop when the
14// test/benchmark it's running in exits.
Serge Bazanskie25b3a42023-03-17 00:07:53 +010015func PipeAllToStderr(t testing.TB, lt *LogTree) {
Serge Bazanskif8a8e652021-07-06 16:23:43 +020016 t.Helper()
17
18 reader, err := lt.Read("", WithChildren(), WithStream())
19 if err != nil {
20 t.Fatalf("Failed to set up logtree reader: %v", err)
21 }
22
23 // Internal context used to cancel the goroutine. This could also be a
24 // implemented via a channel.
25 ctx, ctxC := context.WithCancel(context.Background())
26 t.Cleanup(ctxC)
27
28 go func() {
29 for {
30 select {
31 case <-ctx.Done():
32 return
33 case p := <-reader.Stream:
34 fmt.Fprintf(os.Stderr, "%s\n", p.String())
35 }
36 }
37 }()
38}