1
0
mirror of https://github.com/golang/go synced 2024-09-23 07:23:18 -06:00

os: improve TestExecutable

Instead of running all tests and relying on an init function, let's
embed the child code into the test case and only run one specific test.

Change-Id: Ib04e8a580556e7e30ff776c2041f0b809b440a26
Reviewed-on: https://go-review.googlesource.com/c/go/+/609838
Reviewed-by: Ian Lance Taylor <iant@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>
Reviewed-by: Dmitri Shuralyov <dmitshur@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
This commit is contained in:
Kir Kolyshkin 2024-08-29 23:37:08 -07:00 committed by Gopher Robot
parent 1ae6b9e31b
commit 8eefc3b8f0

View File

@ -13,11 +13,29 @@ import (
"testing"
)
const executable_EnvVar = "OSTEST_OUTPUT_EXECPATH"
func TestExecutable(t *testing.T) {
t.Parallel()
const helperEnvVar = "OSTEST_OUTPUT_EXECPATH"
if os.Getenv(helperEnvVar) != "" {
// First chdir to another path.
dir := "/"
if runtime.GOOS == "windows" {
cwd, err := os.Getwd()
if err != nil {
panic(err)
}
dir = filepath.VolumeName(cwd)
}
os.Chdir(dir)
if ep, err := os.Executable(); err != nil {
fmt.Fprint(os.Stderr, "ERROR: ", err)
} else {
fmt.Fprint(os.Stderr, ep)
}
os.Exit(0)
}
t.Parallel()
ep := testenv.Executable(t)
// we want fn to be of the form "dir/prog"
dir := filepath.Dir(filepath.Dir(ep))
@ -26,7 +44,7 @@ func TestExecutable(t *testing.T) {
t.Fatalf("filepath.Rel: %v", err)
}
cmd := testenv.Command(t, fn, "-test.run=^$")
cmd := testenv.Command(t, fn, "-test.run=^"+t.Name()+"$")
// make child start with a relative program path
cmd.Dir = dir
cmd.Path = fn
@ -37,7 +55,7 @@ func TestExecutable(t *testing.T) {
// get real path of the executable without influenced by argv[0].
cmd.Args[0] = "-"
}
cmd.Env = append(cmd.Environ(), fmt.Sprintf("%s=1", executable_EnvVar))
cmd.Env = append(cmd.Environ(), fmt.Sprintf("%s=1", helperEnvVar))
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("exec(self) failed: %v", err)
@ -63,27 +81,6 @@ func sameFile(fn1, fn2 string) bool {
return os.SameFile(fi1, fi2)
}
func init() {
if e := os.Getenv(executable_EnvVar); e != "" {
// first chdir to another path
dir := "/"
if runtime.GOOS == "windows" {
cwd, err := os.Getwd()
if err != nil {
panic(err)
}
dir = filepath.VolumeName(cwd)
}
os.Chdir(dir)
if ep, err := os.Executable(); err != nil {
fmt.Fprint(os.Stderr, "ERROR: ", err)
} else {
fmt.Fprint(os.Stderr, ep)
}
os.Exit(0)
}
}
func TestExecutableDeleted(t *testing.T) {
testenv.MustHaveGoBuild(t)
switch runtime.GOOS {