github.com/zhongdalu/gf@v1.0.0/g/container/gpool/gpool_z_unit_test.go (about)

     1  // Copyright 2019 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  package gpool_test
     8  
     9  import (
    10  	"errors"
    11  	"github.com/zhongdalu/gf/g"
    12  	"testing"
    13  	"time"
    14  
    15  	"github.com/zhongdalu/gf/g/container/gpool"
    16  	"github.com/zhongdalu/gf/g/test/gtest"
    17  )
    18  
    19  var nf gpool.NewFunc = func() (i interface{}, e error) {
    20  	return "hello", nil
    21  }
    22  
    23  var assertIndex int = 0
    24  var ef gpool.ExpireFunc = func(i interface{}) {
    25  	assertIndex++
    26  	gtest.Assert(i, assertIndex)
    27  }
    28  
    29  func Test_Gpool(t *testing.T) {
    30  	gtest.Case(t, func() {
    31  		//
    32  		//expire = 0
    33  		p1 := gpool.New(0, nf)
    34  		p1.Put(1)
    35  		p1.Put(2)
    36  		time.Sleep(1 * time.Second)
    37  		//test won't be timeout
    38  		v1, err1 := p1.Get()
    39  		gtest.Assert(err1, nil)
    40  		gtest.AssertIN(v1, g.Slice{1, 2})
    41  		//test clear
    42  		p1.Clear()
    43  		gtest.Assert(p1.Size(), 0)
    44  		//test newFunc
    45  		v1, err1 = p1.Get()
    46  		gtest.Assert(err1, nil)
    47  		gtest.Assert(v1, "hello")
    48  		//put data again
    49  		p1.Put(3)
    50  		p1.Put(4)
    51  		v1, err1 = p1.Get()
    52  		gtest.Assert(err1, nil)
    53  		gtest.AssertIN(v1, g.Slice{3, 4})
    54  		//test close
    55  		p1.Close()
    56  		v1, err1 = p1.Get()
    57  		gtest.Assert(err1, nil)
    58  		gtest.Assert(v1, "hello")
    59  	})
    60  
    61  	gtest.Case(t, func() {
    62  		//
    63  		//expire > 0
    64  		p2 := gpool.New(2000, nil, ef)
    65  		for index := 0; index < 10; index++ {
    66  			p2.Put(index)
    67  		}
    68  		gtest.Assert(p2.Size(), 10)
    69  		v2, err2 := p2.Get()
    70  		gtest.Assert(err2, nil)
    71  		gtest.Assert(v2, 0)
    72  		//test timeout expireFunc
    73  		time.Sleep(3 * time.Second)
    74  		v2, err2 = p2.Get()
    75  		gtest.Assert(err2, errors.New("pool is empty"))
    76  		gtest.Assert(v2, nil)
    77  		//test close expireFunc
    78  		for index := 0; index < 10; index++ {
    79  			p2.Put(index)
    80  		}
    81  		gtest.Assert(p2.Size(), 10)
    82  		v2, err2 = p2.Get()
    83  		gtest.Assert(err2, nil)
    84  		gtest.Assert(v2, 0)
    85  		assertIndex = 0
    86  		p2.Close()
    87  		time.Sleep(3 * time.Second)
    88  	})
    89  
    90  	gtest.Case(t, func() {
    91  		//
    92  		//expire < 0
    93  		p3 := gpool.New(-1, nil)
    94  		v3, err3 := p3.Get()
    95  		gtest.Assert(err3, errors.New("pool is empty"))
    96  		gtest.Assert(v3, nil)
    97  	})
    98  }