cancel_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //go:build !windows
  2. // +build !windows
  3. /*
  4. Copyright 2020 Docker Compose CLI authors
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. */
  15. package e2e
  16. import (
  17. "bytes"
  18. "fmt"
  19. "os/exec"
  20. "strings"
  21. "syscall"
  22. "testing"
  23. "time"
  24. "gotest.tools/v3/assert"
  25. "gotest.tools/v3/icmd"
  26. )
  27. func TestComposeCancel(t *testing.T) {
  28. c := NewParallelE2eCLI(t, binDir)
  29. t.Run("metrics on cancel Compose build", func(t *testing.T) {
  30. c.RunDockerCmd("compose", "ls")
  31. buildProjectPath := "fixtures/build-infinite/compose.yaml"
  32. // require a separate groupID from the process running tests, in order to simulate ctrl+C from a terminal.
  33. // sending kill signal
  34. cmd, stdout, stderr, err := StartWithNewGroupID(c.NewDockerCmd("compose", "-f", buildProjectPath, "build", "--progress", "plain"))
  35. assert.NilError(t, err)
  36. c.WaitForCondition(func() (bool, string) {
  37. out := stdout.String()
  38. errors := stderr.String()
  39. return strings.Contains(out, "RUN sleep infinity"), fmt.Sprintf("'RUN sleep infinity' not found in : \n%s\nStderr: \n%s\n", out, errors)
  40. }, 30*time.Second, 1*time.Second)
  41. err = syscall.Kill(-cmd.Process.Pid, syscall.SIGINT) // simulate Ctrl-C : send signal to processGroup, children will have same groupId by default
  42. assert.NilError(t, err)
  43. c.WaitForCondition(func() (bool, string) {
  44. out := stdout.String()
  45. errors := stderr.String()
  46. return strings.Contains(out, "CANCELED"), fmt.Sprintf("'CANCELED' not found in : \n%s\nStderr: \n%s\n", out, errors)
  47. }, 10*time.Second, 1*time.Second)
  48. })
  49. }
  50. func StartWithNewGroupID(command icmd.Cmd) (*exec.Cmd, *bytes.Buffer, *bytes.Buffer, error) {
  51. cmd := exec.Command(command.Command[0], command.Command[1:]...)
  52. cmd.Env = command.Env
  53. cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
  54. var stdout bytes.Buffer
  55. var stderr bytes.Buffer
  56. cmd.Stdout = &stdout
  57. cmd.Stderr = &stderr
  58. err := cmd.Start()
  59. return cmd, &stdout, &stderr, err
  60. }