Files
Gogs/internal/testutil/exec.go
Copilot 6d56105f8f Run modernize tool across codebase (#8147)
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Joe Chen <jc@unknwon.io>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: deepsource-autofix[bot] <62050782+deepsource-autofix[bot]@users.noreply.github.com>
2026-02-05 21:32:09 -05:00

46 lines
1.3 KiB
Go

package testutil
import (
"os"
"os/exec"
"strings"
"github.com/cockroachdb/errors"
)
// 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 mode.
// 2. Call fmt.Fprintln(os.Stdout, ...) to print results for the main test to collect.
func Exec(helper string, envs ...string) (string, error) {
cmd := exec.Command(os.Args[0], "-test.run="+helper, "--")
cmd.Env = []string{
"GO_WANT_HELPER_PROCESS=1",
"GOCOVERDIR=" + os.TempDir(),
}
cmd.Env = append(cmd.Env, envs...)
out, err := cmd.CombinedOutput()
str := string(out)
// The error is quite confusing even when tests passed, so let's check whether
// it is passed first.
if strings.Contains(str, "no tests to run") {
return "", errors.New("no tests to run")
} else if before, _, ok := strings.Cut(str, "PASS"); ok {
// Collect helper result
return strings.TrimSpace(before), nil
}
if err != nil {
return "", errors.Newf("%v - %s", err, str)
}
return "", errors.New(str)
}
// WantHelperProcess returns true if current process is in helper mode.
func WantHelperProcess() bool {
return os.Getenv("GO_WANT_HELPER_PROCESS") == "1"
}