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.
This commit is contained in:
Pieter Noordhuis 2024-03-26 08:57:48 +01:00 committed by GitHub
parent ed194668db
commit e3717ba1c4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 19 additions and 5 deletions

View File

@ -1,6 +1,7 @@
package process
import (
"bufio"
"bytes"
"context"
"fmt"
@ -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"})
@ -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) {
@ -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) {