framework.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. 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 := findExecutable([]string{"../../bin", "../../../bin"})
  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. func findExecutable(paths []string) (string, error) {
  114. for _, p := range paths {
  115. bin, err := filepath.Abs(path.Join(p, DockerExecutableName))
  116. if err != nil {
  117. return "", err
  118. }
  119. if _, err := os.Stat(bin); os.IsNotExist(err) {
  120. continue
  121. }
  122. return bin, nil
  123. }
  124. return "", errors.New("executable not found")
  125. }
  126. // CopyFile copies a file from a sourceFile to a destinationFile setting permissions to 0755
  127. func CopyFile(sourceFile string, destinationFile string) error {
  128. src, err := os.Open(sourceFile)
  129. if err != nil {
  130. return err
  131. }
  132. // nolint: errcheck
  133. defer src.Close()
  134. dst, err := os.OpenFile(destinationFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
  135. if err != nil {
  136. return err
  137. }
  138. // nolint: errcheck
  139. defer dst.Close()
  140. if _, err = io.Copy(dst, src); err != nil {
  141. return err
  142. }
  143. return err
  144. }
  145. // NewCmd creates a cmd object configured with the test environment set
  146. func (c *E2eCLI) NewCmd(command string, args ...string) icmd.Cmd {
  147. env := append(os.Environ(),
  148. "DOCKER_CONFIG="+c.ConfigDir,
  149. "KUBECONFIG=invalid",
  150. "TEST_METRICS_SOCKET="+c.MetricsSocket(),
  151. "PATH="+c.PathEnvVar(),
  152. )
  153. return icmd.Cmd{
  154. Command: append([]string{command}, args...),
  155. Env: env,
  156. }
  157. }
  158. // MetricsSocket get the path where test metrics will be sent
  159. func (c *E2eCLI) MetricsSocket() string {
  160. return filepath.Join(c.ConfigDir, "./docker-cli.sock")
  161. }
  162. // NewDockerCmd creates a docker cmd without running it
  163. func (c *E2eCLI) NewDockerCmd(args ...string) icmd.Cmd {
  164. return c.NewCmd(filepath.Join(c.BinDir, DockerExecutableName), args...)
  165. }
  166. // RunDockerOrExitError runs a docker command and returns a result
  167. func (c *E2eCLI) RunDockerOrExitError(args ...string) *icmd.Result {
  168. fmt.Printf(" [%s] docker %s\n", c.test.Name(), strings.Join(args, " "))
  169. return icmd.RunCmd(c.NewDockerCmd(args...))
  170. }
  171. // RunCmd runs a command, expects no error and returns a result
  172. func (c *E2eCLI) RunCmd(args ...string) *icmd.Result {
  173. fmt.Printf(" [%s] %s\n", c.test.Name(), strings.Join(args, " "))
  174. assert.Assert(c.test, len(args) >= 1, "require at least one command in parameters")
  175. res := icmd.RunCmd(c.NewCmd(args[0], args[1:]...))
  176. res.Assert(c.test, icmd.Success)
  177. return res
  178. }
  179. // RunDockerCmd runs a docker command, expects no error and returns a result
  180. func (c *E2eCLI) RunDockerCmd(args ...string) *icmd.Result {
  181. res := c.RunDockerOrExitError(args...)
  182. res.Assert(c.test, icmd.Success)
  183. return res
  184. }
  185. // StdoutContains returns a predicate on command result expecting a string in stdout
  186. func StdoutContains(expected string) func(*icmd.Result) bool {
  187. return func(res *icmd.Result) bool {
  188. return strings.Contains(res.Stdout(), expected)
  189. }
  190. }
  191. // WaitForCmdResult try to execute a cmd until resulting output matches given predicate
  192. func (c *E2eCLI) WaitForCmdResult(command icmd.Cmd, predicate func(*icmd.Result) bool, timeout time.Duration, delay time.Duration) {
  193. assert.Assert(c.test, timeout.Nanoseconds() > delay.Nanoseconds(), "timeout must be greater than delay")
  194. var res *icmd.Result
  195. checkStopped := func(logt poll.LogT) poll.Result {
  196. fmt.Printf(" [%s] %s\n", c.test.Name(), strings.Join(command.Command, " "))
  197. res = icmd.RunCmd(command)
  198. if !predicate(res) {
  199. return poll.Continue("Cmd output did not match requirement: %q", res.Combined())
  200. }
  201. return poll.Success()
  202. }
  203. poll.WaitOn(c.test, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  204. }
  205. // PathEnvVar returns path (os sensitive) for running test
  206. func (c *E2eCLI) PathEnvVar() string {
  207. path := c.BinDir + ":" + os.Getenv("PATH")
  208. if runtime.GOOS == "windows" {
  209. path = c.BinDir + ";" + os.Getenv("PATH")
  210. }
  211. return path
  212. }
  213. // GoldenFile golden file specific to platform
  214. func GoldenFile(name string) string {
  215. if runtime.GOOS == "windows" {
  216. return name + "-windows.golden"
  217. }
  218. return name + ".golden"
  219. }
  220. //Lines split output into lines
  221. func Lines(output string) []string {
  222. return strings.Split(strings.TrimSpace(output), "\n")
  223. }
  224. // HTTPGetWithRetry performs an HTTP GET on an `endpoint`, using retryDelay also as a request timeout.
  225. // In the case of an error or the response status is not the expeted one, it retries the same request,
  226. // returning the response body as a string (empty if we could not reach it)
  227. func HTTPGetWithRetry(t *testing.T, endpoint string, expectedStatus int, retryDelay time.Duration, timeout time.Duration) string {
  228. var (
  229. r *http.Response
  230. err error
  231. )
  232. client := &http.Client{
  233. Timeout: retryDelay,
  234. }
  235. fmt.Printf(" [%s] GET %s\n", t.Name(), endpoint)
  236. checkUp := func(t poll.LogT) poll.Result {
  237. r, err = client.Get(endpoint)
  238. if err != nil {
  239. return poll.Continue("reaching %q: Error %s", endpoint, err.Error())
  240. }
  241. if r.StatusCode == expectedStatus {
  242. return poll.Success()
  243. }
  244. return poll.Continue("reaching %q: %d != %d", endpoint, r.StatusCode, expectedStatus)
  245. }
  246. poll.WaitOn(t, checkUp, poll.WithDelay(retryDelay), poll.WithTimeout(timeout))
  247. if r != nil {
  248. b, err := ioutil.ReadAll(r.Body)
  249. assert.NilError(t, err)
  250. return string(b)
  251. }
  252. return ""
  253. }