Skip to content

Commit 5613882

Browse files
committed
internal/testenv: use cmd.Environ in CleanCmdEnv
In CleanCmdEnv, use cmd.Environ instead of os.Environ, so it sets the PWD environment variable if cmd.Dir is set. This ensures the child process sees a canonical path for its working directory. Change-Id: Ia769552a488dc909eaf6bb7d21937adba06d1072 Reviewed-on: https://go-review.googlesource.com/c/go/+/538215 LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Bryan Mills <[email protected]>
1 parent b46aec0 commit 5613882

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/internal/testenv/exec.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,14 @@ func MustHaveExecPath(t testing.TB, path string) {
100100
// CleanCmdEnv will fill cmd.Env with the environment, excluding certain
101101
// variables that could modify the behavior of the Go tools such as
102102
// GODEBUG and GOTRACEBACK.
103+
//
104+
// If the caller wants to set cmd.Dir, set it before calling this function,
105+
// so PWD will be set correctly in the environment.
103106
func CleanCmdEnv(cmd *exec.Cmd) *exec.Cmd {
104107
if cmd.Env != nil {
105108
panic("environment already set")
106109
}
107-
for _, env := range os.Environ() {
110+
for _, env := range cmd.Environ() {
108111
// Exclude GODEBUG from the environment to prevent its output
109112
// from breaking tests that are trying to parse other command output.
110113
if strings.HasPrefix(env, "GODEBUG=") {

src/internal/testenv/testenv_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,3 +163,26 @@ func TestMustHaveExec(t *testing.T) {
163163
}
164164
}
165165
}
166+
167+
func TestCleanCmdEnvPWD(t *testing.T) {
168+
// Test that CleanCmdEnv sets PWD if cmd.Dir is set.
169+
switch runtime.GOOS {
170+
case "plan9", "windows":
171+
t.Skipf("PWD is not used on %s", runtime.GOOS)
172+
}
173+
dir := t.TempDir()
174+
cmd := testenv.Command(t, testenv.GoToolPath(t), "help")
175+
cmd.Dir = dir
176+
cmd = testenv.CleanCmdEnv(cmd)
177+
178+
for _, env := range cmd.Env {
179+
if strings.HasPrefix(env, "PWD=") {
180+
pwd := strings.TrimPrefix(env, "PWD=")
181+
if pwd != dir {
182+
t.Errorf("unexpected PWD: want %s, got %s", dir, pwd)
183+
}
184+
return
185+
}
186+
}
187+
t.Error("PWD not set in cmd.Env")
188+
}

0 commit comments

Comments
 (0)