]> Cypherpunks.ru repositories - gostls13.git/commitdiff
internal/testenv: use cmd.Environ in CleanCmdEnv
authorCherry Mui <cherryyz@google.com>
Fri, 27 Oct 2023 16:30:53 +0000 (12:30 -0400)
committerCherry Mui <cherryyz@google.com>
Fri, 27 Oct 2023 17:53:23 +0000 (17:53 +0000)
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 <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Bryan Mills <bcmills@google.com>
src/internal/testenv/exec.go
src/internal/testenv/testenv_test.go

index 50d3b0dc73131ca7c8ae0a2688723efbd5200a69..7f6ad5cac4e39b603c0f59b797ff84c926a5bc5d 100644 (file)
@@ -100,11 +100,14 @@ func MustHaveExecPath(t testing.TB, path string) {
 // CleanCmdEnv will fill cmd.Env with the environment, excluding certain
 // variables that could modify the behavior of the Go tools such as
 // GODEBUG and GOTRACEBACK.
+//
+// If the caller wants to set cmd.Dir, set it before calling this function,
+// so PWD will be set correctly in the environment.
 func CleanCmdEnv(cmd *exec.Cmd) *exec.Cmd {
        if cmd.Env != nil {
                panic("environment already set")
        }
-       for _, env := range os.Environ() {
+       for _, env := range cmd.Environ() {
                // Exclude GODEBUG from the environment to prevent its output
                // from breaking tests that are trying to parse other command output.
                if strings.HasPrefix(env, "GODEBUG=") {
index d748e41540a4adfbdc94b3e1d1b331b3baec414c..d39a02b9814cd99dca993361b422aeebc5d7bba6 100644 (file)
@@ -163,3 +163,26 @@ func TestMustHaveExec(t *testing.T) {
                }
        }
 }
+
+func TestCleanCmdEnvPWD(t *testing.T) {
+       // Test that CleanCmdEnv sets PWD if cmd.Dir is set.
+       switch runtime.GOOS {
+       case "plan9", "windows":
+               t.Skipf("PWD is not used on %s", runtime.GOOS)
+       }
+       dir := t.TempDir()
+       cmd := testenv.Command(t, testenv.GoToolPath(t), "help")
+       cmd.Dir = dir
+       cmd = testenv.CleanCmdEnv(cmd)
+
+       for _, env := range cmd.Env {
+               if strings.HasPrefix(env, "PWD=") {
+                       pwd := strings.TrimPrefix(env, "PWD=")
+                       if pwd != dir {
+                               t.Errorf("unexpected PWD: want %s, got %s", dir, pwd)
+                       }
+                       return
+               }
+       }
+       t.Error("PWD not set in cmd.Env")
+}