integration-cli/docker_api_attach_test.go
9e37a046
 package main
 
 import (
 	"bytes"
ac6a9ce9
 	"net/http"
9e37a046
 	"os/exec"
475c6531
 	"strings"
ac6cb41d
 	"time"
9e37a046
 
dc944ea7
 	"github.com/go-check/check"
 
9e37a046
 	"code.google.com/p/go.net/websocket"
 )
 
dc944ea7
 func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) {
9e37a046
 	runCmd := exec.Command(dockerBinary, "run", "-dit", "busybox", "cat")
 	out, _, err := runCommandWithOutput(runCmd)
 	if err != nil {
dc944ea7
 		c.Fatalf(out, err)
9e37a046
 	}
 
ac6cb41d
 	rwc, err := sockConn(time.Duration(10 * time.Second))
9e37a046
 	if err != nil {
dc944ea7
 		c.Fatal(err)
9e37a046
 	}
 
475c6531
 	cleanedContainerID := strings.TrimSpace(out)
9e37a046
 	config, err := websocket.NewConfig(
 		"/containers/"+cleanedContainerID+"/attach/ws?stream=1&stdin=1&stdout=1&stderr=1",
 		"http://localhost",
 	)
 	if err != nil {
dc944ea7
 		c.Fatal(err)
9e37a046
 	}
 
 	ws, err := websocket.NewClient(config, rwc)
 	if err != nil {
dc944ea7
 		c.Fatal(err)
9e37a046
 	}
 	defer ws.Close()
 
 	expected := []byte("hello")
 	actual := make([]byte, len(expected))
c7b2632d
 
 	outChan := make(chan error)
9e37a046
 	go func() {
c7b2632d
 		_, err := ws.Read(actual)
 		outChan <- err
 		close(outChan)
9e37a046
 	}()
 
c7b2632d
 	inChan := make(chan error)
9e37a046
 	go func() {
c7b2632d
 		_, err := ws.Write(expected)
 		inChan <- err
 		close(inChan)
 	}()
 
 	select {
 	case err := <-inChan:
 		if err != nil {
dc944ea7
 			c.Fatal(err)
9e37a046
 		}
c7b2632d
 	case <-time.After(5 * time.Second):
 		c.Fatal("Timeout writing to ws")
 	}
9e37a046
 
c7b2632d
 	select {
 	case err := <-outChan:
 		if err != nil {
 			c.Fatal(err)
 		}
 	case <-time.After(5 * time.Second):
 		c.Fatal("Timeout reading from ws")
 	}
9e37a046
 
 	if !bytes.Equal(expected, actual) {
dc944ea7
 		c.Fatal("Expected output on websocket to match input")
9e37a046
 	}
 }
ac6a9ce9
 
 // regression gh14320
 func (s *DockerSuite) TestPostContainersAttachContainerNotFound(c *check.C) {
 	status, body, err := sockRequest("POST", "/containers/doesnotexist/attach", nil)
 	c.Assert(status, check.Equals, http.StatusNotFound)
 	c.Assert(err, check.IsNil)
 	expected := "no such id: doesnotexist\n"
 	if !strings.Contains(string(body), expected) {
 		c.Fatalf("Expected response body to contain %q", expected)
 	}
 }
 
 func (s *DockerSuite) TestGetContainersWsAttachContainerNotFound(c *check.C) {
 	status, body, err := sockRequest("GET", "/containers/doesnotexist/attach/ws", nil)
 	c.Assert(status, check.Equals, http.StatusNotFound)
 	c.Assert(err, check.IsNil)
 	expected := "no such id: doesnotexist\n"
 	if !strings.Contains(string(body), expected) {
 		c.Fatalf("Expected response body to contain %q", expected)
 	}
 }