cli.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. package cli // import "github.com/docker/docker/integration-cli/cli"
  2. import (
  3. "fmt"
  4. "io"
  5. "strings"
  6. "testing"
  7. "time"
  8. "github.com/docker/docker/integration-cli/daemon"
  9. "github.com/docker/docker/integration-cli/environment"
  10. "github.com/pkg/errors"
  11. "gotest.tools/v3/icmd"
  12. )
  13. var testEnv *environment.Execution
  14. // SetTestEnvironment sets a static test environment
  15. // TODO: decouple this package from environment
  16. func SetTestEnvironment(env *environment.Execution) {
  17. testEnv = env
  18. }
  19. // CmdOperator defines functions that can modify a command
  20. type CmdOperator func(*icmd.Cmd) func()
  21. // DockerCmd executes the specified docker command and expect a success
  22. func DockerCmd(t testing.TB, args ...string) *icmd.Result {
  23. t.Helper()
  24. return Docker(Args(args...)).Assert(t, icmd.Success)
  25. }
  26. // BuildCmd executes the specified docker build command and expect a success
  27. func BuildCmd(t testing.TB, name string, cmdOperators ...CmdOperator) *icmd.Result {
  28. t.Helper()
  29. return Docker(Args("build", "-t", name), cmdOperators...).Assert(t, icmd.Success)
  30. }
  31. // InspectCmd executes the specified docker inspect command and expect a success
  32. func InspectCmd(t testing.TB, name string, cmdOperators ...CmdOperator) *icmd.Result {
  33. t.Helper()
  34. return Docker(Args("inspect", name), cmdOperators...).Assert(t, icmd.Success)
  35. }
  36. // WaitRun will wait for the specified container to be running, maximum 5 seconds.
  37. func WaitRun(t testing.TB, name string, cmdOperators ...CmdOperator) {
  38. t.Helper()
  39. waitForInspectResult(t, name, "{{.State.Running}}", "true", 5*time.Second, cmdOperators...)
  40. }
  41. // WaitExited will wait for the specified container to state exit, subject
  42. // to a maximum time limit in seconds supplied by the caller
  43. func WaitExited(t testing.TB, name string, timeout time.Duration, cmdOperators ...CmdOperator) {
  44. t.Helper()
  45. waitForInspectResult(t, name, "{{.State.Status}}", "exited", timeout, cmdOperators...)
  46. }
  47. // waitForInspectResult waits for the specified expression to be equals to the specified expected string in the given time.
  48. func waitForInspectResult(t testing.TB, name, expr, expected string, timeout time.Duration, cmdOperators ...CmdOperator) {
  49. after := time.After(timeout)
  50. args := []string{"inspect", "-f", expr, name}
  51. for {
  52. result := Docker(Args(args...), cmdOperators...)
  53. if result.Error != nil {
  54. if !strings.Contains(strings.ToLower(result.Stderr()), "no such") {
  55. t.Fatalf("error executing docker inspect: %v\n%s",
  56. result.Stderr(), result.Stdout())
  57. }
  58. select {
  59. case <-after:
  60. t.Fatal(result.Error)
  61. default:
  62. time.Sleep(10 * time.Millisecond)
  63. continue
  64. }
  65. }
  66. out := strings.TrimSpace(result.Stdout())
  67. if out == expected {
  68. break
  69. }
  70. select {
  71. case <-after:
  72. t.Fatalf("condition \"%q == %q\" not true in time (%v)", out, expected, timeout)
  73. default:
  74. }
  75. time.Sleep(100 * time.Millisecond)
  76. }
  77. }
  78. // Docker executes the specified docker command
  79. func Docker(cmd icmd.Cmd, cmdOperators ...CmdOperator) *icmd.Result {
  80. for _, op := range cmdOperators {
  81. deferFn := op(&cmd)
  82. if deferFn != nil {
  83. defer deferFn()
  84. }
  85. }
  86. cmd.Command = append([]string{testEnv.DockerBinary()}, cmd.Command...)
  87. if err := validateArgs(cmd.Command...); err != nil {
  88. return &icmd.Result{
  89. Error: err,
  90. }
  91. }
  92. return icmd.RunCmd(cmd)
  93. }
  94. // validateArgs is a checker to ensure tests are not running commands which are
  95. // not supported on platforms. Specifically on Windows this is 'busybox top'.
  96. func validateArgs(args ...string) error {
  97. if testEnv.DaemonInfo.OSType != "windows" {
  98. return nil
  99. }
  100. foundBusybox := -1
  101. for key, value := range args {
  102. if strings.ToLower(value) == "busybox" {
  103. foundBusybox = key
  104. }
  105. if (foundBusybox != -1) && (key == foundBusybox+1) && (strings.ToLower(value) == "top") {
  106. return errors.New("cannot use 'busybox top' in tests on Windows. Use runSleepingContainer()")
  107. }
  108. }
  109. return nil
  110. }
  111. // Format sets the specified format with --format flag
  112. func Format(format string) func(*icmd.Cmd) func() {
  113. return func(cmd *icmd.Cmd) func() {
  114. cmd.Command = append(
  115. []string{cmd.Command[0]},
  116. append([]string{"--format", fmt.Sprintf("{{%s}}", format)}, cmd.Command[1:]...)...,
  117. )
  118. return nil
  119. }
  120. }
  121. // Args build an icmd.Cmd struct from the specified (command and) arguments.
  122. func Args(commandAndArgs ...string) icmd.Cmd {
  123. return icmd.Cmd{Command: commandAndArgs}
  124. }
  125. // Daemon points to the specified daemon
  126. func Daemon(d *daemon.Daemon) func(*icmd.Cmd) func() {
  127. return func(cmd *icmd.Cmd) func() {
  128. cmd.Command = append([]string{"--host", d.Sock()}, cmd.Command...)
  129. return nil
  130. }
  131. }
  132. // WithTimeout sets the timeout for the command to run
  133. func WithTimeout(timeout time.Duration) func(cmd *icmd.Cmd) func() {
  134. return func(cmd *icmd.Cmd) func() {
  135. cmd.Timeout = timeout
  136. return nil
  137. }
  138. }
  139. // WithEnvironmentVariables sets the specified environment variables for the command to run
  140. func WithEnvironmentVariables(envs ...string) func(cmd *icmd.Cmd) func() {
  141. return func(cmd *icmd.Cmd) func() {
  142. cmd.Env = envs
  143. return nil
  144. }
  145. }
  146. // WithFlags sets the specified flags for the command to run
  147. func WithFlags(flags ...string) func(*icmd.Cmd) func() {
  148. return func(cmd *icmd.Cmd) func() {
  149. cmd.Command = append(cmd.Command, flags...)
  150. return nil
  151. }
  152. }
  153. // InDir sets the folder in which the command should be executed
  154. func InDir(path string) func(*icmd.Cmd) func() {
  155. return func(cmd *icmd.Cmd) func() {
  156. cmd.Dir = path
  157. return nil
  158. }
  159. }
  160. // WithStdout sets the standard output writer of the command
  161. func WithStdout(writer io.Writer) func(*icmd.Cmd) func() {
  162. return func(cmd *icmd.Cmd) func() {
  163. cmd.Stdout = writer
  164. return nil
  165. }
  166. }
  167. // WithStdin sets the standard input reader for the command
  168. func WithStdin(stdin io.Reader) func(*icmd.Cmd) func() {
  169. return func(cmd *icmd.Cmd) func() {
  170. cmd.Stdin = stdin
  171. return nil
  172. }
  173. }