github.com/mailgun/holster/v4@v4.20.0/grpcconn/idpool_test.go (about)

     1  package grpcconn_test
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/mailgun/holster/v4/grpcconn"
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func TestIDPool(t *testing.T) {
    11  	t.Run("Allocate and release", func(t *testing.T) {
    12  		pool := grpcconn.NewIDPool()
    13  		id := pool.Allocate()
    14  		assert.Equal(t, 1, int(id))
    15  		pool.Release(id)
    16  	})
    17  
    18  	t.Run("Redundant release id ignored", func(t *testing.T) {
    19  		pool := grpcconn.NewIDPool()
    20  		id := pool.Allocate()
    21  		pool.Release(id)
    22  		pool.Release(id)
    23  	})
    24  
    25  	t.Run("Allocate and release all", func(t *testing.T) {
    26  		const poolSize = 10
    27  		pool := grpcconn.NewIDPool()
    28  		var ids []grpcconn.ID
    29  
    30  		// Allocate all.
    31  		for i := 0; i < poolSize; i++ {
    32  			id := pool.Allocate()
    33  			assert.Equal(t, i+1, int(id))
    34  			ids = append(ids, id)
    35  		}
    36  
    37  		// Release all.
    38  		for _, id := range ids {
    39  			pool.Release(id)
    40  		}
    41  
    42  		// Allocate all again.
    43  		for i := 0; i < poolSize; i++ {
    44  			id := pool.Allocate()
    45  			// Expect id to reuse original pool of ids.
    46  			assert.LessOrEqual(t, int(id), poolSize)
    47  		}
    48  	})
    49  }