framework.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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, configDir string) {
  91. t.Helper()
  92. t.Cleanup(func() {
  93. if t.Failed() {
  94. if conf, err := ioutil.ReadFile(filepath.Join(configDir, "config.json")); err == nil {
  95. t.Logf("Config: %s\n", string(conf))
  96. }
  97. t.Log("Contents of config dir:")
  98. for _, p := range dirContents(configDir) {
  99. t.Logf(" - %s", p)
  100. }
  101. }
  102. })
  103. require.NoError(t, os.MkdirAll(filepath.Join(configDir, "cli-plugins"), 0755),
  104. "Failed to create cli-plugins directory")
  105. composePlugin, err := findExecutable(DockerComposeExecutableName, []string{"../../bin", "../../../bin"})
  106. if os.IsNotExist(err) {
  107. t.Logf("WARNING: docker-compose cli-plugin not found")
  108. }
  109. if err == nil {
  110. CopyFile(t, composePlugin, filepath.Join(configDir, "cli-plugins", DockerComposeExecutableName))
  111. // We don't need a functional scan plugin, but a valid plugin binary
  112. CopyFile(t, composePlugin, filepath.Join(configDir, "cli-plugins", DockerScanExecutableName))
  113. }
  114. }
  115. func dirContents(dir string) []string {
  116. var res []string
  117. _ = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  118. res = append(res, path)
  119. return nil
  120. })
  121. return res
  122. }
  123. func findExecutable(executableName string, paths []string) (string, error) {
  124. for _, p := range paths {
  125. bin, err := filepath.Abs(path.Join(p, executableName))
  126. if err != nil {
  127. return "", err
  128. }
  129. if _, err := os.Stat(bin); os.IsNotExist(err) {
  130. continue
  131. }
  132. return bin, nil
  133. }
  134. return "", errors.Wrap(os.ErrNotExist, "executable not found")
  135. }
  136. // CopyFile copies a file from a sourceFile to a destinationFile setting permissions to 0755
  137. func CopyFile(t testing.TB, sourceFile string, destinationFile string) {
  138. t.Helper()
  139. src, err := os.Open(sourceFile)
  140. require.NoError(t, err, "Failed to open source file: %s")
  141. // nolint: errcheck
  142. defer src.Close()
  143. dst, err := os.OpenFile(destinationFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
  144. require.NoError(t, err, "Failed to open destination file: %s", destinationFile)
  145. // nolint: errcheck
  146. defer dst.Close()
  147. _, err = io.Copy(dst, src)
  148. require.NoError(t, err, "Failed to copy file: %s", sourceFile)
  149. }
  150. // BaseEnvironment provides the minimal environment variables used across all
  151. // Docker / Compose commands.
  152. func (c *CLI) BaseEnvironment() []string {
  153. return []string{
  154. "HOME=" + c.HomeDir,
  155. "USER=" + os.Getenv("USER"),
  156. "DOCKER_CONFIG=" + c.ConfigDir,
  157. "KUBECONFIG=invalid",
  158. }
  159. }
  160. // NewCmd creates a cmd object configured with the test environment set
  161. func (c *CLI) NewCmd(command string, args ...string) icmd.Cmd {
  162. return icmd.Cmd{
  163. Command: append([]string{command}, args...),
  164. Env: append(c.BaseEnvironment(), c.env...),
  165. }
  166. }
  167. // NewCmdWithEnv creates a cmd object configured with the test environment set with additional env vars
  168. func (c *CLI) NewCmdWithEnv(envvars []string, command string, args ...string) icmd.Cmd {
  169. // base env -> CLI overrides -> cmd overrides
  170. cmdEnv := append(c.BaseEnvironment(), c.env...)
  171. cmdEnv = append(cmdEnv, envvars...)
  172. return icmd.Cmd{
  173. Command: append([]string{command}, args...),
  174. Env: cmdEnv,
  175. }
  176. }
  177. // MetricsSocket get the path where test metrics will be sent
  178. func (c *CLI) MetricsSocket() string {
  179. return filepath.Join(c.ConfigDir, "./docker-cli.sock")
  180. }
  181. // NewDockerCmd creates a docker cmd without running it
  182. func (c *CLI) NewDockerCmd(t testing.TB, args ...string) icmd.Cmd {
  183. t.Helper()
  184. for _, arg := range args {
  185. if arg == compose.PluginName {
  186. t.Fatal("This test called 'RunDockerCmd' for 'compose'. Please prefer 'RunDockerComposeCmd' to be able to test as a plugin and standalone")
  187. }
  188. }
  189. return c.NewCmd(DockerExecutableName, args...)
  190. }
  191. // RunDockerOrExitError runs a docker command and returns a result
  192. func (c *CLI) RunDockerOrExitError(t testing.TB, args ...string) *icmd.Result {
  193. t.Helper()
  194. t.Logf("\t[%s] docker %s\n", t.Name(), strings.Join(args, " "))
  195. return icmd.RunCmd(c.NewDockerCmd(t, args...))
  196. }
  197. // RunCmd runs a command, expects no error and returns a result
  198. func (c *CLI) RunCmd(t testing.TB, args ...string) *icmd.Result {
  199. t.Helper()
  200. t.Logf("\t[%s] %s\n", t.Name(), strings.Join(args, " "))
  201. assert.Assert(t, len(args) >= 1, "require at least one command in parameters")
  202. res := icmd.RunCmd(c.NewCmd(args[0], args[1:]...))
  203. res.Assert(t, icmd.Success)
  204. return res
  205. }
  206. // RunCmdInDir runs a command in a given dir, expects no error and returns a result
  207. func (c *CLI) RunCmdInDir(t testing.TB, dir string, args ...string) *icmd.Result {
  208. t.Helper()
  209. t.Logf("\t[%s] %s\n", t.Name(), strings.Join(args, " "))
  210. assert.Assert(t, len(args) >= 1, "require at least one command in parameters")
  211. cmd := c.NewCmd(args[0], args[1:]...)
  212. cmd.Dir = dir
  213. res := icmd.RunCmd(cmd)
  214. res.Assert(t, icmd.Success)
  215. return res
  216. }
  217. // RunDockerCmd runs a docker command, expects no error and returns a result
  218. func (c *CLI) RunDockerCmd(t testing.TB, args ...string) *icmd.Result {
  219. t.Helper()
  220. res := c.RunDockerOrExitError(t, args...)
  221. res.Assert(t, icmd.Success)
  222. return res
  223. }
  224. // RunDockerComposeCmd runs a docker compose command, expects no error and returns a result
  225. func (c *CLI) RunDockerComposeCmd(t testing.TB, args ...string) *icmd.Result {
  226. t.Helper()
  227. res := c.RunDockerComposeCmdNoCheck(t, args...)
  228. res.Assert(t, icmd.Success)
  229. return res
  230. }
  231. // RunDockerComposeCmdNoCheck runs a docker compose command, don't presume of any expectation and returns a result
  232. func (c *CLI) RunDockerComposeCmdNoCheck(t testing.TB, args ...string) *icmd.Result {
  233. t.Helper()
  234. return icmd.RunCmd(c.NewDockerComposeCmd(t, args...))
  235. }
  236. // NewDockerComposeCmd creates a command object for Compose, either in plugin
  237. // or standalone mode (based on build tags).
  238. func (c *CLI) NewDockerComposeCmd(t testing.TB, args ...string) icmd.Cmd {
  239. t.Helper()
  240. if composeStandaloneMode {
  241. return c.NewCmd(ComposeStandalonePath(t), args...)
  242. }
  243. args = append([]string{"compose"}, args...)
  244. return c.NewCmd(DockerExecutableName, args...)
  245. }
  246. // ComposeStandalonePath returns the path to the locally-built Compose
  247. // standalone binary from the repo.
  248. //
  249. // This function will fail the test immediately if invoked when not running
  250. // in standalone test mode.
  251. func ComposeStandalonePath(t testing.TB) string {
  252. t.Helper()
  253. if !composeStandaloneMode {
  254. require.Fail(t, "Not running in standalone mode")
  255. }
  256. composeBinary, err := findExecutable(DockerComposeExecutableName, []string{"../../bin", "../../../bin"})
  257. require.NoError(t, err, "Could not find standalone Compose binary (%q)",
  258. DockerComposeExecutableName)
  259. return composeBinary
  260. }
  261. // StdoutContains returns a predicate on command result expecting a string in stdout
  262. func StdoutContains(expected string) func(*icmd.Result) bool {
  263. return func(res *icmd.Result) bool {
  264. return strings.Contains(res.Stdout(), expected)
  265. }
  266. }
  267. // WaitForCmdResult try to execute a cmd until resulting output matches given predicate
  268. func (c *CLI) WaitForCmdResult(
  269. t testing.TB,
  270. command icmd.Cmd,
  271. predicate func(*icmd.Result) bool,
  272. timeout time.Duration,
  273. delay time.Duration,
  274. ) {
  275. t.Helper()
  276. assert.Assert(t, timeout.Nanoseconds() > delay.Nanoseconds(), "timeout must be greater than delay")
  277. var res *icmd.Result
  278. checkStopped := func(logt poll.LogT) poll.Result {
  279. fmt.Printf("\t[%s] %s\n", t.Name(), strings.Join(command.Command, " "))
  280. res = icmd.RunCmd(command)
  281. if !predicate(res) {
  282. return poll.Continue("Cmd output did not match requirement: %q", res.Combined())
  283. }
  284. return poll.Success()
  285. }
  286. poll.WaitOn(t, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  287. }
  288. // WaitForCondition wait for predicate to execute to true
  289. func (c *CLI) WaitForCondition(
  290. t testing.TB,
  291. predicate func() (bool, string),
  292. timeout time.Duration,
  293. delay time.Duration,
  294. ) {
  295. t.Helper()
  296. checkStopped := func(logt poll.LogT) poll.Result {
  297. pass, description := predicate()
  298. if !pass {
  299. return poll.Continue("Condition not met: %q", description)
  300. }
  301. return poll.Success()
  302. }
  303. poll.WaitOn(t, checkStopped, poll.WithDelay(delay), poll.WithTimeout(timeout))
  304. }
  305. // Lines split output into lines
  306. func Lines(output string) []string {
  307. return strings.Split(strings.TrimSpace(output), "\n")
  308. }
  309. // HTTPGetWithRetry performs an HTTP GET on an `endpoint`, using retryDelay also as a request timeout.
  310. // In the case of an error or the response status is not the expected one, it retries the same request,
  311. // returning the response body as a string (empty if we could not reach it)
  312. func HTTPGetWithRetry(
  313. t testing.TB,
  314. endpoint string,
  315. expectedStatus int,
  316. retryDelay time.Duration,
  317. timeout time.Duration,
  318. ) string {
  319. t.Helper()
  320. var (
  321. r *http.Response
  322. err error
  323. )
  324. client := &http.Client{
  325. Timeout: retryDelay,
  326. }
  327. fmt.Printf("\t[%s] GET %s\n", t.Name(), endpoint)
  328. checkUp := func(t poll.LogT) poll.Result {
  329. r, err = client.Get(endpoint)
  330. if err != nil {
  331. return poll.Continue("reaching %q: Error %s", endpoint, err.Error())
  332. }
  333. if r.StatusCode == expectedStatus {
  334. return poll.Success()
  335. }
  336. return poll.Continue("reaching %q: %d != %d", endpoint, r.StatusCode, expectedStatus)
  337. }
  338. poll.WaitOn(t, checkUp, poll.WithDelay(retryDelay), poll.WithTimeout(timeout))
  339. if r != nil {
  340. b, err := ioutil.ReadAll(r.Body)
  341. assert.NilError(t, err)
  342. return string(b)
  343. }
  344. return ""
  345. }