Debian Codegraph @

gopls/internal/test/integration/env.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 "fmt"
10 "net/http/httptest"
11 "os"
12 "os/exec"
13 "strings"
14 "sync"
15 "sync/atomic"
16 "testing"
17
18 "github.com/modelcontextprotocol/go-sdk/mcp"
19 "golang.org/x/tools/gopls/internal/protocol"
20 "golang.org/x/tools/gopls/internal/test/integration/fake"
21 "golang.org/x/tools/internal/jsonrpc2/servertest"
22 )
23
24 // Env holds the building blocks of an editor testing environment, providing
25 // wrapper methods that hide the boilerplate of plumbing contexts and checking
26 // errors.
27 // Call [Env.Shutdown] for cleaning up resources after the test.
28 type Env struct {
29 TB testing.TB
30 Ctx context.Context
31
32 // Most tests should not need to access the scratch area, editor, server, or
33 // connection, but they are available if needed.
34 Sandbox *fake.Sandbox
35 Server servertest.Connector
36
37 // Editor is owned by the Env, and shut down
38 Editor *fake.Editor
39
40 Awaiter *Awaiter
41
42 // MCPServer, MCPSession and EventChan is owned by the Env, and shut down.
43 // Only available if the test enables MCP Server.
44 MCPServer *httptest.Server
45 MCPSession *mcp.ClientSession
46 }
47
48 // nextAwaiterRegistration is used to create unique IDs for various Awaiter
49 // registrations.
50 var nextAwaiterRegistration atomic.Uint64
51
52 // An Awaiter keeps track of relevant LSP state, so that it may be asserted
53 // upon with Expectations.
54 //
55 // Wire it into a fake.Editor using Awaiter.Hooks().
56 //
57 // TODO(rfindley): consider simply merging Awaiter with the fake.Editor. It
58 // probably is not worth its own abstraction.
59 type Awaiter struct {
60 workdir *fake.Workdir
61
62 mu sync.Mutex
63 // For simplicity, each waiter gets a unique ID.
64 state State
65 waiters map[uint64]*condition
66
67 // collectors map a registration to the collection of messages that have been
68 // received since the registration was created.
69 docCollectors map[uint64][]*protocol.ShowDocumentParams
70 messageCollectors map[uint64][]*protocol.ShowMessageParams
71 }
72
73 func NewAwaiter(workdir *fake.Workdir) *Awaiter {
74 return &Awaiter{
75 workdir: workdir,
76 state: State{
77 diagnostics: make(map[string]*protocol.PublishDiagnosticsParams),
78 work: make(map[protocol.ProgressToken]*workProgress),
79 startedWork: make(map[string]uint64),
80 completedWork: make(map[string]uint64),
81 },
82 waiters: make(map[uint64]*condition),
83 }
84 }
85
86 // Hooks returns LSP client hooks required for awaiting asynchronous expectations.
87 func (a *Awaiter) Hooks() fake.ClientHooks {
88 return fake.ClientHooks{
89 OnDiagnostics: a.onDiagnostics,
90 OnLogMessage: a.onLogMessage,
91 OnWorkDoneProgressCreate: a.onWorkDoneProgressCreate,
92 OnProgress: a.onProgress,
93 OnShowDocument: a.onShowDocument,
94 OnShowMessage: a.onShowMessage,
95 OnShowMessageRequest: a.onShowMessageRequest,
96 OnRegisterCapability: a.onRegisterCapability,
97 OnUnregisterCapability: a.onUnregisterCapability,
98 }
99 }
100
101 // State encapsulates the server state TODO: explain more
102 type State struct {
103 // diagnostics are a map of relative path->diagnostics params
104 diagnostics map[string]*protocol.PublishDiagnosticsParams
105 logs []*protocol.LogMessageParams
106 showDocument []*protocol.ShowDocumentParams
107 showMessage []*protocol.ShowMessageParams
108 showMessageRequest []*protocol.ShowMessageRequestParams
109
110 registrations []*protocol.RegistrationParams
111 registeredCapabilities map[string]protocol.Registration
112 unregistrations []*protocol.UnregistrationParams
113
114 // outstandingWork is a map of token->work summary. All tokens are assumed to
115 // be string, though the spec allows for numeric tokens as well.
116 work map[protocol.ProgressToken]*workProgress
117 startedWork map[string]uint64 // title -> count of 'begin'
118 completedWork map[string]uint64 // title -> count of 'end'
119 }
120
121 type workProgress struct {
122 title, msg, endMsg string
123 percent float64
124 complete bool // seen 'end'
125 }
126
127 type awaitResult struct {
128 verdict Verdict
129 reason string
130 }
131
132 // A condition is satisfied when its expectation is [Met] or [Unmeetable]. The
133 // result is sent on the verdict channel.
134 type condition struct {
135 expectation Expectation
136 verdict chan awaitResult
137 }
138
139 func (a *Awaiter) onDiagnostics(_ context.Context, d *protocol.PublishDiagnosticsParams) error {
140 a.mu.Lock()
141 defer a.mu.Unlock()
142
143 pth := a.workdir.URIToPath(d.URI)
144 a.state.diagnostics[pth] = d
145 a.checkConditionsLocked()
146 return nil
147 }
148
149 func (a *Awaiter) onShowDocument(_ context.Context, params *protocol.ShowDocumentParams) error {
150 a.mu.Lock()
151 defer a.mu.Unlock()
152
153 // Update any outstanding listeners.
154 for id, s := range a.docCollectors {
155 a.docCollectors[id] = append(s, params)
156 }
157
158 a.state.showDocument = append(a.state.showDocument, params)
159 a.checkConditionsLocked()
160 return nil
161 }
162
163 // ListenToShownDocuments registers a listener to incoming showDocument
164 // notifications. Call the resulting func to deregister the listener and
165 // receive all notifications that have occurred since the listener was
166 // registered.
167 func (a *Awaiter) ListenToShownDocuments() func() []*protocol.ShowDocumentParams {
168 id := nextAwaiterRegistration.Add(1)
169
170 a.mu.Lock()
171 defer a.mu.Unlock()
172
173 if a.docCollectors == nil {
174 a.docCollectors = make(map[uint64][]*protocol.ShowDocumentParams)
175 }
176 a.docCollectors[id] = nil
177
178 return func() []*protocol.ShowDocumentParams {
179 a.mu.Lock()
180 defer a.mu.Unlock()
181 params := a.docCollectors[id]
182 delete(a.docCollectors, id)
183 return params
184 }
185 }
186
187 func (a *Awaiter) onShowMessage(_ context.Context, params *protocol.ShowMessageParams) error {
188 a.mu.Lock()
189 defer a.mu.Unlock()
190
191 // Update any outstanding listeners.
192 for id, s := range a.messageCollectors {
193 a.messageCollectors[id] = append(s, params)
194 }
195
196 a.state.showMessage = append(a.state.showMessage, params)
197 a.checkConditionsLocked()
198 return nil
199 }
200
201 // ListenToShownMessages registers a listener to incoming showMessage
202 // notifications. Call the resulting func to deregister the listener and
203 // receive all notifications that have occurred since the listener was
204 // registered.
205 //
206 // ListenToShownMessages should be called before the operation that
207 // generates the showMessage event to ensure that the event is
208 // reliably collected.
209 func (a *Awaiter) ListenToShownMessages() func() []*protocol.ShowMessageParams {
210 id := nextAwaiterRegistration.Add(1)
211
212 a.mu.Lock()
213 defer a.mu.Unlock()
214
215 if a.messageCollectors == nil {
216 a.messageCollectors = make(map[uint64][]*protocol.ShowMessageParams)
217 }
218 a.messageCollectors[id] = nil
219
220 return func() []*protocol.ShowMessageParams {
221 a.mu.Lock()
222 defer a.mu.Unlock()
223 params := a.messageCollectors[id]
224 delete(a.messageCollectors, id)
225 return params
226 }
227 }
228
229 func (a *Awaiter) onShowMessageRequest(_ context.Context, m *protocol.ShowMessageRequestParams) error {
230 a.mu.Lock()
231 defer a.mu.Unlock()
232
233 a.state.showMessageRequest = append(a.state.showMessageRequest, m)
234 a.checkConditionsLocked()
235 return nil
236 }
237
238 func (a *Awaiter) onLogMessage(_ context.Context, m *protocol.LogMessageParams) error {
239 a.mu.Lock()
240 defer a.mu.Unlock()
241
242 a.state.logs = append(a.state.logs, m)
243 a.checkConditionsLocked()
244 return nil
245 }
246
247 func (a *Awaiter) onWorkDoneProgressCreate(_ context.Context, m *protocol.WorkDoneProgressCreateParams) error {
248 a.mu.Lock()
249 defer a.mu.Unlock()
250
251 a.state.work[m.Token] = &workProgress{}
252 return nil
253 }
254
255 func (a *Awaiter) onProgress(_ context.Context, m *protocol.ProgressParams) error {
256 a.mu.Lock()
257 defer a.mu.Unlock()
258 work, ok := a.state.work[m.Token]
259 if !ok {
260 panic(fmt.Sprintf("got progress report for unknown report %v: %v", m.Token, m))
261 }
262 v := m.Value.(map[string]any)
263 switch kind := v["kind"]; kind {
264 case "begin":
265 work.title = v["title"].(string)
266 a.state.startedWork[work.title]++
267 if msg, ok := v["message"]; ok {
268 work.msg = msg.(string)
269 }
270 case "report":
271 if pct, ok := v["percentage"]; ok {
272 work.percent = pct.(float64)
273 }
274 if msg, ok := v["message"]; ok {
275 work.msg = msg.(string)
276 }
277 case "end":
278 work.complete = true
279 a.state.completedWork[work.title]++
280 if msg, ok := v["message"]; ok {
281 work.endMsg = msg.(string)
282 }
283 }
284 a.checkConditionsLocked()
285 return nil
286 }
287
288 func (a *Awaiter) onRegisterCapability(_ context.Context, m *protocol.RegistrationParams) error {
289 a.mu.Lock()
290 defer a.mu.Unlock()
291
292 a.state.registrations = append(a.state.registrations, m)
293 if a.state.registeredCapabilities == nil {
294 a.state.registeredCapabilities = make(map[string]protocol.Registration)
295 }
296 for _, reg := range m.Registrations {
297 a.state.registeredCapabilities[reg.Method] = reg
298 }
299 a.checkConditionsLocked()
300 return nil
301 }
302
303 func (a *Awaiter) onUnregisterCapability(_ context.Context, m *protocol.UnregistrationParams) error {
304 a.mu.Lock()
305 defer a.mu.Unlock()
306
307 a.state.unregistrations = append(a.state.unregistrations, m)
308 a.checkConditionsLocked()
309 return nil
310 }
311
312 func (a *Awaiter) checkConditionsLocked() {
313 for id, condition := range a.waiters {
314 if v, why := condition.expectation.Check(a.state); v != Unmet {
315 delete(a.waiters, id)
316 condition.verdict <- awaitResult{v, why}
317 }
318 }
319 }
320
321 // Await blocks until the given expectations are all simultaneously met.
322 //
323 // Generally speaking Await should be avoided because it blocks indefinitely if
324 // gopls ends up in a state where the expectations are never going to be met.
325 // Use AfterChange or OnceMet instead, so that the runner knows when to stop
326 // waiting.
327 func (e *Env) Await(expectations ...Expectation) {
328 e.TB.Helper()
329 if err := e.Awaiter.Await(e.Ctx, AllOf(expectations...)); err != nil {
330 e.TB.Fatal(err)
331 }
332 }
333
334 // OnceMet blocks until the precondition is met by the state or becomes
335 // unmeetable. If it was met, OnceMet checks that the state meets all
336 // expectations in mustMeets.
337 func (e *Env) OnceMet(pre Expectation, mustMeets ...Expectation) {
338 e.TB.Helper()
339 e.Await(OnceMet(pre, AllOf(mustMeets...)))
340 }
341
342 // Await waits for all expectations to simultaneously be met. It should only be
343 // called from the main test goroutine.
344 func (a *Awaiter) Await(ctx context.Context, expectation Expectation) error {
345 a.mu.Lock()
346 // Before adding the waiter, we check if the condition is currently met or
347 // failed to avoid a race where the condition was realized before Await was
348 // called.
349 switch verdict, why := expectation.Check(a.state); verdict {
350 case Met:
351 a.mu.Unlock()
352 return nil
353 case Unmeetable:
354 err := fmt.Errorf("unmeetable expectation:\n%s\nreason:\n%s", indent(expectation.Description), indent(why))
355 a.mu.Unlock()
356 return err
357 }
358 cond := &condition{
359 expectation: expectation,
360 verdict: make(chan awaitResult),
361 }
362 a.waiters[nextAwaiterRegistration.Add(1)] = cond
363 a.mu.Unlock()
364
365 var err error
366 select {
367 case <-ctx.Done():
368 err = ctx.Err()
369 case res := <-cond.verdict:
370 if res.verdict != Met {
371 err = fmt.Errorf("the following condition is %s:\n%s\nreason:\n%s",
372 res.verdict, indent(expectation.Description), indent(res.reason))
373 }
374 }
375 return err
376 }
377
378 // indent indents all lines of msg, including the first.
379 func indent(msg string) string {
380 const prefix = " "
381 return prefix + strings.ReplaceAll(msg, "\n", "\n"+prefix)
382 }
383
384 // CleanModCache cleans the specified GOMODCACHE.
385 //
386 // TODO(golang/go#74595): this is only necessary as the module cache cleaning of the
387 // sandbox does not respect GOMODCACHE set via EnvVars. We should fix this, but
388 // that is probably part of a larger refactoring of the sandbox that I'm not
389 // inclined to undertake. --rfindley.
390 //
391 // (For similar problems caused by the same bug, see Test_issue38211; see also
392 // comment in Sandbox.Env.)
393 func CleanModCache(t *testing.T, modcache string) {
394 cmd := exec.Command("go", "clean", "-modcache")
395 cmd.Env = append(os.Environ(), "GOMODCACHE="+modcache, "GOTOOLCHAIN=local")
396 if output, err := cmd.CombinedOutput(); err != nil {
397 t.Errorf("cleaning modcache: %v\noutput:\n%s", err, string(output))
398 }
399 }
400
401 // CodeActionByKind returns the first action of (exactly) the specified kind, or an error.
402 func CodeActionByKind(actions []protocol.CodeAction, kind protocol.CodeActionKind) (*protocol.CodeAction, error) {
403 for _, act := range actions {
404 if act.Kind == kind {
405 return &act, nil
406 }
407 }
408 return nil, fmt.Errorf("can't find action with kind %s, only %#v", kind, actions)
409 }