github.com/hernad/nomad@v1.6.112/helper/pool/pool_test.go (about)

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