Helper function to capture stdout/stderr during a test run
(t *testing.T, f func())
| 21 | |
| 22 | // Helper function to capture stdout/stderr during a test run |
| 23 | func captureOutput(t *testing.T, f func()) (stdout, stderr string) { |
| 24 | t.Helper() // Marks this as a helper function for testing framework |
| 25 | |
| 26 | originalStdout := os.Stdout |
| 27 | originalStderr := os.Stderr |
| 28 | oldLogger := slog.Default() |
| 29 | rOut, wOut, _ := os.Pipe() |
| 30 | rErr, wErr, _ := os.Pipe() |
| 31 | os.Stdout = wOut |
| 32 | os.Stderr = wErr |
| 33 | |
| 34 | t.Cleanup(func() { |
| 35 | os.Stdout = originalStdout |
| 36 | os.Stderr = originalStderr |
| 37 | slog.SetDefault(oldLogger) |
| 38 | }) |
| 39 | |
| 40 | outCh := make(chan string) |
| 41 | errCh := make(chan string) |
| 42 | |
| 43 | go func() { |
| 44 | var buf bytes.Buffer |
| 45 | _, _ = io.Copy(&buf, rOut) |
| 46 | outCh <- buf.String() |
| 47 | }() |
| 48 | go func() { |
| 49 | var buf bytes.Buffer |
| 50 | _, _ = io.Copy(&buf, rErr) |
| 51 | errCh <- buf.String() |
| 52 | }() |
| 53 | |
| 54 | f() // Execute the function |
| 55 | |
| 56 | _ = wOut.Close() |
| 57 | _ = wErr.Close() |
| 58 | stdout = <-outCh |
| 59 | stderr = <-errCh |
| 60 | return stdout, stderr |
| 61 | } |
| 62 | |
| 63 | // --- Test Suite --- |
| 64 |
no test coverage detected
searching dependent graphs…