all: fix tests in preparation for GO111MODULE=on by default

This CL does not fix failures in ./gopls/internal/regtest, which will
be fixed separately.

In refactor/rename.TestDiff, add a go.mod file.

In internal/imports.ProcessEnv.buildContext, set an I/O hook if
GO111MODULE=off in ProcessEnv but not in the current process's
environment.

Context allows the user to set GOPATH, GOOS, GOARCH, and a few other
environment variables, but not GO111MODULE. Context.Import may return
different results than packages.Load if the latter is invoked with a
GO111MODULE value that differs from the caller's environment. Setting
an I/O hook forces Import to run in GOPATH mode, not invoking 'go list'.
This is undocumented, but it should be stable while GOPATH is
supported.

For golang/go#41330

Change-Id: I5679e8941e32dc95b05c234cb2e3fec5cabebced
Reviewed-on: https://go-review.googlesource.com/c/tools/+/255398
Run-TryBot: Jay Conrod <jayconrod@google.com>
Reviewed-by: Heschi Kreinick <heschi@google.com>
Reviewed-by: Bryan C. Mills <bcmills@google.com>
gopls-CI: kokoro <noreply+kokoro@google.com>
TryBot-Result: Go Bot <gobot@golang.org>
Trust: Jay Conrod <jayconrod@google.com>
diff --git a/internal/imports/fix.go b/internal/imports/fix.go
index a006d6e..675d16c 100644
--- a/internal/imports/fix.go
+++ b/internal/imports/fix.go
@@ -928,6 +928,17 @@
 		dir.SetString(e.WorkingDir)
 	}
 
+	// Since Go 1.11, go/build.Context.Import may invoke 'go list' depending on
+	// the value in GO111MODULE in the process's environment. We always want to
+	// run in GOPATH mode when calling Import, so we need to prevent this from
+	// happening. In Go 1.16, GO111MODULE defaults to "on", so this problem comes
+	// up more frequently.
+	//
+	// HACK: setting any of the Context I/O hooks prevents Import from invoking
+	// 'go list', regardless of GO111MODULE. This is undocumented, but it's
+	// unlikely to change before GOPATH support is removed.
+	ctx.ReadDir = ioutil.ReadDir
+
 	return &ctx, nil
 }
 
diff --git a/refactor/rename/rename_test.go b/refactor/rename/rename_test.go
index 0369d7c..3dfdc18 100644
--- a/refactor/rename/rename_test.go
+++ b/refactor/rename/rename_test.go
@@ -1325,6 +1325,14 @@
 		t.Fatal(err)
 	}
 
+	const modFile = `module example.com/rename
+
+go 1.15
+`
+	if err := ioutil.WriteFile(filepath.Join(pkgDir, "go.mod"), []byte(modFile), 0644); err != nil {
+		t.Fatal(err)
+	}
+
 	const goFile = `package rename
 
 func justHereForTestingDiff() {