Skip to content

Commit

Permalink
add openExistingOrNew unit test
Browse files Browse the repository at this point in the history
Signed-off-by: Arjun Raja Yogidas <[email protected]>
  • Loading branch information
coderbirju committed Nov 19, 2024
1 parent 6264d56 commit 7ec92c8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
5 changes: 2 additions & 3 deletions logrotate.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,9 +269,8 @@ func (l *Logger) backupName(name, nameTimeFormat string, local bool) (string, er
return filepath.Join(dir, filename), nil
}

// openExistingOrNew opens the logfile if it exists and if the current write
// would not put it over MaxBytes. If there is no such file or the write would
// put it over the MaxBytes, a new file is created.
// openExistingOrNew opens the logfile if it exists.
// If there is no such file a new file is created.
func (l *Logger) openExistingOrNew() error {
l.millRun()

Expand Down
38 changes: 38 additions & 0 deletions logrotate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,44 @@ 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
}

func TestWriteTooLong(t *testing.T) {
currentTime = fakeTime
dir := makeTempDir("TestWriteTooLong", t)
Expand Down

0 comments on commit 7ec92c8

Please sign in to comment.