syslog_test.go 947 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package logx
  2. import (
  3. "encoding/json"
  4. "log"
  5. "strings"
  6. "sync/atomic"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. )
  10. const testlog = "Stay hungry, stay foolish."
  11. func TestCollectSysLog(t *testing.T) {
  12. CollectSysLog()
  13. content := getContent(captureOutput(func() {
  14. log.Print(testlog)
  15. }))
  16. assert.True(t, strings.Contains(content, testlog))
  17. }
  18. func TestRedirector(t *testing.T) {
  19. var r redirector
  20. content := getContent(captureOutput(func() {
  21. r.Write([]byte(testlog))
  22. }))
  23. assert.Equal(t, testlog, content)
  24. }
  25. func captureOutput(f func()) string {
  26. writer := new(mockWriter)
  27. infoLog = writer
  28. atomic.StoreUint32(&initialized, 1)
  29. prevLevel := atomic.LoadUint32(&logLevel)
  30. SetLevel(InfoLevel)
  31. f()
  32. SetLevel(prevLevel)
  33. return writer.builder.String()
  34. }
  35. func getContent(jsonStr string) string {
  36. var entry logEntry
  37. json.Unmarshal([]byte(jsonStr), &entry)
  38. val, ok := entry.Content.(string)
  39. if ok {
  40. return val
  41. }
  42. return ""
  43. }