| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "os" |
| 6 | "os/exec" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | // A reader that stops early leaves help's exit status alone: valley |
| 11 | // exits 0 for each help path, and 1 for the unknown verb, whose usage |
| 12 | // goes to stderr. The child is this test binary running valley's main |
| 13 | // (TestMain), with the write end of a real pipe as the stream under test |
| 14 | // and its read end closed before the child writes, so its write finds no |
| 15 | // reader, as one into `head -n 1` that has already exited does. |
| 16 | func TestHelpSurvivesAReaderThatStops(t *testing.T) { |
| 17 | self, err := os.Executable() |
| 18 | if err != nil { |
| 19 | t.Fatal(err) |
| 20 | } |
| 21 | for _, c := range []struct { |
| 22 | args []string |
| 23 | stderr bool // the stream whose reader stops |
| 24 | status int |
| 25 | }{ |
| 26 | {[]string{"help", "review"}, false, 0}, |
| 27 | {[]string{"help"}, false, 0}, |
| 28 | {[]string{"review", "--help"}, false, 0}, |
| 29 | {[]string{"self-update", "-h"}, false, 0}, |
| 30 | {[]string{"zx81q"}, true, 1}, |
| 31 | } { |
| 32 | elsewhere(t) |
| 33 | r, w, err := os.Pipe() |
| 34 | if err != nil { |
| 35 | t.Fatal(err) |
| 36 | } |
| 37 | release, hold, err := os.Pipe() |
| 38 | if err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | cmd := exec.Command(self, c.args...) |
| 42 | cmd.Env = append(os.Environ(), "VALLEY_TEST_AS_MAIN=1") |
| 43 | cmd.Stdin = release |
| 44 | if c.stderr { |
| 45 | cmd.Stderr = w |
| 46 | } else { |
| 47 | cmd.Stdout = w |
| 48 | } |
| 49 | if err := cmd.Start(); err != nil { |
| 50 | t.Fatal(err) |
| 51 | } |
| 52 | r.Close() |
| 53 | w.Close() |
| 54 | release.Close() |
| 55 | hold.Write([]byte{0}) |
| 56 | hold.Close() |
| 57 | err = cmd.Wait() |
| 58 | got := 0 |
| 59 | if ee := (*exec.ExitError)(nil); errors.As(err, &ee) { |
| 60 | got = ee.ExitCode() // -1 when a signal ended it |
| 61 | } else if err != nil { |
| 62 | t.Fatal(err) |
| 63 | } |
| 64 | if got != c.status { |
| 65 | t.Errorf("valley %v with its reader gone: exit %d, want %d", c.args, got, c.status) |
| 66 | } |
| 67 | } |
| 68 | } |