|
16 | 16 | package sdjournal |
17 | 17 |
|
18 | 18 | import ( |
| 19 | + "bytes" |
19 | 20 | "errors" |
20 | 21 | "fmt" |
21 | 22 | "io" |
22 | 23 | "io/ioutil" |
23 | 24 | "os" |
| 25 | + "strings" |
24 | 26 | "testing" |
25 | 27 | "time" |
26 | 28 |
|
@@ -228,3 +230,56 @@ func TestJournalGetEntry(t *testing.T) { |
228 | 230 | t.Fatalf("Bad result for entry.Fields[\"MESSAGE\"]: got %s, want %s", got, want) |
229 | 231 | } |
230 | 232 | } |
| 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