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