cancel_test.go 2.3 KB

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