logger_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package logger
  2. import (
  3. "fmt"
  4. "sync"
  5. "testing"
  6. golog "github.com/op/go-logging"
  7. )
  8. // TestGetLogs_ReturnsAtMostC guards the documented "up to c entries" contract.
  9. // The loop condition must cap output at c (ERROR entries are queried at "debug"
  10. // level so the level filter passes all of them, isolating the count).
  11. func TestGetLogs_ReturnsAtMostC(t *testing.T) {
  12. logBufferMu.Lock()
  13. logBuffer = nil
  14. logBufferMu.Unlock()
  15. for i := range 5 {
  16. addToBuffer("ERROR", fmt.Sprintf("m%d", i))
  17. }
  18. cases := []struct{ c, want int }{
  19. {0, 0},
  20. {2, 2},
  21. {5, 5},
  22. {10, 5}, // capped at what's available
  23. }
  24. for _, tc := range cases {
  25. if got := GetLogs(tc.c, "debug"); len(got) != tc.want {
  26. t.Errorf("GetLogs(%d) returned %d entries, want %d", tc.c, len(got), tc.want)
  27. }
  28. }
  29. }
  30. // InitLogger replaces the package logger while other goroutines are already
  31. // logging — CI caught that as a data race between InitLogger and Warningf.
  32. func TestInitLoggerConcurrentWithLogging(t *testing.T) {
  33. t.Setenv("XUI_LOG_FOLDER", t.TempDir())
  34. t.Cleanup(CloseLogger)
  35. stop := make(chan struct{})
  36. var logging sync.WaitGroup
  37. logging.Add(1)
  38. go func() {
  39. defer logging.Done()
  40. for {
  41. select {
  42. case <-stop:
  43. return
  44. default:
  45. Warningf("concurrent %s", "log")
  46. }
  47. }
  48. }()
  49. for range 10 {
  50. InitLogger(golog.CRITICAL)
  51. }
  52. close(stop)
  53. logging.Wait()
  54. }