github.com/netdata/go.d.plugin@v0.58.1/pkg/logs/lastline_test.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package logs 4 5 import ( 6 "os" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 "github.com/stretchr/testify/require" 11 ) 12 13 func TestReadLastLine(t *testing.T) { 14 tests := []struct { 15 name string 16 content string 17 expected string 18 err error 19 }{ 20 {"empty", "", "", nil}, 21 {"empty-ln", "\n", "\n", nil}, 22 {"one-line", "hello", "hello", nil}, 23 {"one-line-ln", "hello\n", "hello\n", nil}, 24 {"multi-line", "hello\nworld", "world", nil}, 25 {"multi-line-ln", "hello\nworld\n", "world\n", nil}, 26 {"long-line", "hello hello hello", "", ErrTooLongLine}, 27 {"long-line-ln", "hello hello hello\n", "", ErrTooLongLine}, 28 } 29 for _, test := range tests { 30 t.Run(test.name, func(t *testing.T) { 31 filename := prepareFile(t, test.content) 32 defer func() { _ = os.Remove(filename) }() 33 34 line, err := ReadLastLine(filename, 10) 35 36 if test.err != nil { 37 require.NotNil(t, err) 38 assert.Contains(t, err.Error(), test.err.Error()) 39 } else { 40 assert.Equal(t, test.expected, string(line)) 41 } 42 }) 43 } 44 } 45 46 func prepareFile(t *testing.T, content string) string { 47 t.Helper() 48 file, err := os.CreateTemp("", "go-test") 49 require.NoError(t, err) 50 defer func() { _ = file.Close() }() 51 52 _, _ = file.WriteString(content) 53 return file.Name() 54 }