Debian Codegraph @

gopls/internal/test/integration/regtest.go

raw symbols SCIP
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package integration
6
7 import (
8 "context"
9 "flag"
10 "fmt"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "runtime"
15 "strings"
16 "testing"
17 "time"
18
19 "golang.org/x/tools/gopls/internal/cache"
20 "golang.org/x/tools/gopls/internal/cmd"
21 "golang.org/x/tools/gopls/internal/tool"
22 "golang.org/x/tools/gopls/internal/util/memoize"
23 "golang.org/x/tools/internal/drivertest"
24 "golang.org/x/tools/internal/gocommand"
25 "golang.org/x/tools/internal/testenv"
26 )
27
28 var (
29 runSubprocessTests = flag.Bool("enable_gopls_subprocess_tests", false, "run integration tests against a gopls subprocess (default: in-process)")
30 goplsBinaryPath = flag.String("gopls_test_binary", "", "path to the gopls binary for use as a remote, for use with the -enable_gopls_subprocess_tests flag")
31 timeout = flag.Duration("timeout", defaultTimeout(), "if nonzero, default timeout for each integration test; defaults to GOPLS_INTEGRATION_TEST_TIMEOUT")
32 skipCleanup = flag.Bool("skip_cleanup", false, "whether to skip cleaning up temp directories")
33 printGoroutinesOnFailure = flag.Bool("print_goroutines", false, "whether to print goroutines info on failure")
34 printLogs = flag.Bool("print_logs", false, "whether to print LSP logs")
35 )
36
37 func defaultTimeout() time.Duration {
38 s := os.Getenv("GOPLS_INTEGRATION_TEST_TIMEOUT")
39 if s == "" {
40 return 0
41 }
42 d, err := time.ParseDuration(s)
43 if err != nil {
44 fmt.Fprintf(os.Stderr, "invalid GOPLS_INTEGRATION_TEST_TIMEOUT %q: %v\n", s, err)
45 os.Exit(2)
46 }
47 return d
48 }
49
50 var runner *Runner
51
52 func Run(t *testing.T, files string, f TestFunc) {
53 runner.Run(t, files, f)
54 }
55
56 func WithOptions(opts ...RunOption) configuredRunner {
57 return configuredRunner{opts: opts}
58 }
59
60 type configuredRunner struct {
61 opts []RunOption
62 }
63
64 func (r configuredRunner) Run(t *testing.T, files string, f TestFunc) {
65 // Print a warning if the test's temporary directory is not
66 // suitable as a workspace folder, as this may lead to
67 // otherwise-cryptic failures. This situation typically occurs
68 // when an arbitrary string (e.g. "foo.") is used as a subtest
69 // name, on a platform with filename restrictions (e.g. no
70 // trailing period on Windows).
71 tmp := t.TempDir()
72 if err := cache.CheckPathValid(tmp); err != nil {
73 t.Logf("Warning: testing.T.TempDir(%s) is not valid as a workspace folder: %s",
74 tmp, err)
75 }
76
77 runner.Run(t, files, f, r.opts...)
78 }
79
80 // RunMultiple runs a test multiple times, with different options.
81 // The runner should be constructed with [WithOptions].
82 //
83 // TODO(rfindley): replace Modes with selective use of RunMultiple.
84 type RunMultiple []struct {
85 Name string
86 Runner interface {
87 Run(t *testing.T, files string, f TestFunc)
88 }
89 }
90
91 func (r RunMultiple) Run(t *testing.T, files string, f TestFunc) {
92 for _, runner := range r {
93 t.Run(runner.Name, func(t *testing.T) {
94 runner.Runner.Run(t, files, f)
95 })
96 }
97 }
98
99 // DefaultModes returns the default modes to run for each regression test (they
100 // may be reconfigured by the tests themselves).
101 func DefaultModes() Mode {
102 modes := Default
103 if !testing.Short() {
104 // TODO(rfindley): we should just run a few select integration tests in
105 // "Forwarded" mode, and call it a day. No need to run every single test in
106 // two ways.
107 modes |= Forwarded
108 }
109 if *runSubprocessTests {
110 modes |= SeparateProcess
111 }
112 return modes
113 }
114
115 var runFromMain = false // true if Main has been called
116
117 // Main sets up and tears down the shared integration test state.
118 func Main(m *testing.M) (code int) {
119 // Provide an entrypoint for tests that use a fake go/packages driver.
120 drivertest.RunIfChild()
121
122 defer func() {
123 if runner != nil {
124 if err := runner.Close(); err != nil {
125 fmt.Fprintf(os.Stderr, "closing test runner: %v\n", err)
126 // Cleanup is broken in go1.12 and earlier, and sometimes flakes on
127 // Windows due to file locking, but this is OK for our CI.
128 //
129 // Fail on go1.13+, except for windows and android which have shutdown problems.
130 if testenv.Go1Point() >= 13 && runtime.GOOS != "windows" && runtime.GOOS != "android" {
131 if code == 0 {
132 code = 1
133 }
134 }
135 }
136 }
137 }()
138
139 runFromMain = true
140
141 // golang/go#54461: enable additional debugging around hanging Go commands.
142 gocommand.DebugHangingGoCommands = true
143
144 // If this magic environment variable is set, run gopls instead of the test
145 // suite. See the documentation for runTestAsGoplsEnvvar for more details.
146 if os.Getenv(runTestAsGoplsEnvvar) == "true" {
147 tool.Main(context.Background(), cmd.New(), os.Args[1:])
148 return 0
149 }
150
151 if !testenv.HasExec() {
152 fmt.Printf("skipping all tests: exec not supported on %s/%s\n", runtime.GOOS, runtime.GOARCH)
153 return 0
154 }
155 testenv.ExitIfSmallMachine()
156
157 flag.Parse()
158
159 // Disable GOPACKAGESDRIVER, as it can cause spurious test failures.
160 os.Setenv("GOPACKAGESDRIVER", "off") // ignore error
161
162 if skipReason := checkBuilder(); skipReason != "" {
163 fmt.Printf("Skipping all tests: %s\n", skipReason)
164 return 0
165 }
166
167 if err := testenv.HasTool("go"); err != nil {
168 fmt.Println("Missing go command")
169 return 1
170 }
171
172 runner = &Runner{
173 DefaultModes: DefaultModes(),
174 Timeout: *timeout,
175 PrintGoroutinesOnFailure: *printGoroutinesOnFailure,
176 SkipCleanup: *skipCleanup,
177 store: memoize.NewStore(memoize.NeverEvict),
178 }
179
180 runner.goplsPath = *goplsBinaryPath
181 if runner.goplsPath == "" {
182 var err error
183 runner.goplsPath, err = os.Executable()
184 if err != nil {
185 panic(fmt.Sprintf("finding test binary path: %v", err))
186 }
187 }
188
189 dir, err := os.MkdirTemp("", "gopls-test-")
190 if err != nil {
191 panic(fmt.Errorf("creating temp directory: %v", err))
192 }
193 runner.tempDir = dir
194
195 FilterToolchainPathAndGOROOT()
196
197 return m.Run()
198 }
199
200 // FilterToolchainPathAndGOROOT updates the PATH and GOROOT environment
201 // variables for the current process to effectively revert the changes made by
202 // the go command when performing a toolchain switch in the context of `go
203 // test` (see golang/go#68005).
204 //
205 // It does this by looking through PATH for a go command that is NOT a
206 // toolchain go command, and adjusting PATH to find that go command. Then it
207 // unsets GOROOT in order to use the default GOROOT for that go command.
208 //
209 // TODO(rfindley): this is very much a hack, so that our 1.21 and 1.22 builders
210 // actually exercise integration with older go commands. In golang/go#69321, we
211 // hope to do better.
212 func FilterToolchainPathAndGOROOT() {
213 if localGo, first := findLocalGo(); localGo != "" && !first {
214 dir := filepath.Dir(localGo)
215 path := os.Getenv("PATH")
216 os.Setenv("PATH", dir+string(os.PathListSeparator)+path) // ignore error
217 os.Unsetenv("GOROOT") // Remove the GOROOT value that was added by toolchain switch.
218 }
219 }
220
221 // findLocalGo returns a path to a local (=non-toolchain) Go version, or the
222 // empty string if none is found.
223 //
224 // The second result reports if path matches the result of exec.LookPath.
225 func findLocalGo() (path string, first bool) {
226 paths := filepath.SplitList(os.Getenv("PATH"))
227 for _, path := range paths {
228 // Use a simple heuristic to filter out toolchain paths.
229 if strings.Contains(path, "[email protected]") && filepath.Base(path) == "bin" {
230 continue // toolchain path
231 }
232 fullPath := filepath.Join(path, "go")
233 fi, err := os.Stat(fullPath)
234 if err != nil {
235 continue
236 }
237 if fi.Mode()&0111 != 0 {
238 first := false
239 pathGo, err := exec.LookPath("go")
240 if err == nil {
241 first = fullPath == pathGo
242 }
243 return fullPath, first
244 }
245 }
246 return "", false
247 }