github.com/webwurst/docker@v1.7.0/integration-cli/docker_api_attach_test.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"os/exec"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/go-check/check"
    10  
    11  	"code.google.com/p/go.net/websocket"
    12  )
    13  
    14  func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) {
    15  	runCmd := exec.Command(dockerBinary, "run", "-dit", "busybox", "cat")
    16  	out, _, err := runCommandWithOutput(runCmd)
    17  	if err != nil {
    18  		c.Fatalf(out, err)
    19  	}
    20  
    21  	rwc, err := sockConn(time.Duration(10 * time.Second))
    22  	if err != nil {
    23  		c.Fatal(err)
    24  	}
    25  
    26  	cleanedContainerID := strings.TrimSpace(out)
    27  	config, err := websocket.NewConfig(
    28  		"/containers/"+cleanedContainerID+"/attach/ws?stream=1&stdin=1&stdout=1&stderr=1",
    29  		"http://localhost",
    30  	)
    31  	if err != nil {
    32  		c.Fatal(err)
    33  	}
    34  
    35  	ws, err := websocket.NewClient(config, rwc)
    36  	if err != nil {
    37  		c.Fatal(err)
    38  	}
    39  	defer ws.Close()
    40  
    41  	expected := []byte("hello")
    42  	actual := make([]byte, len(expected))
    43  
    44  	outChan := make(chan error)
    45  	go func() {
    46  		_, err := ws.Read(actual)
    47  		outChan <- err
    48  		close(outChan)
    49  	}()
    50  
    51  	inChan := make(chan error)
    52  	go func() {
    53  		_, err := ws.Write(expected)
    54  		inChan <- err
    55  		close(inChan)
    56  	}()
    57  
    58  	select {
    59  	case err := <-inChan:
    60  		if err != nil {
    61  			c.Fatal(err)
    62  		}
    63  	case <-time.After(5 * time.Second):
    64  		c.Fatal("Timeout writing to ws")
    65  	}
    66  
    67  	select {
    68  	case err := <-outChan:
    69  		if err != nil {
    70  			c.Fatal(err)
    71  		}
    72  	case <-time.After(5 * time.Second):
    73  		c.Fatal("Timeout reading from ws")
    74  	}
    75  
    76  	if !bytes.Equal(expected, actual) {
    77  		c.Fatal("Expected output on websocket to match input")
    78  	}
    79  }