runCommand builds the cobra command from `command`, feeds it `args` just like a user would on the shell, captures everything the command writes to stderr, and returns (stderr, executeErr).
(t *testing.T, cmd *cobra.Command, args ...string)
| 58 | // like a user would on the shell, captures everything the command writes to |
| 59 | // stderr, and returns (stderr, executeErr). |
| 60 | func runCommand(t *testing.T, cmd *cobra.Command, args ...string) (string, error) { |
| 61 | t.Helper() |
| 62 | |
| 63 | // Redirect os.Stderr to a pipe. Anything the command writes to |
| 64 | // stderr lands in `reader`. We restore the original os.Stderr before returning. |
| 65 | stdErr := os.Stderr |
| 66 | reader, writer, err := os.Pipe() |
| 67 | if err != nil { |
| 68 | t.Fatal(err) |
| 69 | } |
| 70 | os.Stderr = writer |
| 71 | |
| 72 | // Drain the pipe in a goroutine while the command runs. |
| 73 | done := make(chan string, 1) |
| 74 | go func() { |
| 75 | var buf strings.Builder |
| 76 | _, _ = io.Copy(&buf, reader) |
| 77 | done <- buf.String() |
| 78 | }() |
| 79 | |
| 80 | // Run the command, then close the write end so the goroutine sees |
| 81 | // EOF and exits. Order matters: close must happen before <-done, |
| 82 | // otherwise the receive blocks forever. |
| 83 | cmd.SetArgs(args) |
| 84 | execErr := cmd.Execute() |
| 85 | _ = writer.Close() |
| 86 | os.Stderr = stdErr |
| 87 | return <-done, execErr |
| 88 | } |
| 89 | |
| 90 | // equals reports whether list1 and list2 contain the same elements, ignoring order. |
| 91 | func equals(list1, list2 []string) bool { |
no test coverage detected