framework.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  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. // MetricsSocket get the path where test metrics will be sent
  144. func (c *E2eCLI) MetricsSocket() string {
  145. return filepath.Join(c.ConfigDir, "./docker-cli.sock")
  146. }
  147. // NewDockerCmd creates a docker cmd without running it
  148. func (c *E2eCLI) NewDockerCmd(args ...string) icmd.Cmd {
  149. return c.NewCmd(DockerExecutableName, args...)
  150. }
  151. // RunDockerOrExitError runs a docker command and returns a result
  152. func (c *E2eCLI) RunDockerOrExitError(args ...string) *icmd.Result {
  153. fmt.Printf("\t[%s] docker %s\n", c.test.Name(), strings.Join(args, " "))
  154. return icmd.RunCmd(c.NewDockerCmd(args...))
  155. }
  156. // RunCmd runs a command, expects no error and returns a result
  157. func (c *E2eCLI) RunCmd(args ...string) *icmd.Result {
  158. fmt.Printf("\t[%s] %s\n", c.test.Name(), strings.Join(args, " "))
  159. assert.Assert(c.test, len(args) >= 1, "require at least one command in parameters")
  160. res := icmd.RunCmd(c.NewCmd(args[0], args[1:]...))
  161. res.Assert(c.test, icmd.Success)
  162. return res
  163. }
  164. // RunDockerCmd runs a docker command, expects no error and returns a result
  165. func (c *E2eCLI) RunDockerCmd(args ...string) *icmd.Result {
  166. if len(args) > 0 && args[0] == compose.PluginName {
  167. c.test.Fatal("This test called 'RunDockerCmd' for 'compose'. Please prefer 'RunDockerComposeCmd' to be able to test as a plugin and standalone")
  168. }
  169. res := c.RunDockerOrExitError(args...)
  170. res.Assert(c.test, icmd.Success)
  171. return res
  172. }
  173. // RunDockerComposeCmd runs a docker compose command, expects no error and returns a result
  174. func (c *E2eCLI) RunDockerComposeCmd(args ...string) *icmd.Result {
  175. if composeStandaloneMode {
  176. composeBinary, err := findExecutable(DockerComposeExecutableName, []string{"../../bin", "../../../bin"})
  177. assert.NilError(c.test, err)
  178. res := icmd.RunCmd(c.NewCmd(composeBinary, args...))
  179. res.Assert(c.test, icmd.Success)
  180. return res
  181. }
  182. args = append([]string{"compose"}, args...)
  183. res := icmd.RunCmd(c.NewCmd(DockerExecutableName, args...))
  184. res.Assert(c.test, icmd.Success)
  185. return res
  186. }
  187. // StdoutContains returns a predicate on command result expecting a string in stdout
  188. func StdoutContains(expected string) func(*icmd.Result) bool {
  189. return func(res *icmd.Result) bool {
  190. return strings.Contains(res.Stdout(), expected)
  191. }
  192. }
  193. // WaitForCmdResult try to execute a cmd until resulting output matches given predicate
  194. func (c *E2eCLI) WaitForCmdResult(command icmd.Cmd, predicate func(*icmd.Result) bool, timeout time.Duration, delay time.Duration) {
  195. assert.Assert(c.test, timeout.Nanoseconds() > delay.Nanoseconds(), "timeout must be greater than delay")
  196. var res *icmd.Result
  197. checkStopped := func(logt poll.LogT) poll.Result {
  198. fmt.Printf("\t[%s] %s\n", c.test.Name(), strings.Join(command.Command, " "))
  199. res = icmd.RunCmd(command)
  200. if !predicate(res) {
  201. return poll.Continue("Cmd output did not match requirement: %q", res.Combined())
  202. }
  203. return poll.Success()
  204. }
  205. poll.WaitOn(c.test, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  206. }
  207. // WaitForCondition wait for predicate to execute to true
  208. func (c *E2eCLI) WaitForCondition(predicate func() (bool, string), timeout time.Duration, delay time.Duration) {
  209. checkStopped := func(logt poll.LogT) poll.Result {
  210. pass, description := predicate()
  211. if !pass {
  212. return poll.Continue("Condition not met: %q", description)
  213. }
  214. return poll.Success()
  215. }
  216. poll.WaitOn(c.test, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  217. }
  218. // Lines split output into lines
  219. func Lines(output string) []string {
  220. return strings.Split(strings.TrimSpace(output), "\n")
  221. }
  222. // HTTPGetWithRetry performs an HTTP GET on an `endpoint`, using retryDelay also as a request timeout.
  223. // In the case of an error or the response status is not the expeted one, it retries the same request,
  224. // returning the response body as a string (empty if we could not reach it)
  225. func HTTPGetWithRetry(t *testing.T, endpoint string, expectedStatus int, retryDelay time.Duration, timeout time.Duration) string {
  226. var (
  227. r *http.Response
  228. err error
  229. )
  230. client := &http.Client{
  231. Timeout: retryDelay,
  232. }
  233. fmt.Printf("\t[%s] GET %s\n", t.Name(), endpoint)
  234. checkUp := func(t poll.LogT) poll.Result {
  235. r, err = client.Get(endpoint)
  236. if err != nil {
  237. return poll.Continue("reaching %q: Error %s", endpoint, err.Error())
  238. }
  239. if r.StatusCode == expectedStatus {
  240. return poll.Success()
  241. }
  242. return poll.Continue("reaching %q: %d != %d", endpoint, r.StatusCode, expectedStatus)
  243. }
  244. poll.WaitOn(t, checkUp, poll.WithDelay(retryDelay), poll.WithTimeout(timeout))
  245. if r != nil {
  246. b, err := ioutil.ReadAll(r.Body)
  247. assert.NilError(t, err)
  248. return string(b)
  249. }
  250. return ""
  251. }