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