Serge Bazanski | f8a8e65 | 2021-07-06 16:23:43 +0200 | [diff] [blame] | 1 | package logtree |
| 2 | |
| 3 | import ( |
| 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. |
| 15 | func PipeAllToStderr(t *testing.T, lt *LogTree) { |
| 16 | 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 | } |