go-zero/core/logx/syslog_test.go

49 lines
907 B
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package logx
import (
"encoding/json"
"log"
"strings"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
const testlog = "Stay hungry, stay foolish."
func TestCollectSysLog(t *testing.T) {
CollectSysLog()
content := getContent(captureOutput(func() {
2020-10-16 11:13:55 +08:00
log.Print(testlog)
2020-07-26 17:09:05 +08:00
}))
assert.True(t, strings.Contains(content, testlog))
}
func TestRedirector(t *testing.T) {
var r redirector
content := getContent(captureOutput(func() {
r.Write([]byte(testlog))
}))
assert.Equal(t, testlog, content)
}
func captureOutput(f func()) string {
atomic.StoreUint32(&initialized, 1)
writer := new(mockWriter)
infoLog = writer
2020-10-01 16:58:07 +08:00
prevLevel := atomic.LoadUint32(&logLevel)
SetLevel(InfoLevel)
2020-07-26 17:09:05 +08:00
f()
2020-10-01 16:58:07 +08:00
SetLevel(prevLevel)
2020-07-26 17:09:05 +08:00
return writer.builder.String()
}
func getContent(jsonStr string) string {
var entry logEntry
json.Unmarshal([]byte(jsonStr), &entry)
2021-08-13 18:28:39 +08:00
return entry.Content.(string)
2020-07-26 17:09:05 +08:00
}