github.com/lingyao2333/mo-zero@v1.4.1/core/logx/syslog_test.go (about) 1 package logx 2 3 import ( 4 "encoding/json" 5 "log" 6 "strings" 7 "sync/atomic" 8 "testing" 9 10 "github.com/stretchr/testify/assert" 11 ) 12 13 const testlog = "Stay hungry, stay foolish." 14 15 func TestCollectSysLog(t *testing.T) { 16 CollectSysLog() 17 content := getContent(captureOutput(func() { 18 log.Print(testlog) 19 })) 20 assert.True(t, strings.Contains(content, testlog)) 21 } 22 23 func TestRedirector(t *testing.T) { 24 var r redirector 25 content := getContent(captureOutput(func() { 26 r.Write([]byte(testlog)) 27 })) 28 assert.Equal(t, testlog, content) 29 } 30 31 func captureOutput(f func()) string { 32 w := new(mockWriter) 33 old := writer.Swap(w) 34 defer writer.Store(old) 35 36 prevLevel := atomic.LoadUint32(&logLevel) 37 SetLevel(InfoLevel) 38 f() 39 SetLevel(prevLevel) 40 41 return w.String() 42 } 43 44 func getContent(jsonStr string) string { 45 var entry map[string]interface{} 46 json.Unmarshal([]byte(jsonStr), &entry) 47 48 val, ok := entry[contentKey] 49 if !ok { 50 return "" 51 } 52 53 str, ok := val.(string) 54 if !ok { 55 return "" 56 } 57 58 return str 59 }