| 1 | // Package testlogger contains a helper to put a stdout/stderr output stream of |
| 2 | // a subprocess onto the testing package's t.Log(). |
| 3 | package testlogger |
| 4 | |
| 5 | import ( |
| 6 | "bufio" |
| 7 | "io" |
| 8 | "sync" |
| 9 | "testing" |
| 10 | ) |
| 11 | |
| 12 | type Logger struct { |
| 13 | tb testing.TB |
| 14 | writer *io.PipeWriter |
| 15 | scanner *bufio.Scanner |
| 16 | } |
| 17 | |
| 18 | func New(tb testing.TB) *Logger { |
| 19 | r, w := io.Pipe() |
| 20 | tl := &Logger{ |
| 21 | tb: tb, |
| 22 | writer: w, |
| 23 | scanner: bufio.NewScanner(r), |
| 24 | } |
| 25 | var wg sync.WaitGroup |
| 26 | wg.Add(1) |
| 27 | tb.Cleanup(func() { |
| 28 | w.Close() |
| 29 | // tl.scanner.Scan() will return false, |
| 30 | // tl.scanner.Err() will return nil. |
| 31 | |
| 32 | // Ensure the goroutine below is done |
| 33 | // to prevent data races in tb.Log() |
| 34 | wg.Wait() |
| 35 | }) |
| 36 | go func() { |
| 37 | defer wg.Done() |
| 38 | for tl.scanner.Scan() { |
| 39 | tb.Log(tl.scanner.Text()) |
| 40 | } |
| 41 | if err := tl.scanner.Err(); err != nil { |
| 42 | tb.Log(err) |
| 43 | } |
| 44 | }() |
| 45 | return tl |
| 46 | } |
| 47 | |
| 48 | // Write implements io.Writer. |
| 49 | func (lw Logger) Write(p []byte) (n int, err error) { |
| 50 | return lw.writer.Write(p) |
| 51 | } |
| 52 | |
| 53 | // Close implements io.Closer. |
| 54 | func (lw Logger) Close() error { return nil } |