framework.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package e2e
  14. import (
  15. "fmt"
  16. "io"
  17. "io/ioutil"
  18. "net/http"
  19. "os"
  20. "path"
  21. "path/filepath"
  22. "runtime"
  23. "strings"
  24. "testing"
  25. "time"
  26. "github.com/pkg/errors"
  27. "gotest.tools/v3/assert"
  28. is "gotest.tools/v3/assert/cmp"
  29. "gotest.tools/v3/icmd"
  30. "gotest.tools/v3/poll"
  31. "github.com/docker/compose/v2/cmd/compose"
  32. )
  33. var (
  34. // DockerExecutableName is the OS dependent Docker CLI binary name
  35. DockerExecutableName = "docker"
  36. // DockerComposeExecutableName is the OS dependent Docker CLI binary name
  37. DockerComposeExecutableName = "docker-" + compose.PluginName
  38. // DockerScanExecutableName is the OS dependent Docker CLI binary name
  39. DockerScanExecutableName = "docker-scan"
  40. )
  41. func init() {
  42. if runtime.GOOS == "windows" {
  43. DockerExecutableName = DockerExecutableName + ".exe"
  44. DockerComposeExecutableName = DockerComposeExecutableName + ".exe"
  45. DockerScanExecutableName = DockerScanExecutableName + ".exe"
  46. }
  47. }
  48. // CLI is used to wrap the CLI for end to end testing
  49. type CLI struct {
  50. ConfigDir string
  51. }
  52. // NewParallelCLI returns a configured CLI with t.Parallel() set
  53. func NewParallelCLI(t *testing.T) *CLI {
  54. t.Parallel()
  55. return NewCLI(t)
  56. }
  57. // NewCLI returns a CLI to use for E2E tests
  58. func NewCLI(t testing.TB) *CLI {
  59. d, err := ioutil.TempDir("", "")
  60. assert.Check(t, is.Nil(err))
  61. t.Cleanup(func() {
  62. if t.Failed() {
  63. conf, _ := ioutil.ReadFile(filepath.Join(d, "config.json"))
  64. t.Errorf("Config: %s\n", string(conf))
  65. t.Error("Contents of config dir:")
  66. for _, p := range dirContents(d) {
  67. t.Errorf(p)
  68. }
  69. }
  70. _ = os.RemoveAll(d)
  71. })
  72. _ = os.MkdirAll(filepath.Join(d, "cli-plugins"), 0755)
  73. composePlugin, err := findExecutable(DockerComposeExecutableName, []string{"../../bin", "../../../bin"})
  74. if os.IsNotExist(err) {
  75. fmt.Println("WARNING: docker-compose cli-plugin not found")
  76. }
  77. if err == nil {
  78. err = CopyFile(composePlugin, filepath.Join(d, "cli-plugins", DockerComposeExecutableName))
  79. if err != nil {
  80. panic(err)
  81. }
  82. // We don't need a functional scan plugin, but a valid plugin binary
  83. err = CopyFile(composePlugin, filepath.Join(d, "cli-plugins", DockerScanExecutableName))
  84. if err != nil {
  85. panic(err)
  86. }
  87. }
  88. return &CLI{ConfigDir: d}
  89. }
  90. func dirContents(dir string) []string {
  91. var res []string
  92. _ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  93. res = append(res, path)
  94. return nil
  95. })
  96. return res
  97. }
  98. func findExecutable(executableName string, paths []string) (string, error) {
  99. for _, p := range paths {
  100. bin, err := filepath.Abs(path.Join(p, executableName))
  101. if err != nil {
  102. return "", err
  103. }
  104. if _, err := os.Stat(bin); os.IsNotExist(err) {
  105. continue
  106. }
  107. return bin, nil
  108. }
  109. return "", errors.Wrap(os.ErrNotExist, "executable not found")
  110. }
  111. // CopyFile copies a file from a sourceFile to a destinationFile setting permissions to 0755
  112. func CopyFile(sourceFile string, destinationFile string) error {
  113. src, err := os.Open(sourceFile)
  114. if err != nil {
  115. return err
  116. }
  117. // nolint: errcheck
  118. defer src.Close()
  119. dst, err := os.OpenFile(destinationFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
  120. if err != nil {
  121. return err
  122. }
  123. // nolint: errcheck
  124. defer dst.Close()
  125. if _, err = io.Copy(dst, src); err != nil {
  126. return err
  127. }
  128. return err
  129. }
  130. // NewCmd creates a cmd object configured with the test environment set
  131. func (c *CLI) NewCmd(command string, args ...string) icmd.Cmd {
  132. env := append(os.Environ(),
  133. "DOCKER_CONFIG="+c.ConfigDir,
  134. "KUBECONFIG=invalid",
  135. )
  136. return icmd.Cmd{
  137. Command: append([]string{command}, args...),
  138. Env: env,
  139. }
  140. }
  141. // NewCmdWithEnv creates a cmd object configured with the test environment set with additional env vars
  142. func (c *CLI) NewCmdWithEnv(envvars []string, command string, args ...string) icmd.Cmd {
  143. env := append(os.Environ(),
  144. append(envvars,
  145. "DOCKER_CONFIG="+c.ConfigDir,
  146. "KUBECONFIG=invalid")...,
  147. )
  148. return icmd.Cmd{
  149. Command: append([]string{command}, args...),
  150. Env: env,
  151. }
  152. }
  153. // MetricsSocket get the path where test metrics will be sent
  154. func (c *CLI) MetricsSocket() string {
  155. return filepath.Join(c.ConfigDir, "./docker-cli.sock")
  156. }
  157. // NewDockerCmd creates a docker cmd without running it
  158. func (c *CLI) NewDockerCmd(args ...string) icmd.Cmd {
  159. return c.NewCmd(DockerExecutableName, args...)
  160. }
  161. // RunDockerOrExitError runs a docker command and returns a result
  162. func (c *CLI) RunDockerOrExitError(t testing.TB, args ...string) *icmd.Result {
  163. fmt.Printf("\t[%s] docker %s\n", t.Name(), strings.Join(args, " "))
  164. return icmd.RunCmd(c.NewDockerCmd(args...))
  165. }
  166. // RunCmd runs a command, expects no error and returns a result
  167. func (c *CLI) RunCmd(t testing.TB, args ...string) *icmd.Result {
  168. fmt.Printf("\t[%s] %s\n", t.Name(), strings.Join(args, " "))
  169. assert.Assert(t, len(args) >= 1, "require at least one command in parameters")
  170. res := icmd.RunCmd(c.NewCmd(args[0], args[1:]...))
  171. res.Assert(t, icmd.Success)
  172. return res
  173. }
  174. // RunCmdInDir runs a command in a given dir, expects no error and returns a result
  175. func (c *CLI) RunCmdInDir(t testing.TB, dir string, args ...string) *icmd.Result {
  176. fmt.Printf("\t[%s] %s\n", t.Name(), strings.Join(args, " "))
  177. assert.Assert(t, len(args) >= 1, "require at least one command in parameters")
  178. cmd := c.NewCmd(args[0], args[1:]...)
  179. cmd.Dir = dir
  180. res := icmd.RunCmd(cmd)
  181. res.Assert(t, icmd.Success)
  182. return res
  183. }
  184. // RunDockerCmd runs a docker command, expects no error and returns a result
  185. func (c *CLI) RunDockerCmd(t testing.TB, args ...string) *icmd.Result {
  186. if len(args) > 0 && args[0] == compose.PluginName {
  187. t.Fatal("This test called 'RunDockerCmd' for 'compose'. Please prefer 'RunDockerComposeCmd' to be able to test as a plugin and standalone")
  188. }
  189. res := c.RunDockerOrExitError(t, args...)
  190. res.Assert(t, icmd.Success)
  191. return res
  192. }
  193. // RunDockerComposeCmd runs a docker compose command, expects no error and returns a result
  194. func (c *CLI) RunDockerComposeCmd(t testing.TB, args ...string) *icmd.Result {
  195. res := c.RunDockerComposeCmdNoCheck(t, args...)
  196. res.Assert(t, icmd.Success)
  197. return res
  198. }
  199. // RunDockerComposeCmdNoCheck runs a docker compose command, don't presume of any expectation and returns a result
  200. func (c *CLI) RunDockerComposeCmdNoCheck(t testing.TB, args ...string) *icmd.Result {
  201. if composeStandaloneMode {
  202. composeBinary, err := findExecutable(DockerComposeExecutableName, []string{"../../bin", "../../../bin"})
  203. assert.NilError(t, err)
  204. return icmd.RunCmd(c.NewCmd(composeBinary, args...))
  205. }
  206. args = append([]string{"compose"}, args...)
  207. return icmd.RunCmd(c.NewCmd(DockerExecutableName, args...))
  208. }
  209. // StdoutContains returns a predicate on command result expecting a string in stdout
  210. func StdoutContains(expected string) func(*icmd.Result) bool {
  211. return func(res *icmd.Result) bool {
  212. return strings.Contains(res.Stdout(), expected)
  213. }
  214. }
  215. // WaitForCmdResult try to execute a cmd until resulting output matches given predicate
  216. func (c *CLI) WaitForCmdResult(t testing.TB, command icmd.Cmd, predicate func(*icmd.Result) bool, timeout time.Duration, delay time.Duration) {
  217. assert.Assert(t, timeout.Nanoseconds() > delay.Nanoseconds(), "timeout must be greater than delay")
  218. var res *icmd.Result
  219. checkStopped := func(logt poll.LogT) poll.Result {
  220. fmt.Printf("\t[%s] %s\n", t.Name(), strings.Join(command.Command, " "))
  221. res = icmd.RunCmd(command)
  222. if !predicate(res) {
  223. return poll.Continue("Cmd output did not match requirement: %q", res.Combined())
  224. }
  225. return poll.Success()
  226. }
  227. poll.WaitOn(t, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  228. }
  229. // WaitForCondition wait for predicate to execute to true
  230. func (c *CLI) WaitForCondition(t testing.TB, predicate func() (bool, string), timeout time.Duration, delay time.Duration) {
  231. checkStopped := func(logt poll.LogT) poll.Result {
  232. pass, description := predicate()
  233. if !pass {
  234. return poll.Continue("Condition not met: %q", description)
  235. }
  236. return poll.Success()
  237. }
  238. poll.WaitOn(t, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  239. }
  240. // Lines split output into lines
  241. func Lines(output string) []string {
  242. return strings.Split(strings.TrimSpace(output), "\n")
  243. }
  244. // HTTPGetWithRetry performs an HTTP GET on an `endpoint`, using retryDelay also as a request timeout.
  245. // In the case of an error or the response status is not the expeted one, it retries the same request,
  246. // returning the response body as a string (empty if we could not reach it)
  247. func HTTPGetWithRetry(t testing.TB, endpoint string, expectedStatus int, retryDelay time.Duration, timeout time.Duration) string {
  248. var (
  249. r *http.Response
  250. err error
  251. )
  252. client := &http.Client{
  253. Timeout: retryDelay,
  254. }
  255. fmt.Printf("\t[%s] GET %s\n", t.Name(), endpoint)
  256. checkUp := func(t poll.LogT) poll.Result {
  257. r, err = client.Get(endpoint)
  258. if err != nil {
  259. return poll.Continue("reaching %q: Error %s", endpoint, err.Error())
  260. }
  261. if r.StatusCode == expectedStatus {
  262. return poll.Success()
  263. }
  264. return poll.Continue("reaching %q: %d != %d", endpoint, r.StatusCode, expectedStatus)
  265. }
  266. poll.WaitOn(t, checkUp, poll.WithDelay(retryDelay), poll.WithTimeout(timeout))
  267. if r != nil {
  268. b, err := ioutil.ReadAll(r.Body)
  269. assert.NilError(t, err)
  270. return string(b)
  271. }
  272. return ""
  273. }