limitedexecutor_test.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package logx
  2. import (
  3. "sync/atomic"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. "github.com/wuntsong-org/go-zero-plus/core/timex"
  8. )
  9. func TestLimitedExecutor_logOrDiscard(t *testing.T) {
  10. tests := []struct {
  11. name string
  12. threshold time.Duration
  13. lastTime time.Duration
  14. discarded uint32
  15. executed bool
  16. }{
  17. {
  18. name: "nil executor",
  19. executed: true,
  20. },
  21. {
  22. name: "regular",
  23. threshold: time.Hour,
  24. lastTime: timex.Now(),
  25. discarded: 10,
  26. executed: false,
  27. },
  28. {
  29. name: "slow",
  30. threshold: time.Duration(1),
  31. lastTime: -1000,
  32. discarded: 10,
  33. executed: true,
  34. },
  35. }
  36. for _, test := range tests {
  37. test := test
  38. t.Run(test.name, func(t *testing.T) {
  39. t.Parallel()
  40. executor := newLimitedExecutor(0)
  41. executor.threshold = test.threshold
  42. executor.discarded = test.discarded
  43. executor.lastTime.Set(test.lastTime)
  44. var run int32
  45. executor.logOrDiscard(func() {
  46. atomic.AddInt32(&run, 1)
  47. })
  48. if test.executed {
  49. assert.Equal(t, int32(1), atomic.LoadInt32(&run))
  50. } else {
  51. assert.Equal(t, int32(0), atomic.LoadInt32(&run))
  52. assert.Equal(t, test.discarded+1, atomic.LoadUint32(&executor.discarded))
  53. }
  54. })
  55. }
  56. }