framework.go 9.6 KB

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