captureOutput temporarily redirects os.Stdout during f(), returning what was printed. Useful for testing formatters that write directly to os.Stdout instead of Cobra's writer.
(f func())
| 16 | // captureOutput temporarily redirects os.Stdout during f(), returning what was printed. |
| 17 | // Useful for testing formatters that write directly to os.Stdout instead of Cobra's writer. |
| 18 | func captureOutput(f func()) string { |
| 19 | var buf bytes.Buffer |
| 20 | stdout := os.Stdout |
| 21 | r, w, _ := os.Pipe() |
| 22 | os.Stdout = w |
| 23 | |
| 24 | done := make(chan struct{}) |
| 25 | go func() { |
| 26 | _, _ = io.Copy(&buf, r) |
| 27 | close(done) |
| 28 | }() |
| 29 | |
| 30 | f() |
| 31 | |
| 32 | w.Close() |
| 33 | <-done |
| 34 | os.Stdout = stdout |
| 35 | |
| 36 | return buf.String() |
| 37 | } |
| 38 | |
| 39 | func TestCheckmake_NoArgsShowsHelp(t *testing.T) { |
| 40 | out := captureOutput(func() { |
no test coverage detected