1
0

framework.go 8.9 KB

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