framework.go 7.6 KB

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