framework.go 13 KB

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