| 67 | } |
| 68 | |
| 69 | func newExpecter(t *testing.T, r io.Reader, name string) outExpecter { |
| 70 | // Use pipe for logging. |
| 71 | logDone := make(chan struct{}) |
| 72 | logr, logw := io.Pipe() |
| 73 | |
| 74 | // Write to log and output buffer. |
| 75 | copyDone := make(chan struct{}) |
| 76 | out := newStdbuf() |
| 77 | w := io.MultiWriter(logw, out) |
| 78 | |
| 79 | ex := outExpecter{ |
| 80 | t: t, |
| 81 | out: out, |
| 82 | name: atomic.NewString(name), |
| 83 | |
| 84 | runeReader: bufio.NewReaderSize(out, utf8.UTFMax), |
| 85 | } |
| 86 | |
| 87 | logClose := func(name string, c io.Closer) { |
| 88 | ex.logf("closing %s", name) |
| 89 | err := c.Close() |
| 90 | ex.logf("closed %s: %v", name, err) |
| 91 | } |
| 92 | // Set the actual close function for the outExpecter. |
| 93 | ex.close = func(reason string) error { |
| 94 | ctx, cancel := context.WithTimeout(context.Background(), testutil.WaitShort) |
| 95 | defer cancel() |
| 96 | |
| 97 | ex.logf("closing expecter: %s", reason) |
| 98 | |
| 99 | // Caller needs to have closed the PTY so that copying can complete |
| 100 | select { |
| 101 | case <-ctx.Done(): |
| 102 | ex.fatalf("close", "copy did not close in time") |
| 103 | case <-copyDone: |
| 104 | } |
| 105 | |
| 106 | logClose("logw", logw) |
| 107 | logClose("logr", logr) |
| 108 | select { |
| 109 | case <-ctx.Done(): |
| 110 | ex.fatalf("close", "log pipe did not close in time") |
| 111 | case <-logDone: |
| 112 | } |
| 113 | |
| 114 | ex.logf("closed expecter") |
| 115 | |
| 116 | return nil |
| 117 | } |
| 118 | |
| 119 | go func() { |
| 120 | defer close(copyDone) |
| 121 | _, err := io.Copy(w, r) |
| 122 | ex.logf("copy done: %v", err) |
| 123 | ex.logf("closing out") |
| 124 | err = out.closeErr(err) |
| 125 | ex.logf("closed out: %v", err) |
| 126 | }() |