Skip to content

Commit

Permalink
os: improve TestExecutable
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
kolyshkin authored and gopherbot committed Sep 3, 2024
1 parent 1ae6b9e commit 8eefc3b
Showing 1 changed file with 23 additions and 26 deletions.
49 changes: 23 additions & 26 deletions src/os/executable_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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
Expand All @@ -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)
Expand All @@ -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 {
Expand Down

0 comments on commit 8eefc3b

Please sign in to comment.