Skip to content

Commit

Permalink
Fix flaky test in libs/process
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
pietern committed Mar 26, 2024
1 parent 1efebab commit 25868fe
Showing 1 changed file with 19 additions and 5 deletions.
24 changes: 19 additions & 5 deletions libs/process/background_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package process

import (
"bufio"
"bytes"
"context"
"fmt"
Expand All @@ -12,6 +13,17 @@ import (
"github.com/stretchr/testify/assert"
)

func splitLines(b []byte) (lines []string) {
scan := bufio.NewScanner(bytes.NewReader(b))
for scan.Scan() {
line := scan.Text()
if line != "" {
lines = append(lines, line)
}
}
return lines
}

func TestBackgroundUnwrapsNotFound(t *testing.T) {
ctx := context.Background()
_, err := Background(ctx, []string{"/bin/meeecho", "1"})
Expand Down Expand Up @@ -46,7 +58,12 @@ func TestBackgroundCombinedOutput(t *testing.T) {
}, WithCombinedOutput(&buf))
assert.NoError(t, err)
assert.Equal(t, "2", strings.TrimSpace(res))
assert.Equal(t, "1\n2\n", strings.ReplaceAll(buf.String(), "\r", ""))

// 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.
assert.ElementsMatch(t, []string{"1", "2"}, splitLines(buf.Bytes()))
}

func TestBackgroundCombinedOutputFailure(t *testing.T) {
Expand All @@ -66,10 +83,7 @@ func TestBackgroundCombinedOutputFailure(t *testing.T) {
assert.Equal(t, "2", strings.TrimSpace(processErr.Stdout))
}
assert.Equal(t, "2", strings.TrimSpace(res))

out := strings.ReplaceAll(buf.String(), "\r", "")
assert.Contains(t, out, "1\n")
assert.Contains(t, out, "2\n")
assert.ElementsMatch(t, []string{"1", "2"}, splitLines(buf.Bytes()))
}

func TestBackgroundNoStdin(t *testing.T) {
Expand Down

0 comments on commit 25868fe

Please sign in to comment.