e2e.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 framework
  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. type E2eCLI struct {
  46. BinDir string
  47. ConfigDir string
  48. test *testing.T
  49. }
  50. // NewParallelE2eCLI returns a configured TestE2eCLI with t.Parallel() set
  51. func NewParallelE2eCLI(t *testing.T, binDir string) *E2eCLI {
  52. t.Parallel()
  53. return newE2eCLI(t, binDir)
  54. }
  55. // NewE2eCLI returns a configured TestE2eCLI
  56. func NewE2eCLI(t *testing.T, binDir string) *E2eCLI {
  57. return newE2eCLI(t, binDir)
  58. }
  59. func newE2eCLI(t *testing.T, binDir string) *E2eCLI {
  60. d, err := ioutil.TempDir("", "")
  61. assert.Check(t, is.Nil(err))
  62. t.Cleanup(func() {
  63. if t.Failed() {
  64. conf, _ := ioutil.ReadFile(filepath.Join(d, "config.json"))
  65. t.Errorf("Config: %s\n", string(conf))
  66. t.Error("Contents of config dir:")
  67. for _, p := range dirContents(d) {
  68. t.Errorf(p)
  69. }
  70. }
  71. _ = os.RemoveAll(d)
  72. })
  73. return &E2eCLI{binDir, d, t}
  74. }
  75. func dirContents(dir string) []string {
  76. res := []string{}
  77. _ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  78. res = append(res, filepath.Join(dir, path))
  79. return nil
  80. })
  81. return res
  82. }
  83. // SetupExistingCLI copies the existing CLI in a temporary directory so that the
  84. // new CLI can be configured to use it
  85. func SetupExistingCLI() (string, func(), error) {
  86. p, err := exec.LookPath(existingExectuableName)
  87. if err != nil {
  88. p, err = exec.LookPath(DockerExecutableName)
  89. if err != nil {
  90. return "", nil, errors.New("existing CLI not found in PATH")
  91. }
  92. }
  93. d, err := ioutil.TempDir("", "")
  94. if err != nil {
  95. return "", nil, err
  96. }
  97. if err := CopyFile(p, filepath.Join(d, existingExectuableName)); err != nil {
  98. return "", nil, err
  99. }
  100. bin, err := findExecutable([]string{"../../bin", "../../../bin"})
  101. if err != nil {
  102. return "", nil, err
  103. }
  104. if err := CopyFile(bin, filepath.Join(d, DockerExecutableName)); err != nil {
  105. return "", nil, err
  106. }
  107. cleanup := func() {
  108. _ = os.RemoveAll(d)
  109. }
  110. return d, cleanup, nil
  111. }
  112. func findExecutable(paths []string) (string, error) {
  113. for _, p := range paths {
  114. bin, err := filepath.Abs(path.Join(p, DockerExecutableName))
  115. if err != nil {
  116. return "", err
  117. }
  118. if _, err := os.Stat(bin); os.IsNotExist(err) {
  119. continue
  120. }
  121. return bin, nil
  122. }
  123. return "", errors.New("executable not found")
  124. }
  125. // CopyFile copies a file from a sourceFile to a destinationFile setting permissions to 0755
  126. func CopyFile(sourceFile string, destinationFile string) error {
  127. src, err := os.Open(sourceFile)
  128. if err != nil {
  129. return err
  130. }
  131. // nolint: errcheck
  132. defer src.Close()
  133. dst, err := os.OpenFile(destinationFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
  134. if err != nil {
  135. return err
  136. }
  137. // nolint: errcheck
  138. defer dst.Close()
  139. if _, err = io.Copy(dst, src); err != nil {
  140. return err
  141. }
  142. return err
  143. }
  144. // NewCmd creates a cmd object configured with the test environment set
  145. func (c *E2eCLI) NewCmd(command string, args ...string) icmd.Cmd {
  146. env := append(os.Environ(),
  147. "DOCKER_CONFIG="+c.ConfigDir,
  148. "KUBECONFIG=invalid",
  149. "TEST_METRICS_SOCKET="+c.MetricsSocket(),
  150. "PATH="+c.PathEnvVar(),
  151. )
  152. return icmd.Cmd{
  153. Command: append([]string{command}, args...),
  154. Env: env,
  155. }
  156. }
  157. // MetricsSocket get the path where test metrics will be sent
  158. func (c *E2eCLI) MetricsSocket() string {
  159. return filepath.Join(c.ConfigDir, "./docker-cli.sock")
  160. }
  161. // NewDockerCmd creates a docker cmd without running it
  162. func (c *E2eCLI) NewDockerCmd(args ...string) icmd.Cmd {
  163. return c.NewCmd(filepath.Join(c.BinDir, DockerExecutableName), args...)
  164. }
  165. // RunDockerOrExitError runs a docker command and returns a result
  166. func (c *E2eCLI) RunDockerOrExitError(args ...string) *icmd.Result {
  167. fmt.Printf(" [%s] docker %s\n", c.test.Name(), strings.Join(args, " "))
  168. return icmd.RunCmd(c.NewDockerCmd(args...))
  169. }
  170. // RunDockerCmd runs a docker command, expects no error and returns a result
  171. func (c *E2eCLI) RunDockerCmd(args ...string) *icmd.Result {
  172. res := c.RunDockerOrExitError(args...)
  173. res.Assert(c.test, icmd.Success)
  174. return res
  175. }
  176. // PathEnvVar returns path (os sensitive) for running test
  177. func (c *E2eCLI) PathEnvVar() string {
  178. path := c.BinDir + ":" + os.Getenv("PATH")
  179. if runtime.GOOS == "windows" {
  180. path = c.BinDir + ";" + os.Getenv("PATH")
  181. }
  182. return path
  183. }
  184. // GoldenFile golden file specific to platform
  185. func GoldenFile(name string) string {
  186. if runtime.GOOS == "windows" {
  187. return name + "-windows.golden"
  188. }
  189. return name + ".golden"
  190. }
  191. //Lines split output into lines
  192. func Lines(output string) []string {
  193. return strings.Split(strings.TrimSpace(output), "\n")
  194. }
  195. // HTTPGetWithRetry performs an HTTP GET on an `endpoint`, using retryDelay also as a request timeout.
  196. // In the case of an error or the response status is not the expeted one, it retries the same request,
  197. // returning the response body as a string (empty if we could not reach it)
  198. func HTTPGetWithRetry(t *testing.T, endpoint string, expectedStatus int, retryDelay time.Duration, timeout time.Duration) string {
  199. var (
  200. r *http.Response
  201. err error
  202. )
  203. client := &http.Client{
  204. Timeout: retryDelay,
  205. }
  206. fmt.Printf(" [%s] GET %s\n", t.Name(), endpoint)
  207. checkUp := func(t poll.LogT) poll.Result {
  208. r, err = client.Get(endpoint)
  209. if err != nil {
  210. return poll.Continue("reaching %q: Error %s", endpoint, err.Error())
  211. }
  212. if r.StatusCode == expectedStatus {
  213. return poll.Success()
  214. }
  215. return poll.Continue("reaching %q: %d != %d", endpoint, r.StatusCode, expectedStatus)
  216. }
  217. poll.WaitOn(t, checkUp, poll.WithDelay(retryDelay), poll.WithTimeout(timeout))
  218. if r != nil {
  219. b, err := ioutil.ReadAll(r.Body)
  220. assert.NilError(t, err)
  221. return string(b)
  222. }
  223. return ""
  224. }