package tail import ( "os" "path/filepath" "sync" "testing" ) // copytruncate where the application regrows the file past the old offset // before the next poll: the size never looks smaller, the head changes. func TestCopytruncateRegrowIsDetected(t *testing.T) { p := filepath.Join(t.TempDir(), "a.log") os.WriteFile(p, []byte("l1\nl2\nl3\n"), 0o644) var mu sync.Mutex var got []string f := NewFollower(p, Pos{}) f.Handle = func(b []byte) { mu.Lock(); got = append(got, string(b)); mu.Unlock() } f.step() os.WriteFile(p, []byte("n1\nn2\nn3\nn4\nn5\n"), 0o644) // truncated in place and regrown beyond offset 9 f.step() f.step() want := []string{"l1", "l2", "l3", "n1", "n2", "n3", "n4", "n5"} if len(got) != len(want) { t.Fatalf("lines %v, want %v", got, want) } for i := range want { if got[i] != want[i] { t.Fatalf("lines %v, want %v", got, want) } } } // the same while the daemon was stopped: the saved position carries the fingerprint. func TestSavedPositionDetectsRegrownFile(t *testing.T) { p := filepath.Join(t.TempDir(), "a.log") os.WriteFile(p, []byte("l1\nl2\nl3\n"), 0o644) f := NewFollower(p, Pos{}) f.Handle = func([]byte) {} f.step() pos := f.Pos() f.closeFile() if pos.FPLen == 0 { t.Fatal("the position must carry a fingerprint") } os.WriteFile(p, []byte("n1\nn2\nn3\nn4\nn5\n"), 0o644) var got []string g := NewFollower(p, pos) g.Handle = func(b []byte) { got = append(got, string(b)) } g.step() if len(got) != 5 || got[0] != "n1" { t.Fatalf("resumed in the middle of a different file: %v", got) } } func TestFileAppearingLaterAndAppends(t *testing.T) { p := filepath.Join(t.TempDir(), "later.log") var got []string f := NewFollower(p, Pos{}) f.Handle = func(b []byte) { got = append(got, string(b)) } f.step() if f.Err() == nil { t.Fatal("an absent file is reported") } os.WriteFile(p, []byte("a\nb\n"), 0o644) f.step() fh, _ := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0) fh.WriteString("c\n") fh.Close() f.step() if len(got) != 3 || got[2] != "c" || f.Err() != nil { t.Fatalf("%v %v", got, f.Err()) } }