exec.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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{"GO_WANT_HELPER_PROCESS=1"}
  21. cmd.Env = append(cmd.Env, envs...)
  22. out, err := cmd.CombinedOutput()
  23. str := string(out)
  24. if err != nil {
  25. return "", fmt.Errorf("%v - %s", err, str)
  26. }
  27. if strings.Contains(str, "no tests to run") {
  28. return "", errors.New("no tests to run")
  29. } else if !strings.Contains(str, "PASS") {
  30. return "", errors.New(str)
  31. }
  32. // Collect helper result
  33. result := str[:strings.Index(str, "PASS")]
  34. result = strings.TrimSpace(result)
  35. return result, nil
  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. }