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."
|
|
|
|
|
2023-05-08 17:16:44 +08:00
|
|
|
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 {
|
2022-05-03 17:34:26 +08:00
|
|
|
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
|
|
|
|
2022-05-14 19:58:17 +08:00
|
|
|
return w.String()
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func getContent(jsonStr string) string {
|
2023-01-24 16:32:02 +08:00
|
|
|
var entry map[string]any
|
2020-07-26 17:09:05 +08:00
|
|
|
json.Unmarshal([]byte(jsonStr), &entry)
|
2022-09-17 22:48:24 +08:00
|
|
|
|
|
|
|
val, ok := entry[contentKey]
|
|
|
|
if !ok {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
str, ok := val.(string)
|
|
|
|
if !ok {
|
|
|
|
return ""
|
2022-02-28 23:17:51 +08:00
|
|
|
}
|
2022-09-17 22:48:24 +08:00
|
|
|
|
|
|
|
return str
|
2020-07-26 17:09:05 +08:00
|
|
|
}
|