pool_test.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package pool
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func lg() Factory[int] {
  9. initial := -1
  10. return func(context.Context) (int, error) {
  11. initial++
  12. return initial, nil
  13. }
  14. }
  15. func TestPool_Basic(t *testing.T) {
  16. g := lg()
  17. pool := New[int](g)
  18. elm, _ := pool.Get()
  19. assert.Equal(t, 0, elm)
  20. pool.Put(elm)
  21. elm, _ = pool.Get()
  22. assert.Equal(t, 0, elm)
  23. elm, _ = pool.Get()
  24. assert.Equal(t, 1, elm)
  25. }
  26. func TestPool_MaxSize(t *testing.T) {
  27. g := lg()
  28. size := 5
  29. pool := New[int](g, WithSize[int](size))
  30. var items []int
  31. for i := 0; i < size; i++ {
  32. item, _ := pool.Get()
  33. items = append(items, item)
  34. }
  35. extra, _ := pool.Get()
  36. assert.Equal(t, size, extra)
  37. for _, item := range items {
  38. pool.Put(item)
  39. }
  40. pool.Put(extra)
  41. for _, item := range items {
  42. elm, _ := pool.Get()
  43. assert.Equal(t, item, elm)
  44. }
  45. }
  46. func TestPool_MaxAge(t *testing.T) {
  47. g := lg()
  48. pool := New[int](g, WithAge[int](20))
  49. elm, _ := pool.Get()
  50. pool.Put(elm)
  51. elm, _ = pool.Get()
  52. assert.Equal(t, 0, elm)
  53. pool.Put(elm)
  54. time.Sleep(time.Millisecond * 22)
  55. elm, _ = pool.Get()
  56. assert.Equal(t, 1, elm)
  57. }