WithStdoutCaptured executes the passed function and returns a string containing the stdout of the executed function.
(f func())
| 88 | // WithStdoutCaptured executes the passed function and returns a string |
| 89 | // containing the stdout of the executed function. |
| 90 | func WithStdoutCaptured(f func()) string { |
| 91 | osStdout := os.Stdout |
| 92 | r, w, err := os.Pipe() |
| 93 | |
| 94 | if err != nil { |
| 95 | panic(err) |
| 96 | } |
| 97 | |
| 98 | os.Stdout = w |
| 99 | |
| 100 | outC := make(chan string) |
| 101 | |
| 102 | go func() { |
| 103 | var buf bytes.Buffer |
| 104 | |
| 105 | if _, err := io.Copy(&buf, r); err != nil { |
| 106 | panic(err) |
| 107 | } |
| 108 | |
| 109 | outC <- buf.String() |
| 110 | }() |
| 111 | |
| 112 | f() |
| 113 | |
| 114 | w.Close() |
| 115 | os.Stdout = osStdout |
| 116 | out := <-outC |
| 117 | |
| 118 | return out |
| 119 | } |
| 120 | |
| 121 | // RemoveDirectoryOrFail removes a directory (and its contents) or fails the test. |
| 122 | func RemoveDirectoryOrFail(t *testing.T, path string) { |