Skip to content

Commit 41239d1

Browse files
authored
Fix flaky test in libs/process (#1314)
## Changes The order of stdout and stderr being read into the buffer for combined output is not deterministic due to scheduling of the underlying goroutines that consume them. That's why this asserts on the contents and not the order.
1 parent c7d1725 commit 41239d1

1 file changed

Lines changed: 19 additions & 5 deletions

File tree

libs/process/background_test.go

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package process
22

33
import (
4+
"bufio"
45
"bytes"
56
"context"
67
"fmt"
@@ -12,6 +13,17 @@ import (
1213
"github.com/stretchr/testify/assert"
1314
)
1415

16+
func splitLines(b []byte) (lines []string) {
17+
scan := bufio.NewScanner(bytes.NewReader(b))
18+
for scan.Scan() {
19+
line := scan.Text()
20+
if line != "" {
21+
lines = append(lines, line)
22+
}
23+
}
24+
return lines
25+
}
26+
1527
func TestBackgroundUnwrapsNotFound(t *testing.T) {
1628
ctx := context.Background()
1729
_, err := Background(ctx, []string{"/bin/meeecho", "1"})
@@ -46,7 +58,12 @@ func TestBackgroundCombinedOutput(t *testing.T) {
4658
}, WithCombinedOutput(&buf))
4759
assert.NoError(t, err)
4860
assert.Equal(t, "2", strings.TrimSpace(res))
49-
assert.Equal(t, "1\n2\n", strings.ReplaceAll(buf.String(), "\r", ""))
61+
62+
// The order of stdout and stderr being read into the buffer
63+
// for combined output is not deterministic due to scheduling
64+
// of the underlying goroutines that consume them.
65+
// That's why this asserts on the contents and not the order.
66+
assert.ElementsMatch(t, []string{"1", "2"}, splitLines(buf.Bytes()))
5067
}
5168

5269
func TestBackgroundCombinedOutputFailure(t *testing.T) {
@@ -66,10 +83,7 @@ func TestBackgroundCombinedOutputFailure(t *testing.T) {
6683
assert.Equal(t, "2", strings.TrimSpace(processErr.Stdout))
6784
}
6885
assert.Equal(t, "2", strings.TrimSpace(res))
69-
70-
out := strings.ReplaceAll(buf.String(), "\r", "")
71-
assert.Contains(t, out, "1\n")
72-
assert.Contains(t, out, "2\n")
86+
assert.ElementsMatch(t, []string{"1", "2"}, splitLines(buf.Bytes()))
7387
}
7488

7589
func TestBackgroundNoStdin(t *testing.T) {

0 commit comments

Comments
 (0)