e2e.go 6.4 KB

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