Skip to content

Commit b32b846

Browse files
authored
Merge pull request #182 from lucab/to-upstream/journalreader-test
sdjournal: add test for incorrect Read() length
2 parents ffc18f8 + e68eaeb commit b32b846

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

sdjournal/journal_test.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,13 @@
1616
package sdjournal
1717

1818
import (
19+
"bytes"
1920
"errors"
2021
"fmt"
2122
"io"
2223
"io/ioutil"
2324
"os"
25+
"strings"
2426
"testing"
2527
"time"
2628

@@ -228,3 +230,56 @@ func TestJournalGetEntry(t *testing.T) {
228230
t.Fatalf("Bad result for entry.Fields[\"MESSAGE\"]: got %s, want %s", got, want)
229231
}
230232
}
233+
234+
// Check for incorrect read into small buffers,
235+
// see https://github.com/coreos/go-systemd/issues/172
236+
func TestJournalReaderSmallReadBuffer(t *testing.T) {
237+
// Write a long entry ...
238+
delim := "%%%%%%"
239+
longEntry := strings.Repeat("a", 256)
240+
matchField := "TESTJOURNALREADERSMALLBUF"
241+
matchValue := fmt.Sprintf("%d", time.Now().UnixNano())
242+
r, err := NewJournalReader(JournalReaderConfig{
243+
Since: time.Duration(-15) * time.Second,
244+
Matches: []Match{
245+
{
246+
Field: matchField,
247+
Value: matchValue,
248+
},
249+
},
250+
})
251+
if err != nil {
252+
t.Fatalf("Error opening journal: %s", err)
253+
}
254+
if r == nil {
255+
t.Fatal("Got a nil reader")
256+
}
257+
defer r.Close()
258+
259+
want := fmt.Sprintf("%slongentry %s%s", delim, longEntry, delim)
260+
err = journal.Send(want, journal.PriInfo, map[string]string{matchField: matchValue})
261+
if err != nil {
262+
t.Fatal("Error writing to journal", err)
263+
}
264+
time.Sleep(time.Second)
265+
266+
// ... and try to read it back piece by piece via a small buffer
267+
finalBuff := new(bytes.Buffer)
268+
var e error
269+
for c := -1; c != 0 && e == nil; {
270+
smallBuf := make([]byte, 5)
271+
c, e = r.Read(smallBuf)
272+
if c > len(smallBuf) {
273+
t.Fatalf("Got unexpected read length: %d vs %d", c, len(smallBuf))
274+
}
275+
_, _ = finalBuff.Write(smallBuf)
276+
}
277+
b := finalBuff.String()
278+
got := strings.Split(b, delim)
279+
if len(got) != 3 {
280+
t.Fatalf("Got unexpected entry %s", b)
281+
}
282+
if got[1] != strings.Trim(want, delim) {
283+
t.Fatalf("Got unexpected message %s", got[1])
284+
}
285+
}

0 commit comments

Comments
 (0)