Exec executes "go test" on given helper with supplied environment variables. It is useful to mock "os/exec" functions in tests. When succeeded, it returns the result produced by the test helper. The test helper should: 1. Use WantHelperProcess function to determine if it is being called in helper mo
(helper string, envs ...string)
| 15 | // 1. Use WantHelperProcess function to determine if it is being called in helper mode. |
| 16 | // 2. Call fmt.Fprintln(os.Stdout, ...) to print results for the main test to collect. |
| 17 | func Exec(helper string, envs ...string) (string, error) { |
| 18 | cmd := exec.Command(os.Args[0], "-test.run="+helper, "--") |
| 19 | cmd.Env = []string{ |
| 20 | "GO_WANT_HELPER_PROCESS=1", |
| 21 | "GOCOVERDIR=" + os.TempDir(), |
| 22 | } |
| 23 | cmd.Env = append(cmd.Env, envs...) |
| 24 | out, err := cmd.CombinedOutput() |
| 25 | str := string(out) |
| 26 | |
| 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 | |
| 36 | if err != nil { |
| 37 | return "", errors.Newf("%v - %s", err, str) |
| 38 | } |
| 39 | return "", errors.New(str) |
| 40 | } |
| 41 | |
| 42 | // WantHelperProcess returns true if current process is in helper mode. |
| 43 | func WantHelperProcess() bool { |