framework.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. "path"
  21. "path/filepath"
  22. "runtime"
  23. "strings"
  24. "testing"
  25. "time"
  26. "github.com/pkg/errors"
  27. "github.com/stretchr/testify/require"
  28. "gotest.tools/v3/assert"
  29. "gotest.tools/v3/icmd"
  30. "gotest.tools/v3/poll"
  31. "github.com/docker/compose/v2/cmd/compose"
  32. )
  33. var (
  34. // DockerExecutableName is the OS dependent Docker CLI binary name
  35. DockerExecutableName = "docker"
  36. // DockerComposeExecutableName is the OS dependent Docker CLI binary name
  37. DockerComposeExecutableName = "docker-" + compose.PluginName
  38. // DockerScanExecutableName is the OS dependent Docker CLI binary name
  39. DockerScanExecutableName = "docker-scan"
  40. )
  41. func init() {
  42. if runtime.GOOS == "windows" {
  43. DockerExecutableName = DockerExecutableName + ".exe"
  44. DockerComposeExecutableName = DockerComposeExecutableName + ".exe"
  45. DockerScanExecutableName = DockerScanExecutableName + ".exe"
  46. }
  47. }
  48. // CLI is used to wrap the CLI for end to end testing
  49. type CLI struct {
  50. // ConfigDir for Docker configuration (set as DOCKER_CONFIG)
  51. ConfigDir string
  52. // HomeDir for tools that look for user files (set as HOME)
  53. HomeDir string
  54. // env overrides to apply to every invoked command
  55. //
  56. // To populate, use WithEnv when creating a CLI instance.
  57. env []string
  58. }
  59. // CLIOption to customize behavior for all commands for a CLI instance.
  60. type CLIOption func(c *CLI)
  61. // NewParallelCLI marks the parent test as parallel and returns a CLI instance
  62. // suitable for usage across child tests.
  63. func NewParallelCLI(t *testing.T, opts ...CLIOption) *CLI {
  64. t.Helper()
  65. t.Parallel()
  66. return NewCLI(t, opts...)
  67. }
  68. // NewCLI creates a CLI instance for running E2E tests.
  69. func NewCLI(t testing.TB, opts ...CLIOption) *CLI {
  70. t.Helper()
  71. configDir := t.TempDir()
  72. initializePlugins(t, configDir)
  73. c := &CLI{
  74. ConfigDir: configDir,
  75. HomeDir: t.TempDir(),
  76. }
  77. for _, opt := range opts {
  78. opt(c)
  79. }
  80. return c
  81. }
  82. // WithEnv sets environment variables that will be passed to commands.
  83. func WithEnv(env ...string) CLIOption {
  84. return func(c *CLI) {
  85. c.env = append(c.env, env...)
  86. }
  87. }
  88. // initializePlugins copies the necessary plugin files to the temporary config
  89. // directory for the test.
  90. func initializePlugins(t testing.TB, d string) {
  91. t.Helper()
  92. t.Cleanup(func() {
  93. if t.Failed() {
  94. conf, _ := ioutil.ReadFile(filepath.Join(d, "config.json"))
  95. t.Errorf("Config: %s\n", string(conf))
  96. t.Error("Contents of config dir:")
  97. for _, p := range dirContents(d) {
  98. t.Errorf(p)
  99. }
  100. }
  101. _ = os.RemoveAll(d)
  102. })
  103. _ = os.MkdirAll(filepath.Join(d, "cli-plugins"), 0755)
  104. composePlugin, err := findExecutable(DockerComposeExecutableName, []string{"../../bin", "../../../bin"})
  105. if os.IsNotExist(err) {
  106. fmt.Println("WARNING: docker-compose cli-plugin not found")
  107. }
  108. if err == nil {
  109. err = CopyFile(composePlugin, filepath.Join(d, "cli-plugins", DockerComposeExecutableName))
  110. if err != nil {
  111. panic(err)
  112. }
  113. // We don't need a functional scan plugin, but a valid plugin binary
  114. err = CopyFile(composePlugin, filepath.Join(d, "cli-plugins", DockerScanExecutableName))
  115. if err != nil {
  116. panic(err)
  117. }
  118. }
  119. }
  120. func dirContents(dir string) []string {
  121. var res []string
  122. _ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  123. res = append(res, path)
  124. return nil
  125. })
  126. return res
  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. // BaseEnvironment provides the minimal environment variables used across all
  161. // Docker / Compose commands.
  162. func (c *CLI) BaseEnvironment() []string {
  163. return []string{
  164. "HOME=" + c.HomeDir,
  165. "USER=" + os.Getenv("USER"),
  166. "DOCKER_CONFIG=" + c.ConfigDir,
  167. "KUBECONFIG=invalid",
  168. }
  169. }
  170. // NewCmd creates a cmd object configured with the test environment set
  171. func (c *CLI) NewCmd(command string, args ...string) icmd.Cmd {
  172. return icmd.Cmd{
  173. Command: append([]string{command}, args...),
  174. Env: append(c.BaseEnvironment(), c.env...),
  175. }
  176. }
  177. // NewCmdWithEnv creates a cmd object configured with the test environment set with additional env vars
  178. func (c *CLI) NewCmdWithEnv(envvars []string, command string, args ...string) icmd.Cmd {
  179. // base env -> CLI overrides -> cmd overrides
  180. cmdEnv := append(c.BaseEnvironment(), c.env...)
  181. cmdEnv = append(cmdEnv, envvars...)
  182. return icmd.Cmd{
  183. Command: append([]string{command}, args...),
  184. Env: cmdEnv,
  185. }
  186. }
  187. // MetricsSocket get the path where test metrics will be sent
  188. func (c *CLI) MetricsSocket() string {
  189. return filepath.Join(c.ConfigDir, "./docker-cli.sock")
  190. }
  191. // NewDockerCmd creates a docker cmd without running it
  192. func (c *CLI) NewDockerCmd(args ...string) icmd.Cmd {
  193. return c.NewCmd(DockerExecutableName, args...)
  194. }
  195. // RunDockerOrExitError runs a docker command and returns a result
  196. func (c *CLI) RunDockerOrExitError(t testing.TB, args ...string) *icmd.Result {
  197. fmt.Printf("\t[%s] docker %s\n", t.Name(), strings.Join(args, " "))
  198. return icmd.RunCmd(c.NewDockerCmd(args...))
  199. }
  200. // RunCmd runs a command, expects no error and returns a result
  201. func (c *CLI) RunCmd(t testing.TB, args ...string) *icmd.Result {
  202. fmt.Printf("\t[%s] %s\n", t.Name(), strings.Join(args, " "))
  203. assert.Assert(t, len(args) >= 1, "require at least one command in parameters")
  204. res := icmd.RunCmd(c.NewCmd(args[0], args[1:]...))
  205. res.Assert(t, icmd.Success)
  206. return res
  207. }
  208. // RunCmdInDir runs a command in a given dir, expects no error and returns a result
  209. func (c *CLI) RunCmdInDir(t testing.TB, dir string, args ...string) *icmd.Result {
  210. fmt.Printf("\t[%s] %s\n", t.Name(), strings.Join(args, " "))
  211. assert.Assert(t, len(args) >= 1, "require at least one command in parameters")
  212. cmd := c.NewCmd(args[0], args[1:]...)
  213. cmd.Dir = dir
  214. res := icmd.RunCmd(cmd)
  215. res.Assert(t, icmd.Success)
  216. return res
  217. }
  218. // RunDockerCmd runs a docker command, expects no error and returns a result
  219. func (c *CLI) RunDockerCmd(t testing.TB, args ...string) *icmd.Result {
  220. if len(args) > 0 && args[0] == compose.PluginName {
  221. t.Fatal("This test called 'RunDockerCmd' for 'compose'. Please prefer 'RunDockerComposeCmd' to be able to test as a plugin and standalone")
  222. }
  223. res := c.RunDockerOrExitError(t, args...)
  224. res.Assert(t, icmd.Success)
  225. return res
  226. }
  227. // RunDockerComposeCmd runs a docker compose command, expects no error and returns a result
  228. func (c *CLI) RunDockerComposeCmd(t testing.TB, args ...string) *icmd.Result {
  229. res := c.RunDockerComposeCmdNoCheck(t, args...)
  230. res.Assert(t, icmd.Success)
  231. return res
  232. }
  233. // RunDockerComposeCmdNoCheck runs a docker compose command, don't presume of any expectation and returns a result
  234. func (c *CLI) RunDockerComposeCmdNoCheck(t testing.TB, args ...string) *icmd.Result {
  235. return icmd.RunCmd(c.NewDockerComposeCmd(t, args...))
  236. }
  237. // NewDockerComposeCmd creates a command object for Compose, either in plugin
  238. // or standalone mode (based on build tags).
  239. func (c *CLI) NewDockerComposeCmd(t testing.TB, args ...string) icmd.Cmd {
  240. t.Helper()
  241. if composeStandaloneMode {
  242. return c.NewCmd(ComposeStandalonePath(t), args...)
  243. }
  244. args = append([]string{"compose"}, args...)
  245. return c.NewCmd(DockerExecutableName, args...)
  246. }
  247. // ComposeStandalonePath returns the path to the locally-built Compose
  248. // standalone binary from the repo.
  249. //
  250. // This function will fail the test immediately if invoked when not running
  251. // in standalone test mode.
  252. func ComposeStandalonePath(t testing.TB) string {
  253. t.Helper()
  254. if !composeStandaloneMode {
  255. require.Fail(t, "Not running in standalone mode")
  256. }
  257. composeBinary, err := findExecutable(DockerComposeExecutableName, []string{"../../bin", "../../../bin"})
  258. require.NoError(t, err, "Could not find standalone Compose binary (%q)",
  259. DockerComposeExecutableName)
  260. return composeBinary
  261. }
  262. // StdoutContains returns a predicate on command result expecting a string in stdout
  263. func StdoutContains(expected string) func(*icmd.Result) bool {
  264. return func(res *icmd.Result) bool {
  265. return strings.Contains(res.Stdout(), expected)
  266. }
  267. }
  268. // WaitForCmdResult try to execute a cmd until resulting output matches given predicate
  269. func (c *CLI) WaitForCmdResult(t testing.TB, command icmd.Cmd, predicate func(*icmd.Result) bool, timeout time.Duration, delay time.Duration) {
  270. assert.Assert(t, timeout.Nanoseconds() > delay.Nanoseconds(), "timeout must be greater than delay")
  271. var res *icmd.Result
  272. checkStopped := func(logt poll.LogT) poll.Result {
  273. fmt.Printf("\t[%s] %s\n", t.Name(), strings.Join(command.Command, " "))
  274. res = icmd.RunCmd(command)
  275. if !predicate(res) {
  276. return poll.Continue("Cmd output did not match requirement: %q", res.Combined())
  277. }
  278. return poll.Success()
  279. }
  280. poll.WaitOn(t, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  281. }
  282. // WaitForCondition wait for predicate to execute to true
  283. func (c *CLI) WaitForCondition(t testing.TB, predicate func() (bool, string), timeout time.Duration, delay time.Duration) {
  284. checkStopped := func(logt poll.LogT) poll.Result {
  285. pass, description := predicate()
  286. if !pass {
  287. return poll.Continue("Condition not met: %q", description)
  288. }
  289. return poll.Success()
  290. }
  291. poll.WaitOn(t, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  292. }
  293. // Lines split output into lines
  294. func Lines(output string) []string {
  295. return strings.Split(strings.TrimSpace(output), "\n")
  296. }
  297. // HTTPGetWithRetry performs an HTTP GET on an `endpoint`, using retryDelay also as a request timeout.
  298. // In the case of an error or the response status is not the expeted one, it retries the same request,
  299. // returning the response body as a string (empty if we could not reach it)
  300. func HTTPGetWithRetry(t testing.TB, endpoint string, expectedStatus int, retryDelay time.Duration, timeout time.Duration) string {
  301. var (
  302. r *http.Response
  303. err error
  304. )
  305. client := &http.Client{
  306. Timeout: retryDelay,
  307. }
  308. fmt.Printf("\t[%s] GET %s\n", t.Name(), endpoint)
  309. checkUp := func(t poll.LogT) poll.Result {
  310. r, err = client.Get(endpoint)
  311. if err != nil {
  312. return poll.Continue("reaching %q: Error %s", endpoint, err.Error())
  313. }
  314. if r.StatusCode == expectedStatus {
  315. return poll.Success()
  316. }
  317. return poll.Continue("reaching %q: %d != %d", endpoint, r.StatusCode, expectedStatus)
  318. }
  319. poll.WaitOn(t, checkUp, poll.WithDelay(retryDelay), poll.WithTimeout(timeout))
  320. if r != nil {
  321. b, err := ioutil.ReadAll(r.Body)
  322. assert.NilError(t, err)
  323. return string(b)
  324. }
  325. return ""
  326. }