syslog_test.go 898 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. atomic.StoreUint32(&initialized, 1)
  27. writer := new(mockWriter)
  28. infoLog = writer
  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. return entry.Content
  39. }