cli.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. return Docker(Build(name), cmdOperators...).Assert(t, icmd.Success)
  29. }
  30. // InspectCmd executes the specified docker inspect command and expect a success
  31. func InspectCmd(t testing.TB, name string, cmdOperators ...CmdOperator) *icmd.Result {
  32. return Docker(Inspect(name), cmdOperators...).Assert(t, icmd.Success)
  33. }
  34. // WaitRun will wait for the specified container to be running, maximum 5 seconds.
  35. func WaitRun(t testing.TB, name string, cmdOperators ...CmdOperator) {
  36. WaitForInspectResult(t, name, "{{.State.Running}}", "true", 5*time.Second, cmdOperators...)
  37. }
  38. // WaitExited will wait for the specified container to state exit, subject
  39. // to a maximum time limit in seconds supplied by the caller
  40. func WaitExited(t testing.TB, name string, timeout time.Duration, cmdOperators ...CmdOperator) {
  41. WaitForInspectResult(t, name, "{{.State.Status}}", "exited", timeout, cmdOperators...)
  42. }
  43. // WaitRestart will wait for the specified container to restart once
  44. func WaitRestart(t testing.TB, name string, timeout time.Duration, cmdOperators ...CmdOperator) {
  45. WaitForInspectResult(t, name, "{{.RestartCount}}", "1", 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. appendDocker(&cmd)
  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.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. // Build executes the specified docker build command
  112. func Build(name string) icmd.Cmd {
  113. return icmd.Command("build", "-t", name)
  114. }
  115. // Inspect executes the specified docker inspect command
  116. func Inspect(name string) icmd.Cmd {
  117. return icmd.Command("inspect", name)
  118. }
  119. // Format sets the specified format with --format flag
  120. func Format(format string) func(*icmd.Cmd) func() {
  121. return func(cmd *icmd.Cmd) func() {
  122. cmd.Command = append(
  123. []string{cmd.Command[0]},
  124. append([]string{"--format", fmt.Sprintf("{{%s}}", format)}, cmd.Command[1:]...)...,
  125. )
  126. return nil
  127. }
  128. }
  129. func appendDocker(cmd *icmd.Cmd) {
  130. cmd.Command = append([]string{testEnv.DockerBinary()}, cmd.Command...)
  131. }
  132. // Args build an icmd.Cmd struct from the specified arguments
  133. func Args(args ...string) icmd.Cmd {
  134. switch len(args) {
  135. case 0:
  136. return icmd.Cmd{}
  137. case 1:
  138. return icmd.Command(args[0])
  139. default:
  140. return icmd.Command(args[0], args[1:]...)
  141. }
  142. }
  143. // Daemon points to the specified daemon
  144. func Daemon(d *daemon.Daemon) func(*icmd.Cmd) func() {
  145. return func(cmd *icmd.Cmd) func() {
  146. cmd.Command = append([]string{"--host", d.Sock()}, cmd.Command...)
  147. return nil
  148. }
  149. }
  150. // WithTimeout sets the timeout for the command to run
  151. func WithTimeout(timeout time.Duration) func(cmd *icmd.Cmd) func() {
  152. return func(cmd *icmd.Cmd) func() {
  153. cmd.Timeout = timeout
  154. return nil
  155. }
  156. }
  157. // WithEnvironmentVariables sets the specified environment variables for the command to run
  158. func WithEnvironmentVariables(envs ...string) func(cmd *icmd.Cmd) func() {
  159. return func(cmd *icmd.Cmd) func() {
  160. cmd.Env = envs
  161. return nil
  162. }
  163. }
  164. // WithFlags sets the specified flags for the command to run
  165. func WithFlags(flags ...string) func(*icmd.Cmd) func() {
  166. return func(cmd *icmd.Cmd) func() {
  167. cmd.Command = append(cmd.Command, flags...)
  168. return nil
  169. }
  170. }
  171. // InDir sets the folder in which the command should be executed
  172. func InDir(path string) func(*icmd.Cmd) func() {
  173. return func(cmd *icmd.Cmd) func() {
  174. cmd.Dir = path
  175. return nil
  176. }
  177. }
  178. // WithStdout sets the standard output writer of the command
  179. func WithStdout(writer io.Writer) func(*icmd.Cmd) func() {
  180. return func(cmd *icmd.Cmd) func() {
  181. cmd.Stdout = writer
  182. return nil
  183. }
  184. }
  185. // WithStdin sets the standard input reader for the command
  186. func WithStdin(stdin io.Reader) func(*icmd.Cmd) func() {
  187. return func(cmd *icmd.Cmd) func() {
  188. cmd.Stdin = stdin
  189. return nil
  190. }
  191. }