A golang package for logging to a file
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
1.7 KiB

  1. package flog
  2. import (
  3. "bufio"
  4. "bytes"
  5. "os"
  6. "strings"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. )
  10. func TestGetOutput(t *testing.T) {
  11. assert.Equal(t, os.Stdout, getOutput())
  12. b := bytes.Buffer{}
  13. Output = &b
  14. assert.Equal(t, &b, getOutput())
  15. Output = nil
  16. }
  17. func TestLogFormat(t *testing.T) {
  18. b := bytes.Buffer{}
  19. MinLevel, Output = LevelDebug, &b
  20. Debug(`Testtt`)
  21. assert.True(t, strings.HasPrefix(b.String(), `debug [`))
  22. b.Reset()
  23. Info(`Testtt`)
  24. assert.True(t, strings.HasPrefix(b.String(), `info [`))
  25. MinLevel, Output = LevelInfo, nil
  26. }
  27. func TestLogLevel(t *testing.T) {
  28. b := bytes.Buffer{}
  29. MinLevel, Output = LevelWarning, &b
  30. Info(`Testtt`)
  31. assert.True(t, b.Len() == 0)
  32. b.Reset()
  33. Warning(`Testtt`)
  34. assert.False(t, b.Len() == 0)
  35. b.Reset()
  36. MinLevel = LevelError
  37. Warning(`Testtt`)
  38. assert.True(t, b.Len() == 0)
  39. b.Reset()
  40. MinLevel, Output = LevelInfo, nil
  41. }
  42. func TestLogf(t *testing.T) {
  43. b := bytes.Buffer{}
  44. Output = &b
  45. Infof(`Test%s-%d`, `tt`, 1)
  46. assert.True(t, strings.Contains(b.String(), `Testtt-1`))
  47. Output = nil
  48. }
  49. func TestStackTrace(t *testing.T) {
  50. b := bytes.Buffer{}
  51. Output = &b
  52. Error(`Testtt`)
  53. checkStackTrace(t, &b, `git.fuyu.moe/Fuyu/flog.TestStackTrace`)
  54. b.Reset()
  55. func() {
  56. defer func() {
  57. v := recover()
  58. if v != nil {
  59. Critical(v)
  60. }
  61. }()
  62. panic(`Testtt`)
  63. }()
  64. checkStackTrace(t, &b, `git.fuyu.moe/Fuyu/flog.TestStackTrace.func1`)
  65. Output = nil
  66. }
  67. func checkStackTrace(t *testing.T, b *bytes.Buffer, f string) {
  68. rdr := bufio.NewReader(b)
  69. _, _ = rdr.ReadBytes('\n')
  70. data, err := rdr.ReadBytes('\n')
  71. if err != nil {
  72. t.Fatal(`Got error while reading:`, err)
  73. }
  74. parts := strings.Split(strings.TrimSpace(string(data)), ` `)
  75. assert.Equal(t, f, parts[0])
  76. }