1
0

exec.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package testutil
  2. import (
  3. "os"
  4. "os/exec"
  5. "strings"
  6. "github.com/cockroachdb/errors"
  7. )
  8. // Exec executes "go test" on given helper with supplied environment variables.
  9. // It is useful to mock "os/exec" functions in tests. When succeeded, it returns
  10. // the result produced by the test helper.
  11. // The test helper should:
  12. // 1. Use WantHelperProcess function to determine if it is being called in helper mode.
  13. // 2. Call fmt.Fprintln(os.Stdout, ...) to print results for the main test to collect.
  14. func Exec(helper string, envs ...string) (string, error) {
  15. cmd := exec.Command(os.Args[0], "-test.run="+helper, "--")
  16. cmd.Env = []string{
  17. "GO_WANT_HELPER_PROCESS=1",
  18. "GOCOVERDIR=" + os.TempDir(),
  19. }
  20. cmd.Env = append(cmd.Env, envs...)
  21. out, err := cmd.CombinedOutput()
  22. str := string(out)
  23. // The error is quite confusing even when tests passed, so let's check whether
  24. // it is passed first.
  25. if strings.Contains(str, "no tests to run") {
  26. return "", errors.New("no tests to run")
  27. } else if i := strings.Index(str, "PASS"); i >= 0 {
  28. // Collect helper result
  29. return strings.TrimSpace(str[:i]), nil
  30. }
  31. if err != nil {
  32. return "", errors.Newf("%v - %s", err, str)
  33. }
  34. return "", errors.New(str)
  35. }
  36. // WantHelperProcess returns true if current process is in helper mode.
  37. func WantHelperProcess() bool {
  38. return os.Getenv("GO_WANT_HELPER_PROCESS") == "1"
  39. }