docker_cli_exec_unix_test.go 1.6 KB

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