logging_test.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package lifecycle
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strconv"
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/stretchr/testify/require"
  9. )
  10. func TestRotateLogs(t *testing.T) {
  11. logDir := t.TempDir()
  12. logFile := filepath.Join(logDir, "testlog.log")
  13. // No log exists
  14. rotateLogs(logFile)
  15. require.NoError(t, os.WriteFile(logFile, []byte("1"), 0644))
  16. assert.FileExists(t, logFile)
  17. // First rotation
  18. rotateLogs(logFile)
  19. assert.FileExists(t, filepath.Join(logDir, "testlog-1.log"))
  20. assert.NoFileExists(t, filepath.Join(logDir, "testlog-2.log"))
  21. assert.NoFileExists(t, logFile)
  22. // Should be a no-op without a new log
  23. rotateLogs(logFile)
  24. assert.FileExists(t, filepath.Join(logDir, "testlog-1.log"))
  25. assert.NoFileExists(t, filepath.Join(logDir, "testlog-2.log"))
  26. assert.NoFileExists(t, logFile)
  27. for i := 2; i <= LogRotationCount+1; i++ {
  28. require.NoError(t, os.WriteFile(logFile, []byte(strconv.Itoa(i)), 0644))
  29. assert.FileExists(t, logFile)
  30. rotateLogs(logFile)
  31. assert.NoFileExists(t, logFile)
  32. for j := 1; j < i; j++ {
  33. assert.FileExists(t, filepath.Join(logDir, "testlog-"+strconv.Itoa(j)+".log"))
  34. }
  35. assert.NoFileExists(t, filepath.Join(logDir, "testlog-"+strconv.Itoa(i+1)+".log"))
  36. }
  37. }