exec.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. // Copyright 2023 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package testenv
  5. import (
  6. "context"
  7. "os"
  8. "os/exec"
  9. "reflect"
  10. "strconv"
  11. "testing"
  12. "time"
  13. )
  14. // CommandContext is like exec.CommandContext, but:
  15. // - skips t if the platform does not support os/exec,
  16. // - sends SIGQUIT (if supported by the platform) instead of SIGKILL
  17. // in its Cancel function
  18. // - if the test has a deadline, adds a Context timeout and WaitDelay
  19. // for an arbitrary grace period before the test's deadline expires,
  20. // - fails the test if the command does not complete before the test's deadline, and
  21. // - sets a Cleanup function that verifies that the test did not leak a subprocess.
  22. func CommandContext(t testing.TB, ctx context.Context, name string, args ...string) *exec.Cmd {
  23. t.Helper()
  24. var (
  25. cancelCtx context.CancelFunc
  26. gracePeriod time.Duration // unlimited unless the test has a deadline (to allow for interactive debugging)
  27. )
  28. if t, ok := t.(interface {
  29. testing.TB
  30. Deadline() (time.Time, bool)
  31. }); ok {
  32. if td, ok := t.Deadline(); ok {
  33. // Start with a minimum grace period, just long enough to consume the
  34. // output of a reasonable program after it terminates.
  35. gracePeriod = 100 * time.Millisecond
  36. if s := os.Getenv("GO_TEST_TIMEOUT_SCALE"); s != "" {
  37. scale, err := strconv.Atoi(s)
  38. if err != nil {
  39. t.Fatalf("invalid GO_TEST_TIMEOUT_SCALE: %v", err)
  40. }
  41. gracePeriod *= time.Duration(scale)
  42. }
  43. // If time allows, increase the termination grace period to 5% of the
  44. // test's remaining time.
  45. testTimeout := time.Until(td)
  46. if gp := testTimeout / 20; gp > gracePeriod {
  47. gracePeriod = gp
  48. }
  49. // When we run commands that execute subprocesses, we want to reserve two
  50. // grace periods to clean up: one for the delay between the first
  51. // termination signal being sent (via the Cancel callback when the Context
  52. // expires) and the process being forcibly terminated (via the WaitDelay
  53. // field), and a second one for the delay between the process being
  54. // terminated and the test logging its output for debugging.
  55. //
  56. // (We want to ensure that the test process itself has enough time to
  57. // log the output before it is also terminated.)
  58. cmdTimeout := testTimeout - 2*gracePeriod
  59. if cd, ok := ctx.Deadline(); !ok || time.Until(cd) > cmdTimeout {
  60. // Either ctx doesn't have a deadline, or its deadline would expire
  61. // after (or too close before) the test has already timed out.
  62. // Add a shorter timeout so that the test will produce useful output.
  63. ctx, cancelCtx = context.WithTimeout(ctx, cmdTimeout)
  64. }
  65. }
  66. }
  67. cmd := exec.CommandContext(ctx, name, args...)
  68. // Set the Cancel and WaitDelay fields only if present (go 1.20 and later).
  69. // TODO: When Go 1.19 is no longer supported, remove this use of reflection
  70. // and instead set the fields directly.
  71. if cmdCancel := reflect.ValueOf(cmd).Elem().FieldByName("Cancel"); cmdCancel.IsValid() {
  72. cmdCancel.Set(reflect.ValueOf(func() error {
  73. if cancelCtx != nil && ctx.Err() == context.DeadlineExceeded {
  74. // The command timed out due to running too close to the test's deadline.
  75. // There is no way the test did that intentionally — it's too close to the
  76. // wire! — so mark it as a test failure. That way, if the test expects the
  77. // command to fail for some other reason, it doesn't have to distinguish
  78. // between that reason and a timeout.
  79. t.Errorf("test timed out while running command: %v", cmd)
  80. } else {
  81. // The command is being terminated due to ctx being canceled, but
  82. // apparently not due to an explicit test deadline that we added.
  83. // Log that information in case it is useful for diagnosing a failure,
  84. // but don't actually fail the test because of it.
  85. t.Logf("%v: terminating command: %v", ctx.Err(), cmd)
  86. }
  87. return cmd.Process.Signal(Sigquit)
  88. }))
  89. }
  90. if cmdWaitDelay := reflect.ValueOf(cmd).Elem().FieldByName("WaitDelay"); cmdWaitDelay.IsValid() {
  91. cmdWaitDelay.Set(reflect.ValueOf(gracePeriod))
  92. }
  93. t.Cleanup(func() {
  94. if cancelCtx != nil {
  95. cancelCtx()
  96. }
  97. if cmd.Process != nil && cmd.ProcessState == nil {
  98. t.Errorf("command was started, but test did not wait for it to complete: %v", cmd)
  99. }
  100. })
  101. return cmd
  102. }
  103. // Command is like exec.Command, but applies the same changes as
  104. // testenv.CommandContext (with a default Context).
  105. func Command(t testing.TB, name string, args ...string) *exec.Cmd {
  106. t.Helper()
  107. return CommandContext(t, context.Background(), name, args...)
  108. }