github.com/smithx10/nomad@v0.9.1-rc1/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/consul/lib/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.GetT(t, 1)
    26  	addrStr := fmt.Sprintf("127.0.0.1:%d", ports[0])
    27  	addr, err := net.ResolveTCPAddr("tcp", addrStr)
    28  	require.Nil(err)
    29  
    30  	exitCh := make(chan struct{})
    31  	defer close(exitCh)
    32  	go func() {
    33  		ln, err := net.Listen("tcp", addrStr)
    34  		require.Nil(err)
    35  		defer ln.Close()
    36  		conn, _ := ln.Accept()
    37  		defer conn.Close()
    38  
    39  		<-exitCh
    40  	}()
    41  
    42  	time.Sleep(100 * time.Millisecond)
    43  
    44  	// Create a test pool
    45  	pool := newTestPool(t)
    46  
    47  	// Setup a listener
    48  	c := make(chan *yamux.Session, 1)
    49  	pool.SetConnListener(c)
    50  
    51  	// Make an RPC
    52  	_, err = pool.acquire("test", addr, structs.ApiMajorVersion)
    53  	require.Nil(err)
    54  
    55  	// Assert we get a connection.
    56  	select {
    57  	case <-c:
    58  	case <-time.After(100 * time.Millisecond):
    59  		t.Fatalf("timeout")
    60  	}
    61  
    62  	// Test that the channel is closed when the pool shuts down.
    63  	require.Nil(pool.Shutdown())
    64  	_, ok := <-c
    65  	require.False(ok)
    66  }