github.com/rsampaio/docker@v0.7.2-0.20150827203920-fdc73cc3fc31/integration-cli/docker_cli_exec_unix_test.go (about)

     1  // +build !windows,!test_no_exec
     2  
     3  package main
     4  
     5  import (
     6  	"bytes"
     7  	"io"
     8  	"os/exec"
     9  	"strings"
    10  	"time"
    11  
    12  	"github.com/go-check/check"
    13  	"github.com/kr/pty"
    14  )
    15  
    16  // regression test for #12546
    17  func (s *DockerSuite) TestExecInteractiveStdinClose(c *check.C) {
    18  	out, _ := dockerCmd(c, "run", "-itd", "busybox", "/bin/cat")
    19  	contID := strings.TrimSpace(out)
    20  
    21  	cmd := exec.Command(dockerBinary, "exec", "-i", contID, "echo", "-n", "hello")
    22  	p, err := pty.Start(cmd)
    23  	if err != nil {
    24  		c.Fatal(err)
    25  	}
    26  
    27  	b := bytes.NewBuffer(nil)
    28  	go io.Copy(b, p)
    29  
    30  	ch := make(chan error)
    31  	go func() { ch <- cmd.Wait() }()
    32  
    33  	select {
    34  	case err := <-ch:
    35  		if err != nil {
    36  			c.Errorf("cmd finished with error %v", err)
    37  		}
    38  		if output := b.String(); strings.TrimSpace(output) != "hello" {
    39  			c.Fatalf("Unexpected output %s", output)
    40  		}
    41  	case <-time.After(1 * time.Second):
    42  		c.Fatal("timed out running docker exec")
    43  	}
    44  }
    45  
    46  func (s *DockerSuite) TestExecTTY(c *check.C) {
    47  	dockerCmd(c, "run", "-d", "--name=test", "busybox", "sh", "-c", "echo hello > /foo && top")
    48  
    49  	cmd := exec.Command(dockerBinary, "exec", "-it", "test", "sh")
    50  	p, err := pty.Start(cmd)
    51  	c.Assert(err, check.IsNil)
    52  	defer p.Close()
    53  
    54  	_, err = p.Write([]byte("cat /foo && exit\n"))
    55  	c.Assert(err, check.IsNil)
    56  
    57  	chErr := make(chan error)
    58  	go func() {
    59  		chErr <- cmd.Wait()
    60  	}()
    61  	select {
    62  	case err := <-chErr:
    63  		c.Assert(err, check.IsNil)
    64  	case <-time.After(3 * time.Second):
    65  		c.Fatal("timeout waiting for exec to exit")
    66  	}
    67  
    68  	buf := make([]byte, 256)
    69  	read, err := p.Read(buf)
    70  	c.Assert(err, check.IsNil)
    71  	c.Assert(bytes.Contains(buf, []byte("hello")), check.Equals, true, check.Commentf(string(buf[:read])))
    72  }