docker_cli_exec_unix_test.go 1.7 KB

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