exec.go 1.5 KB

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