framework.go 14 KB

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