From b73721afcea0e367329ef553deebf163169a2469 Mon Sep 17 00:00:00 2001 From: Arjun Raja Yogidas Date: Tue, 19 Nov 2024 00:40:06 +0000 Subject: [PATCH] add openExistingOrNew unit test Signed-off-by: Arjun Raja Yogidas --- logrotate_test.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/logrotate_test.go b/logrotate_test.go index 2cb0b03..f793fc1 100644 --- a/logrotate_test.go +++ b/logrotate_test.go @@ -78,6 +78,55 @@ func TestOpenExisting(t *testing.T) { fileCount(dir, 1, t) } +func TestOpenExistingOrNew(t *testing.T) { + dir := makeTempDir("TestOpenExistingOrNew", t) + defer os.RemoveAll(dir) + + filename := logFile(dir) + l := &Logger{ + Filename: filename, + MaxBytes: 100, + } + + // File doesn't exist + err := l.openExistingOrNew() + isNil(err, t) + assert(l.file != nil, t, "Expected file to be opened") + equals(int64(0), l.size, t) + + content := []byte("Hello, World!") + _, err = l.file.Write(content) + isNil(err, t) + l.size = int64(len(content)) + + // Close + err = l.file.Close() + isNil(err, t) + l.file = nil + + // File exists and is not over MaxBytes + err = l.openExistingOrNew() + isNil(err, t) + assert(l.file != nil, t, "Expected file to be opened") + equals(int64(len(content)), l.size, t) + + // Close + err = l.file.Close() + isNil(err, t) + l.file = nil + + // File exists and is over MaxBytes + l.MaxBytes = 10 // Set MaxBytes to a value less than the file size + err = l.openExistingOrNew() + isNil(err, t) + assert(l.file != nil, t, "Expected file to be opened") + equals(int64(0), l.size, t) // New file should be empty + + // Clean up + err = l.file.Close() + isNil(err, t) +} + func TestWriteTooLong(t *testing.T) { currentTime = fakeTime dir := makeTempDir("TestWriteTooLong", t)