utils.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package docker
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "strings"
  7. "testing"
  8. "time"
  9. "github.com/docker/docker/daemon"
  10. )
  11. func closeWrap(args ...io.Closer) error {
  12. e := false
  13. ret := fmt.Errorf("Error closing elements")
  14. for _, c := range args {
  15. if err := c.Close(); err != nil {
  16. e = true
  17. ret = fmt.Errorf("%s\n%s", ret, err)
  18. }
  19. }
  20. if e {
  21. return ret
  22. }
  23. return nil
  24. }
  25. func waitContainerStart(t *testing.T, timeout time.Duration) *daemon.Container {
  26. var container *daemon.Container
  27. setTimeout(t, "Waiting for the container to be started timed out", timeout, func() {
  28. for {
  29. l := globalDaemon.List()
  30. if len(l) == 1 && l[0].IsRunning() {
  31. container = l[0]
  32. break
  33. }
  34. time.Sleep(10 * time.Millisecond)
  35. }
  36. })
  37. if container == nil {
  38. t.Fatal("An error occurred while waiting for the container to start")
  39. }
  40. return container
  41. }
  42. func setTimeout(t *testing.T, msg string, d time.Duration, f func()) {
  43. c := make(chan bool)
  44. // Make sure we are not too long
  45. go func() {
  46. time.Sleep(d)
  47. c <- true
  48. }()
  49. go func() {
  50. f()
  51. c <- false
  52. }()
  53. if <-c && msg != "" {
  54. t.Fatal(msg)
  55. }
  56. }
  57. func expectPipe(expected string, r io.Reader) error {
  58. o, err := bufio.NewReader(r).ReadString('\n')
  59. if err != nil {
  60. return err
  61. }
  62. if strings.Trim(o, " \r\n") != expected {
  63. return fmt.Errorf("Unexpected output. Expected [%s], received [%s]", expected, o)
  64. }
  65. return nil
  66. }
  67. func assertPipe(input, output string, r io.Reader, w io.Writer, count int) error {
  68. for i := 0; i < count; i++ {
  69. if _, err := w.Write([]byte(input)); err != nil {
  70. return err
  71. }
  72. if err := expectPipe(output, r); err != nil {
  73. return err
  74. }
  75. }
  76. return nil
  77. }