e2e.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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/ioutil"
  18. "net/http"
  19. "os"
  20. "os/exec"
  21. "path/filepath"
  22. "runtime"
  23. "strings"
  24. "testing"
  25. "time"
  26. "gotest.tools/v3/assert"
  27. is "gotest.tools/v3/assert/cmp"
  28. "gotest.tools/v3/icmd"
  29. "gotest.tools/v3/poll"
  30. )
  31. var (
  32. // DockerExecutableName is the OS dependent Docker CLI binary name
  33. DockerExecutableName = "docker"
  34. existingExectuableName = "com.docker.cli"
  35. )
  36. func init() {
  37. if runtime.GOOS == "windows" {
  38. DockerExecutableName = DockerExecutableName + ".exe"
  39. existingExectuableName = existingExectuableName + ".exe"
  40. }
  41. }
  42. // E2eCLI is used to wrap the CLI for end to end testing
  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. // NewE2eCLI returns a configured TestE2eCLI
  54. func NewE2eCLI(t *testing.T, binDir string) *E2eCLI {
  55. return newE2eCLI(t, binDir)
  56. }
  57. func newE2eCLI(t *testing.T, binDir string) *E2eCLI {
  58. d, err := ioutil.TempDir("", "")
  59. assert.Check(t, is.Nil(err))
  60. t.Cleanup(func() {
  61. if t.Failed() {
  62. conf, _ := ioutil.ReadFile(filepath.Join(d, "config.json"))
  63. t.Errorf("Config: %s\n", string(conf))
  64. t.Error("Contents of config dir:")
  65. for _, p := range dirContents(d) {
  66. t.Errorf(p)
  67. }
  68. }
  69. _ = os.RemoveAll(d)
  70. })
  71. return &E2eCLI{binDir, d, t}
  72. }
  73. func dirContents(dir string) []string {
  74. res := []string{}
  75. _ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  76. res = append(res, filepath.Join(dir, path))
  77. return nil
  78. })
  79. return res
  80. }
  81. // SetupExistingCLI copies the existing CLI in a temporary directory so that the
  82. // new CLI can be configured to use it
  83. func SetupExistingCLI() (string, func(), error) {
  84. p, err := exec.LookPath(existingExectuableName)
  85. if err != nil {
  86. p, err = exec.LookPath(DockerExecutableName)
  87. if err != nil {
  88. return "", nil, errors.New("existing CLI not found in PATH")
  89. }
  90. }
  91. d, err := ioutil.TempDir("", "")
  92. if err != nil {
  93. return "", nil, err
  94. }
  95. if err := CopyFile(p, filepath.Join(d, existingExectuableName)); err != nil {
  96. return "", nil, err
  97. }
  98. bin, err := filepath.Abs("../../bin/" + DockerExecutableName)
  99. if err != nil {
  100. return "", nil, err
  101. }
  102. if err := CopyFile(bin, filepath.Join(d, DockerExecutableName)); err != nil {
  103. return "", nil, err
  104. }
  105. cleanup := func() {
  106. _ = os.RemoveAll(d)
  107. }
  108. return d, cleanup, nil
  109. }
  110. // CopyFile copies a file from a path to a path setting permissions to 0777
  111. func CopyFile(sourceFile string, destinationFile string) error {
  112. input, err := ioutil.ReadFile(sourceFile)
  113. if err != nil {
  114. return err
  115. }
  116. err = ioutil.WriteFile(destinationFile, input, 0777)
  117. if err != nil {
  118. return err
  119. }
  120. return nil
  121. }
  122. // NewCmd creates a cmd object configured with the test environment set
  123. func (c *E2eCLI) NewCmd(command string, args ...string) icmd.Cmd {
  124. env := append(os.Environ(),
  125. "DOCKER_CONFIG="+c.ConfigDir,
  126. "KUBECONFIG=invalid",
  127. "TEST_METRICS_SOCKET="+c.MetricsSocket(),
  128. "PATH="+c.PathEnvVar(),
  129. )
  130. return icmd.Cmd{
  131. Command: append([]string{command}, args...),
  132. Env: env,
  133. }
  134. }
  135. // MetricsSocket get the path where test metrics will be sent
  136. func (c *E2eCLI) MetricsSocket() string {
  137. return filepath.Join(c.ConfigDir, "./docker-cli.sock")
  138. }
  139. // NewDockerCmd creates a docker cmd without running it
  140. func (c *E2eCLI) NewDockerCmd(args ...string) icmd.Cmd {
  141. return c.NewCmd(filepath.Join(c.BinDir, DockerExecutableName), args...)
  142. }
  143. // RunDockerOrExitError runs a docker command and returns a result
  144. func (c *E2eCLI) RunDockerOrExitError(args ...string) *icmd.Result {
  145. fmt.Printf(" [%s] docker %s\n", c.test.Name(), strings.Join(args, " "))
  146. return icmd.RunCmd(c.NewDockerCmd(args...))
  147. }
  148. // RunDockerCmd runs a docker command, expects no error and returns a result
  149. func (c *E2eCLI) RunDockerCmd(args ...string) *icmd.Result {
  150. res := c.RunDockerOrExitError(args...)
  151. res.Assert(c.test, icmd.Success)
  152. return res
  153. }
  154. // PathEnvVar returns path (os sensitive) for running test
  155. func (c *E2eCLI) PathEnvVar() string {
  156. path := c.BinDir + ":" + os.Getenv("PATH")
  157. if runtime.GOOS == "windows" {
  158. path = c.BinDir + ";" + os.Getenv("PATH")
  159. }
  160. return path
  161. }
  162. // GoldenFile golden file specific to platform
  163. func GoldenFile(name string) string {
  164. if runtime.GOOS == "windows" {
  165. return name + "-windows.golden"
  166. }
  167. return name + ".golden"
  168. }
  169. // HTTPGetWithRetry performs an HTTP GET on an `endpoint`, using retryDelay also as a request timeout.
  170. // In the case of an error or the response status is not the expeted one, it retries the same request,
  171. // returning the response body as a string (empty if we could not reach it)
  172. func HTTPGetWithRetry(t *testing.T, endpoint string, expectedStatus int, retryDelay time.Duration, timeout time.Duration) string {
  173. var (
  174. r *http.Response
  175. err error
  176. )
  177. client := &http.Client{
  178. Timeout: retryDelay,
  179. }
  180. fmt.Printf(" [%s] GET %s\n", t.Name(), endpoint)
  181. checkUp := func(t poll.LogT) poll.Result {
  182. r, err = client.Get(endpoint)
  183. if err != nil {
  184. return poll.Continue("reaching %q: Error %s", endpoint, err.Error())
  185. }
  186. if r.StatusCode == expectedStatus {
  187. return poll.Success()
  188. }
  189. return poll.Continue("reaching %q: %d != %d", endpoint, r.StatusCode, expectedStatus)
  190. }
  191. poll.WaitOn(t, checkUp, poll.WithDelay(retryDelay), poll.WithTimeout(timeout))
  192. if r != nil {
  193. b, err := ioutil.ReadAll(r.Body)
  194. assert.NilError(t, err)
  195. return string(b)
  196. }
  197. return ""
  198. }