exec.go 1.3 KB

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