github.com/cloudfoundry-attic/ltc@v0.0.0-20151123212628-098adc7919fc/ssh/listener_test.go (about)

     1  package ssh_test
     2  
     3  import (
     4  	"io/ioutil"
     5  	"net"
     6  
     7  	"github.com/cloudfoundry-incubator/ltc/ssh"
     8  
     9  	. "github.com/onsi/ginkgo"
    10  	. "github.com/onsi/gomega"
    11  )
    12  
    13  var _ = Describe("Listener", func() {
    14  	var listener *ssh.ChannelListener
    15  
    16  	BeforeEach(func() {
    17  		listener = &ssh.ChannelListener{}
    18  	})
    19  
    20  	Describe("#Listen", func() {
    21  		It("should accept connections", func() {
    22  			address := freeAddress()
    23  			acceptChan, _ := listener.Listen("tcp", address)
    24  
    25  			writeConn, err := net.Dial("tcp", address)
    26  			Expect(err).NotTo(HaveOccurred())
    27  
    28  			readConn := <-acceptChan
    29  
    30  			writeConn.Write([]byte("abcd"))
    31  			writeConn.Close()
    32  			Expect(ioutil.ReadAll(readConn)).To(Equal([]byte("abcd")))
    33  		})
    34  
    35  		Context("when we fail to listen", func() {
    36  			It("should return an error on the returned error channel", func() {
    37  				_, errChan := listener.Listen("bad network", "bad address")
    38  				Expect(<-errChan).To(MatchError("listen bad network: unknown network bad network"))
    39  			})
    40  		})
    41  	})
    42  })
    43  
    44  func freeAddress() string {
    45  	listener, err := net.Listen("tcp", "127.0.0.1:0")
    46  	if err != nil {
    47  		Fail(err.Error())
    48  	}
    49  	defer listener.Close()
    50  	return listener.Addr().String()
    51  }