github.com/richardwilkes/toolbox@v1.121.0/log/rotation/rotator_test.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 package rotation_test 11 12 import ( 13 "fmt" 14 "os" 15 "path/filepath" 16 "testing" 17 18 "github.com/richardwilkes/toolbox/check" 19 "github.com/richardwilkes/toolbox/log/rotation" 20 ) 21 22 const ( 23 maxSize = 100 24 maxBackups = 2 25 ) 26 27 func TestRotator(t *testing.T) { 28 tmpdir, err := os.MkdirTemp("", "rotator_test_") 29 check.NoError(t, err) 30 defer cleanup(t, tmpdir) 31 32 logFiles := []string{filepath.Join(tmpdir, "test.log")} 33 for i := 1; i <= maxBackups; i++ { 34 logFiles = append(logFiles, fmt.Sprintf("%s-%d", logFiles[0], i)) 35 } 36 37 r, err := rotation.New(rotation.Path(logFiles[0]), rotation.MaxSize(maxSize), rotation.MaxBackups(maxBackups)) 38 check.NoError(t, err) 39 _, err = os.Stat(logFiles[0]) 40 check.Error(t, err) 41 check.True(t, os.IsNotExist(err)) 42 for i := 0; i < maxSize*(2+maxBackups); i++ { 43 _, err = fmt.Fprintln(r, i) 44 check.NoError(t, err) 45 } 46 _, err = fmt.Fprintln(r, "goodbye") 47 check.NoError(t, err) 48 check.NoError(t, r.Close()) 49 for _, f := range logFiles { 50 fi, fErr := os.Stat(f) 51 check.NoError(t, fErr) 52 check.True(t, fi.Size() <= maxSize) 53 } 54 55 r, err = rotation.New(rotation.Path(logFiles[0]), rotation.MaxSize(maxSize), rotation.MaxBackups(maxBackups)) 56 check.NoError(t, err) 57 _, err = fmt.Fprintln(r, "hello") 58 check.NoError(t, err) 59 check.NoError(t, r.Close()) 60 } 61 62 func cleanup(t *testing.T, path string) { 63 t.Helper() 64 check.NoError(t, os.RemoveAll(path)) 65 }