framework.go 12 KB

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