github.com/chwjbn/xclash@v0.2.0/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 { 12 initial := -1 13 return func(context.Context) (interface{}, error) { 14 initial++ 15 return initial, nil 16 } 17 } 18 19 func TestPool_Basic(t *testing.T) { 20 g := lg() 21 pool := New(g) 22 23 elm, _ := pool.Get() 24 assert.Equal(t, 0, elm.(int)) 25 pool.Put(elm) 26 elm, _ = pool.Get() 27 assert.Equal(t, 0, elm.(int)) 28 elm, _ = pool.Get() 29 assert.Equal(t, 1, elm.(int)) 30 } 31 32 func TestPool_MaxSize(t *testing.T) { 33 g := lg() 34 size := 5 35 pool := New(g, WithSize(size)) 36 37 items := []interface{}{} 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.(int)) 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.(int), elm.(int)) 56 } 57 } 58 59 func TestPool_MaxAge(t *testing.T) { 60 g := lg() 61 pool := New(g, WithAge(20)) 62 63 elm, _ := pool.Get() 64 pool.Put(elm) 65 66 elm, _ = pool.Get() 67 assert.Equal(t, 0, elm.(int)) 68 pool.Put(elm) 69 70 time.Sleep(time.Millisecond * 22) 71 elm, _ = pool.Get() 72 assert.Equal(t, 1, elm.(int)) 73 }