logger_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. stop := make(chan struct{})
  35. var logging sync.WaitGroup
  36. logging.Add(1)
  37. go func() {
  38. defer logging.Done()
  39. for {
  40. select {
  41. case <-stop:
  42. return
  43. default:
  44. Warningf("concurrent %s", "log")
  45. }
  46. }
  47. }()
  48. for range 10 {
  49. InitLogger(golog.CRITICAL)
  50. }
  51. close(stop)
  52. logging.Wait()
  53. }