github.com/Ilhicas/nomad@v1.0.4-0.20210304152020-e86851182bc3/helper/pool/pool_test.go (about)

     1  package pool
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/hashicorp/nomad/helper/freeport"
    10  	"github.com/hashicorp/nomad/helper/testlog"
    11  	"github.com/hashicorp/nomad/nomad/structs"
    12  	"github.com/hashicorp/yamux"
    13  	"github.com/stretchr/testify/require"
    14  )
    15  
    16  func newTestPool(t *testing.T) *ConnPool {
    17  	l := testlog.HCLogger(t)
    18  	p := NewPool(l, 1*time.Minute, 10, nil)
    19  	return p
    20  }
    21  
    22  func TestConnPool_ConnListener(t *testing.T) {
    23  	require := require.New(t)
    24  
    25  	ports := freeport.MustTake(1)
    26  	defer freeport.Return(ports)
    27  
    28  	addrStr := fmt.Sprintf("127.0.0.1:%d", ports[0])
    29  	addr, err := net.ResolveTCPAddr("tcp", addrStr)
    30  	require.Nil(err)
    31  
    32  	exitCh := make(chan struct{})
    33  	defer close(exitCh)
    34  	go func() {
    35  		ln, err := net.Listen("tcp", addrStr)
    36  		require.Nil(err)
    37  		defer ln.Close()
    38  		conn, _ := ln.Accept()
    39  		defer conn.Close()
    40  
    41  		<-exitCh
    42  	}()
    43  
    44  	time.Sleep(100 * time.Millisecond)
    45  
    46  	// Create a test pool
    47  	pool := newTestPool(t)
    48  
    49  	// Setup a listener
    50  	c := make(chan *yamux.Session, 1)
    51  	pool.SetConnListener(c)
    52  
    53  	// Make an RPC
    54  	_, err = pool.acquire("test", addr, structs.ApiMajorVersion)
    55  	require.Nil(err)
    56  
    57  	// Assert we get a connection.
    58  	select {
    59  	case <-c:
    60  	case <-time.After(100 * time.Millisecond):
    61  		t.Fatalf("timeout")
    62  	}
    63  
    64  	// Test that the channel is closed when the pool shuts down.
    65  	require.Nil(pool.Shutdown())
    66  	_, ok := <-c
    67  	require.False(ok)
    68  }