Skip to content

Commit b076d77

Browse files
committed
test: improve stdout capture in tests with error handling
**Added:** - Introduced a `captureResult` struct to carry both output and error from goroutine handling stdout capture **Changed:** - Updated stdout capturing logic to use `captureResult`, enabling error propagation from the goroutine to the test - Modified `restore` to fail the test with `t.Fatalf` if an error occurred during output capture **Removed:** - Removed use of string-only channels for capturing output, ensuring errors are not silently ignored
1 parent 349883a commit b076d77

1 file changed

Lines changed: 14 additions & 5 deletions

File tree

‎cli/internal/validate/validator_test.go‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -175,10 +175,15 @@ func indexOf(lines []string, substr string) int {
175175
type stdoutCapture struct {
176176
orig *os.File
177177
r, w *os.File
178-
done chan string
178+
done chan captureResult
179179
t *testing.T
180180
}
181181

182+
type captureResult struct {
183+
output string
184+
err error
185+
}
186+
182187
func captureStdout(t *testing.T) *stdoutCapture {
183188
t.Helper()
184189
r, w, err := os.Pipe()
@@ -188,11 +193,11 @@ func captureStdout(t *testing.T) *stdoutCapture {
188193
orig := os.Stdout
189194
os.Stdout = w
190195

191-
done := make(chan string)
196+
done := make(chan captureResult)
192197
go func() {
193198
var buf bytes.Buffer
194-
_, _ = io.Copy(&buf, r)
195-
done <- buf.String()
199+
_, err := io.Copy(&buf, r)
200+
done <- captureResult{output: buf.String(), err: err}
196201
}()
197202

198203
return &stdoutCapture{orig: orig, r: r, w: w, done: done, t: t}
@@ -202,5 +207,9 @@ func (c *stdoutCapture) restore() string {
202207
c.t.Helper()
203208
c.w.Close()
204209
os.Stdout = c.orig
205-
return <-c.done
210+
res := <-c.done
211+
if res.err != nil {
212+
c.t.Fatalf("capturing stdout: %v", res.err)
213+
}
214+
return res.output
206215
}

0 commit comments

Comments
 (0)