syslog_test.go 977 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. w := new(mockWriter)
  27. old := writer.Swap(w)
  28. defer writer.Store(old)
  29. prevLevel := atomic.LoadUint32(&logLevel)
  30. SetLevel(InfoLevel)
  31. f()
  32. SetLevel(prevLevel)
  33. return w.String()
  34. }
  35. func getContent(jsonStr string) string {
  36. var entry map[string]any
  37. json.Unmarshal([]byte(jsonStr), &entry)
  38. val, ok := entry[contentKey]
  39. if !ok {
  40. return ""
  41. }
  42. str, ok := val.(string)
  43. if !ok {
  44. return ""
  45. }
  46. return str
  47. }