go-zero/core/logx/syslog_test.go

62 lines
1021 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."
var testobj = map[string]any{"foo": "bar"}
2020-07-26 17:09:05 +08:00
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 {
w := new(mockWriter)
old := writer.Swap(w)
defer writer.Store(old)
2020-07-26 17:09:05 +08:00
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 w.String()
2020-07-26 17:09:05 +08:00
}
func getContent(jsonStr string) string {
var entry map[string]any
2020-07-26 17:09:05 +08:00
json.Unmarshal([]byte(jsonStr), &entry)
val, ok := entry[contentKey]
if !ok {
return ""
}
str, ok := val.(string)
if !ok {
return ""
2022-02-28 23:17:51 +08:00
}
return str
2020-07-26 17:09:05 +08:00
}