pool_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. package syncx
  2. import (
  3. "sync"
  4. "sync/atomic"
  5. "testing"
  6. "time"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/wuntsong-org/go-zero-plus/core/lang"
  9. )
  10. const limit = 10
  11. func TestPoolGet(t *testing.T) {
  12. stack := NewPool(limit, create, destroy)
  13. ch := make(chan lang.PlaceholderType)
  14. for i := 0; i < limit; i++ {
  15. var fail AtomicBool
  16. go func() {
  17. v := stack.Get()
  18. if v.(int) != 1 {
  19. fail.Set(true)
  20. }
  21. ch <- lang.Placeholder
  22. }()
  23. select {
  24. case <-ch:
  25. case <-time.After(time.Second):
  26. t.Fail()
  27. }
  28. if fail.True() {
  29. t.Fatal("unmatch value")
  30. }
  31. }
  32. }
  33. func TestPoolPopTooMany(t *testing.T) {
  34. stack := NewPool(limit, create, destroy)
  35. ch := make(chan lang.PlaceholderType, 1)
  36. for i := 0; i < limit; i++ {
  37. var wait sync.WaitGroup
  38. wait.Add(1)
  39. go func() {
  40. stack.Get()
  41. ch <- lang.Placeholder
  42. wait.Done()
  43. }()
  44. wait.Wait()
  45. select {
  46. case <-ch:
  47. default:
  48. t.Fail()
  49. }
  50. }
  51. var waitGroup, pushWait sync.WaitGroup
  52. waitGroup.Add(1)
  53. pushWait.Add(1)
  54. go func() {
  55. pushWait.Done()
  56. stack.Get()
  57. waitGroup.Done()
  58. }()
  59. pushWait.Wait()
  60. stack.Put(1)
  61. waitGroup.Wait()
  62. }
  63. func TestPoolPopFirst(t *testing.T) {
  64. var value int32
  65. stack := NewPool(limit, func() any {
  66. return atomic.AddInt32(&value, 1)
  67. }, destroy)
  68. for i := 0; i < 100; i++ {
  69. v := stack.Get().(int32)
  70. assert.Equal(t, 1, int(v))
  71. stack.Put(v)
  72. }
  73. }
  74. func TestPoolWithMaxAge(t *testing.T) {
  75. var value int32
  76. stack := NewPool(limit, func() any {
  77. return atomic.AddInt32(&value, 1)
  78. }, destroy, WithMaxAge(time.Millisecond))
  79. v1 := stack.Get().(int32)
  80. // put nil should not matter
  81. stack.Put(nil)
  82. stack.Put(v1)
  83. time.Sleep(time.Millisecond * 10)
  84. v2 := stack.Get().(int32)
  85. assert.NotEqual(t, v1, v2)
  86. }
  87. func TestNewPoolPanics(t *testing.T) {
  88. assert.Panics(t, func() {
  89. NewPool(0, create, destroy)
  90. })
  91. }
  92. func create() any {
  93. return 1
  94. }
  95. func destroy(_ any) {
  96. }