syslog_test.go 1021 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. var testobj = map[string]any{"foo": "bar"}
  12. func TestCollectSysLog(t *testing.T) {
  13. CollectSysLog()
  14. content := getContent(captureOutput(func() {
  15. log.Print(testlog)
  16. }))
  17. assert.True(t, strings.Contains(content, testlog))
  18. }
  19. func TestRedirector(t *testing.T) {
  20. var r redirector
  21. content := getContent(captureOutput(func() {
  22. r.Write([]byte(testlog))
  23. }))
  24. assert.Equal(t, testlog, content)
  25. }
  26. func captureOutput(f func()) string {
  27. w := new(mockWriter)
  28. old := writer.Swap(w)
  29. defer writer.Store(old)
  30. prevLevel := atomic.LoadUint32(&logLevel)
  31. SetLevel(InfoLevel)
  32. f()
  33. SetLevel(prevLevel)
  34. return w.String()
  35. }
  36. func getContent(jsonStr string) string {
  37. var entry map[string]any
  38. json.Unmarshal([]byte(jsonStr), &entry)
  39. val, ok := entry[contentKey]
  40. if !ok {
  41. return ""
  42. }
  43. str, ok := val.(string)
  44. if !ok {
  45. return ""
  46. }
  47. return str
  48. }