framework.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. "errors"
  16. "fmt"
  17. "io"
  18. "io/ioutil"
  19. "net/http"
  20. "os"
  21. "os/exec"
  22. "path"
  23. "path/filepath"
  24. "runtime"
  25. "strings"
  26. "testing"
  27. "time"
  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. existingExectuableName = "com.docker.cli"
  37. )
  38. func init() {
  39. if runtime.GOOS == "windows" {
  40. DockerExecutableName = DockerExecutableName + ".exe"
  41. existingExectuableName = existingExectuableName + ".exe"
  42. }
  43. }
  44. // E2eCLI is used to wrap the CLI for end to end testing
  45. // nolint stutter
  46. type E2eCLI struct {
  47. BinDir string
  48. ConfigDir string
  49. test *testing.T
  50. }
  51. // NewParallelE2eCLI returns a configured TestE2eCLI with t.Parallel() set
  52. func NewParallelE2eCLI(t *testing.T, binDir string) *E2eCLI {
  53. t.Parallel()
  54. return newE2eCLI(t, binDir)
  55. }
  56. // NewE2eCLI returns a configured TestE2eCLI
  57. func NewE2eCLI(t *testing.T, binDir string) *E2eCLI {
  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. composePluginFile := "docker-compose"
  76. if runtime.GOOS == "windows" {
  77. composePluginFile += ".exe"
  78. }
  79. composePlugin, _ := findExecutable(composePluginFile, []string{"../../bin", "../../../bin"})
  80. err = CopyFile(composePlugin, filepath.Join(d, "cli-plugins", composePluginFile))
  81. if err != nil {
  82. panic(err)
  83. }
  84. return &E2eCLI{binDir, d, t}
  85. }
  86. func dirContents(dir string) []string {
  87. res := []string{}
  88. _ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  89. res = append(res, filepath.Join(dir, path))
  90. return nil
  91. })
  92. return res
  93. }
  94. // SetupExistingCLI copies the existing CLI in a temporary directory so that the
  95. // new CLI can be configured to use it
  96. func SetupExistingCLI() (string, func(), error) {
  97. p, err := exec.LookPath(existingExectuableName)
  98. if err != nil {
  99. p, err = exec.LookPath(DockerExecutableName)
  100. if err != nil {
  101. return "", nil, errors.New("existing CLI not found in PATH")
  102. }
  103. }
  104. d, err := ioutil.TempDir("", "")
  105. if err != nil {
  106. return "", nil, err
  107. }
  108. if err := CopyFile(p, filepath.Join(d, existingExectuableName)); err != nil {
  109. return "", nil, err
  110. }
  111. bin, err := findExecutable(DockerExecutableName, []string{"../../bin", "../../../bin"})
  112. if err != nil {
  113. return "", nil, err
  114. }
  115. if err := CopyFile(bin, filepath.Join(d, DockerExecutableName)); err != nil {
  116. return "", nil, err
  117. }
  118. cleanup := func() {
  119. _ = os.RemoveAll(d)
  120. }
  121. return d, cleanup, nil
  122. }
  123. func findExecutable(executableName string, paths []string) (string, error) {
  124. for _, p := range paths {
  125. bin, err := filepath.Abs(path.Join(p, executableName))
  126. if err != nil {
  127. return "", err
  128. }
  129. if _, err := os.Stat(bin); os.IsNotExist(err) {
  130. continue
  131. }
  132. return bin, nil
  133. }
  134. return "", errors.New("executable not found")
  135. }
  136. // CopyFile copies a file from a sourceFile to a destinationFile setting permissions to 0755
  137. func CopyFile(sourceFile string, destinationFile string) error {
  138. src, err := os.Open(sourceFile)
  139. if err != nil {
  140. return err
  141. }
  142. // nolint: errcheck
  143. defer src.Close()
  144. dst, err := os.OpenFile(destinationFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
  145. if err != nil {
  146. return err
  147. }
  148. // nolint: errcheck
  149. defer dst.Close()
  150. if _, err = io.Copy(dst, src); err != nil {
  151. return err
  152. }
  153. return err
  154. }
  155. // NewCmd creates a cmd object configured with the test environment set
  156. func (c *E2eCLI) NewCmd(command string, args ...string) icmd.Cmd {
  157. env := append(os.Environ(),
  158. "DOCKER_CONFIG="+c.ConfigDir,
  159. "KUBECONFIG=invalid",
  160. "TEST_METRICS_SOCKET="+c.MetricsSocket(),
  161. "PATH="+c.PathEnvVar(),
  162. )
  163. return icmd.Cmd{
  164. Command: append([]string{command}, args...),
  165. Env: env,
  166. }
  167. }
  168. // MetricsSocket get the path where test metrics will be sent
  169. func (c *E2eCLI) MetricsSocket() string {
  170. return filepath.Join(c.ConfigDir, "./docker-cli.sock")
  171. }
  172. // NewDockerCmd creates a docker cmd without running it
  173. func (c *E2eCLI) NewDockerCmd(args ...string) icmd.Cmd {
  174. return c.NewCmd(filepath.Join(c.BinDir, DockerExecutableName), args...)
  175. }
  176. // RunDockerOrExitError runs a docker command and returns a result
  177. func (c *E2eCLI) RunDockerOrExitError(args ...string) *icmd.Result {
  178. fmt.Printf(" [%s] docker %s\n", c.test.Name(), strings.Join(args, " "))
  179. return icmd.RunCmd(c.NewDockerCmd(args...))
  180. }
  181. // RunCmd runs a command, expects no error and returns a result
  182. func (c *E2eCLI) RunCmd(args ...string) *icmd.Result {
  183. fmt.Printf(" [%s] %s\n", c.test.Name(), strings.Join(args, " "))
  184. assert.Assert(c.test, len(args) >= 1, "require at least one command in parameters")
  185. res := icmd.RunCmd(c.NewCmd(args[0], args[1:]...))
  186. res.Assert(c.test, icmd.Success)
  187. return res
  188. }
  189. // RunDockerCmd runs a docker command, expects no error and returns a result
  190. func (c *E2eCLI) RunDockerCmd(args ...string) *icmd.Result {
  191. res := c.RunDockerOrExitError(args...)
  192. res.Assert(c.test, icmd.Success)
  193. return res
  194. }
  195. // StdoutContains returns a predicate on command result expecting a string in stdout
  196. func StdoutContains(expected string) func(*icmd.Result) bool {
  197. return func(res *icmd.Result) bool {
  198. return strings.Contains(res.Stdout(), expected)
  199. }
  200. }
  201. // WaitForCmdResult try to execute a cmd until resulting output matches given predicate
  202. func (c *E2eCLI) WaitForCmdResult(command icmd.Cmd, predicate func(*icmd.Result) bool, timeout time.Duration, delay time.Duration) {
  203. assert.Assert(c.test, timeout.Nanoseconds() > delay.Nanoseconds(), "timeout must be greater than delay")
  204. var res *icmd.Result
  205. checkStopped := func(logt poll.LogT) poll.Result {
  206. fmt.Printf(" [%s] %s\n", c.test.Name(), strings.Join(command.Command, " "))
  207. res = icmd.RunCmd(command)
  208. if !predicate(res) {
  209. return poll.Continue("Cmd output did not match requirement: %q", res.Combined())
  210. }
  211. return poll.Success()
  212. }
  213. poll.WaitOn(c.test, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  214. }
  215. // PathEnvVar returns path (os sensitive) for running test
  216. func (c *E2eCLI) PathEnvVar() string {
  217. path := c.BinDir + ":" + os.Getenv("PATH")
  218. if runtime.GOOS == "windows" {
  219. path = c.BinDir + ";" + os.Getenv("PATH")
  220. }
  221. return path
  222. }
  223. // GoldenFile golden file specific to platform
  224. func GoldenFile(name string) string {
  225. if runtime.GOOS == "windows" {
  226. return name + "-windows.golden"
  227. }
  228. return name + ".golden"
  229. }
  230. //Lines split output into lines
  231. func Lines(output string) []string {
  232. return strings.Split(strings.TrimSpace(output), "\n")
  233. }
  234. // HTTPGetWithRetry performs an HTTP GET on an `endpoint`, using retryDelay also as a request timeout.
  235. // In the case of an error or the response status is not the expeted one, it retries the same request,
  236. // returning the response body as a string (empty if we could not reach it)
  237. func HTTPGetWithRetry(t *testing.T, endpoint string, expectedStatus int, retryDelay time.Duration, timeout time.Duration) string {
  238. var (
  239. r *http.Response
  240. err error
  241. )
  242. client := &http.Client{
  243. Timeout: retryDelay,
  244. }
  245. fmt.Printf(" [%s] GET %s\n", t.Name(), endpoint)
  246. checkUp := func(t poll.LogT) poll.Result {
  247. r, err = client.Get(endpoint)
  248. if err != nil {
  249. return poll.Continue("reaching %q: Error %s", endpoint, err.Error())
  250. }
  251. if r.StatusCode == expectedStatus {
  252. return poll.Success()
  253. }
  254. return poll.Continue("reaching %q: %d != %d", endpoint, r.StatusCode, expectedStatus)
  255. }
  256. poll.WaitOn(t, checkUp, poll.WithDelay(retryDelay), poll.WithTimeout(timeout))
  257. if r != nil {
  258. b, err := ioutil.ReadAll(r.Body)
  259. assert.NilError(t, err)
  260. return string(b)
  261. }
  262. return ""
  263. }