framework.go 13 KB

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