github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/countlog/output/rotation/rotation_test.go (about) 1 package rotation_test 2 3 import ( 4 "testing" 5 "github.com/v2pro/plz/test" 6 "github.com/v2pro/plz/countlog" 7 "github.com/v2pro/plz/countlog/output/rotation" 8 "github.com/v2pro/plz/test/must" 9 "os" 10 "io/ioutil" 11 "time" 12 ) 13 14 func resetTestLogDir() { 15 os.RemoveAll("/tmp/testlog") 16 os.Mkdir("/tmp/testlog", 0744) 17 } 18 19 func reset(cfg rotation.Config) *rotation.Writer { 20 resetTestLogDir() 21 writer := must.Call(rotation.NewWriter, cfg)[0].(*rotation.Writer) 22 return writer 23 } 24 25 func Test_write(t *testing.T) { 26 t.Run("write to existing file", test.Case(func(ctx *countlog.Context) { 27 resetTestLogDir() 28 ioutil.WriteFile("/tmp/testlog/test.log", []byte("hello\n"), 0644) 29 writer := must.Call(rotation.NewWriter, rotation.Config{ 30 WritePath: "/tmp/testlog/test.log", 31 })[0].(*rotation.Writer) 32 defer must.Call(writer.Close) 33 must.Call(writer.Write, []byte("world")) 34 content := must.Call(ioutil.ReadFile, "/tmp/testlog/test.log")[0].([]byte) 35 must.Equal("hello\nworld", string(content)) 36 })) 37 t.Run("write to new file", test.Case(func(ctx *countlog.Context) { 38 writer := reset(rotation.Config{ 39 WritePath: "/tmp/testlog/test.log", 40 }) 41 defer must.Call(writer.Close) 42 must.Call(writer.Write, []byte("hello")) 43 content := must.Call(ioutil.ReadFile, "/tmp/testlog/test.log")[0].([]byte) 44 must.Equal("hello", string(content)) 45 })) 46 t.Run("write to new dir", test.Case(func(ctx *countlog.Context) { 47 writer := reset(rotation.Config{ 48 WritePath: "/tmp/testlog/newdir/test.log", 49 }) 50 defer must.Call(writer.Close) 51 must.Call(writer.Write, []byte("hello")) 52 content := must.Call(ioutil.ReadFile, "/tmp/testlog/newdir/test.log")[0].([]byte) 53 must.Equal("hello", string(content)) 54 })) 55 } 56 57 func Test_rotation(t *testing.T) { 58 t.Run("rotate by time interval", test.Case(func(ctx *countlog.Context) { 59 writer := reset(rotation.Config{ 60 WritePath: "/tmp/testlog/test.log", 61 TriggerStrategy: &rotation.TriggerByInterval{ 62 Interval: time.Second, 63 }, 64 ArchiveStrategy: &rotation.ArchiveByMove{ 65 NamingStrategy: &rotation.NameByTime{ 66 Directory: "/tmp/testlog", 67 Pattern: "test-2006-01-02T15-04-05.log", 68 }, 69 }, 70 RetainStrategy: &rotation.RetainByCount{3}, 71 PurgeStrategy: &rotation.PurgeByDelete{}, 72 }) 73 defer must.Call(writer.Close) 74 for i := 0; i < 60; i++ { 75 writer.Write([]byte("hello\n")) 76 time.Sleep(time.Second) 77 } 78 })) 79 }