From 25868fef8d99af5ff9366a6ce26e7931d35f3a11 Mon Sep 17 00:00:00 2001 From: Pieter Noordhuis Date: Tue, 26 Mar 2024 08:48:48 +0100 Subject: [PATCH] Fix flaky test in `libs/process` 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. --- libs/process/background_test.go | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/libs/process/background_test.go b/libs/process/background_test.go index 5bf2400bcb3..2ee6727a010 100644 --- a/libs/process/background_test.go +++ b/libs/process/background_test.go @@ -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) {