pool_test.go 1.8 KB

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