From 72cf3efb1d39d3b268659edd759532bdf96ff49e Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Wed, 9 Oct 2024 15:08:42 +0200 Subject: [PATCH] Add test demonstrating problem with ForEachLineInFile The function drops the last line if it doesn't end with a line feed. --- pkg/utils/io_test.go | 63 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 pkg/utils/io_test.go diff --git a/pkg/utils/io_test.go b/pkg/utils/io_test.go new file mode 100644 index 00000000000..bf1d46ebe3b --- /dev/null +++ b/pkg/utils/io_test.go @@ -0,0 +1,63 @@ +package utils + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_forEachLineInStream(t *testing.T) { + scenarios := []struct { + name string + input string + expectedLines []string + }{ + { + name: "empty input", + input: "", + expectedLines: []string{}, + }, + { + name: "single line", + input: "abc\n", + expectedLines: []string{"abc\n"}, + }, + { + name: "single line without line feed", + input: "abc", + /* EXPECTED: + expectedLines: []string{"abc"}, + ACTUAL: */ + expectedLines: []string{}, + }, + { + name: "multiple lines", + input: "abc\ndef\n", + expectedLines: []string{"abc\n", "def\n"}, + }, + { + name: "multiple lines including empty lines", + input: "abc\n\ndef\n", + expectedLines: []string{"abc\n", "\n", "def\n"}, + }, + { + name: "multiple lines without linefeed at end of file", + input: "abc\ndef\nghi", + /* EXPECTED: + expectedLines: []string{"abc\n", "def\n", "ghi"}, + ACTUAL: */ + expectedLines: []string{"abc\n", "def\n"}, + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + lines := []string{} + forEachLineInStream(strings.NewReader(s.input), func(line string, i int) { + lines = append(lines, line) + }) + assert.EqualValues(t, s.expectedLines, lines) + }) + } +}