framework.go 14 KB

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