github.com/gogf/gf@v1.16.9/container/gpool/gpool_z_unit_test.go (about)

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