Debian Codegraph @

gopls/internal/test/integration/web/pkdoc_test.go

raw symbols SCIP
1 // Copyright 2025 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 web_test
6
7 import (
8 "fmt"
9 "html"
10 "regexp"
11 "strings"
12 "testing"
13
14 "golang.org/x/tools/gopls/internal/protocol"
15 "golang.org/x/tools/gopls/internal/settings"
16 . "golang.org/x/tools/gopls/internal/test/integration"
17 )
18
19 // TODO(adonovan): define marker test verbs for checking package docs.
20
21 // TestBrowsePkgDoc provides basic coverage of the "Browse package
22 // documentation", which creates a web server on demand.
23 func TestBrowsePkgDoc(t *testing.T) {
24 const files = `
25 -- go.mod --
26 module example.com
27
28 -- a/a.go --
29 package a
30
31 const A = 1
32
33 type G[T any] int
34 func (G[T]) F(int, int, int, int, int, int, int, ...int) {}
35
36 // EOF
37 `
38 Run(t, files, func(t *testing.T, env *Env) {
39 // Assert that the HTML page contains the expected const declaration.
40 // (We may need to make allowances for HTML markup.)
41 env.OpenFile("a/a.go")
42 uri1 := viewPkgDoc(t, env, env.Sandbox.Workdir.EntireFile("a/a.go"))
43 doc1 := get(t, uri1)
44 checkMatch(t, true, doc1, "const A =.*1")
45
46 // Regression test for signature truncation (#67287, #67294).
47 checkMatch(t, true, doc1, regexp.QuoteMeta("func (G[T]) F(int, int, int, ...)"))
48
49 // Check that edits to the buffer (even unsaved) are
50 // reflected in the HTML document.
51 env.RegexpReplace("a/a.go", "// EOF", "func NewFunc() {}")
52 env.Await(env.DoneDiagnosingChanges())
53 doc2 := get(t, uri1)
54 checkMatch(t, true, doc2, "func NewFunc")
55
56 // TODO(adonovan): assert some basic properties of the
57 // HTML document using something like
58 // golang.org/x/pkgsite/internal/testing/htmlcheck.
59
60 // Grab the URL in the HTML source link for NewFunc.
61 // (We don't have a DOM or JS interpreter so we have
62 // to know something of the document internals here.)
63 rx := regexp.MustCompile(`<h3 id='NewFunc'.*httpGET\("(.*)"\)`)
64 srcURL := html.UnescapeString(string(rx.FindSubmatch(doc2)[1]))
65
66 // Fetch the document. Its result isn't important,
67 // but it must have the side effect of another showDocument
68 // downcall, this time for a "file:" URL, causing the
69 // client editor to navigate to the source file.
70 t.Log("extracted /src URL", srcURL)
71 collectDocs := env.Awaiter.ListenToShownDocuments()
72 get(t, srcURL)
73
74 // Check that shown location is that of NewFunc.
75 shownSource := shownDocument(t, collectDocs(), "file:")
76 gotLoc := protocol.Location{
77 URI: protocol.DocumentURI(shownSource.URI), // fishy conversion
78 Range: *shownSource.Selection,
79 }
80 t.Log("showDocument(source file) URL:", gotLoc)
81 wantLoc := env.RegexpSearch("a/a.go", `func ()NewFunc`)
82 if gotLoc != wantLoc {
83 t.Errorf("got location %v, want %v", gotLoc, wantLoc)
84 }
85 })
86 }
87
88 func TestShowDocumentUnsupported(t *testing.T) {
89 const files = `
90 -- go.mod --
91 module example.com
92
93 -- a.go --
94 package a
95
96 const A = 1
97 `
98
99 for _, supported := range []bool{false, true} {
100 t.Run(fmt.Sprintf("supported=%v", supported), func(t *testing.T) {
101 opts := []RunOption{Modes(Default)}
102 if !supported {
103 opts = append(opts, CapabilitiesJSON([]byte(`
104 {
105 "window": {
106 "showDocument": {
107 "support": false
108 }
109 }
110 }`)))
111 }
112 WithOptions(opts...).Run(t, files, func(t *testing.T, env *Env) {
113 env.OpenFile("a.go")
114 // Invoke the "Browse package documentation" code
115 // action to start the server.
116 actions := env.CodeAction(env.Sandbox.Workdir.EntireFile("a.go"), nil, 0)
117 docAction, err := CodeActionByKind(actions, settings.GoDoc)
118 if err != nil {
119 t.Fatal(err)
120 }
121
122 // Execute the command.
123 // Its side effect should be a single showDocument request.
124 params := &protocol.ExecuteCommandParams{
125 Command: docAction.Command.Command,
126 Arguments: docAction.Command.Arguments,
127 }
128 var result any
129 collectDocs := env.Awaiter.ListenToShownDocuments()
130 collectMessages := env.Awaiter.ListenToShownMessages()
131 env.ExecuteCommand(params, &result)
132
133 // golang/go#70342: just because the command has finished does not mean
134 // that we will have received the necessary notifications. Synchronize
135 // using progress reports.
136 env.Await(CompletedWork(params.Command, 1, false))
137
138 wantDocs, wantMessages := 0, 1
139 if supported {
140 wantDocs, wantMessages = 1, 0
141 }
142
143 docs := collectDocs()
144 messages := collectMessages()
145
146 if gotDocs := len(docs); gotDocs != wantDocs {
147 t.Errorf("gopls.doc: got %d showDocument requests, want %d", gotDocs, wantDocs)
148 }
149 if gotMessages := len(messages); gotMessages != wantMessages {
150 t.Errorf("gopls.doc: got %d showMessage requests, want %d", gotMessages, wantMessages)
151 }
152 })
153 })
154 }
155 }
156
157 func TestPkgDocNoPanic66449(t *testing.T) {
158 // This particular input triggered a latent bug in doc.New
159 // that would corrupt the AST while filtering out unexported
160 // symbols such as b, causing nodeHTML to panic.
161 // Now it doesn't crash.
162 //
163 // We also check cross-reference anchors for all symbols.
164 const files = `
165 -- go.mod --
166 module example.com
167
168 -- a/a.go --
169 package a
170
171 // The 'π' suffix is to elimimate spurious matches with other HTML substrings,
172 // in particular the random base64 secret tokens that appear in gopls URLs.
173
174 var Vπ, vπ = 0, 0
175 const Cπ, cπ = 0, 0
176
177 func Fπ()
178 func fπ()
179
180 type Tπ int
181 type tπ int
182
183 func (Tπ) Mπ() {}
184 func (Tπ) mπ() {}
185
186 func (tπ) Mπ() {}
187 func (tπ) mπ() {}
188 `
189 Run(t, files, func(t *testing.T, env *Env) {
190 env.OpenFile("a/a.go")
191 uri1 := viewPkgDoc(t, env, env.Sandbox.Workdir.EntireFile("a/a.go"))
192
193 doc := get(t, uri1)
194 // (Ideally our code rendering would also
195 // eliminate unexported symbols...)
196 checkMatch(t, true, doc, "var Vπ, vπ = .*0.*0")
197 checkMatch(t, true, doc, "const Cπ, cπ = .*0.*0")
198
199 // Unexported funcs/types/... must still be discarded.
200 checkMatch(t, true, doc, "Fπ")
201 checkMatch(t, false, doc, "fπ")
202 checkMatch(t, true, doc, "Tπ")
203 checkMatch(t, false, doc, "tπ")
204
205 // Also, check that anchors exist (only) for exported symbols.
206 // exported:
207 checkMatch(t, true, doc, "<a id='Vπ'")
208 checkMatch(t, true, doc, "<a id='Cπ'")
209 checkMatch(t, true, doc, "<h3 id='Tπ'")
210 checkMatch(t, true, doc, "<h3 id='Fπ'")
211 checkMatch(t, true, doc, "<h4 id='Tπ.Mπ'")
212 // unexported:
213 checkMatch(t, false, doc, "<a id='vπ'")
214 checkMatch(t, false, doc, "<a id='cπ'")
215 checkMatch(t, false, doc, "<h3 id='tπ'")
216 checkMatch(t, false, doc, "<h3 id='fπ'")
217 checkMatch(t, false, doc, "<h4 id='Tπ.mπ'")
218 checkMatch(t, false, doc, "<h4 id='tπ.Mπ'")
219 checkMatch(t, false, doc, "<h4 id='tπ.mπ'")
220 })
221 }
222
223 // TestPkgDocNavigation tests that the symbol selector and index of
224 // symbols are well formed.
225 func TestPkgDocNavigation(t *testing.T) {
226 const files = `
227 -- go.mod --
228 module example.com
229
230 -- a/a.go --
231 package a
232
233 func Func1(int, string, bool, []string) (int, error)
234 func Func2(x, y int, a, b string) (int, error)
235
236 type Type struct {}
237 func (t Type) Method() {}
238 func (p *Type) PtrMethod() {}
239
240 func Constructor() Type
241 `
242 Run(t, files, func(t *testing.T, env *Env) {
243 env.OpenFile("a/a.go")
244 uri1 := viewPkgDoc(t, env, env.Sandbox.Workdir.EntireFile("a/a.go"))
245 doc := get(t, uri1)
246
247 q := regexp.QuoteMeta
248
249 // selector
250 checkMatch(t, true, doc, q(`<option label='Func1(_, _, _, _)' value='#Func1'/>`))
251 checkMatch(t, true, doc, q(`<option label='Func2(x, y, a, b)' value='#Func2'/>`))
252 checkMatch(t, true, doc, q(`<option label='Type' value='#Type'/>`))
253 checkMatch(t, true, doc, q(`<option label='Constructor()' value='#Constructor'/>`))
254 checkMatch(t, true, doc, q(`<option label='(t) Method()' value='#Type.Method'/>`))
255 checkMatch(t, true, doc, q(`<option label='(p) PtrMethod()' value='#Type.PtrMethod'/>`))
256
257 // index
258 checkMatch(t, true, doc, q(`<li><a href='#Func1'>func Func1(int, string, bool, ...) (int, error)</a></li>`))
259 checkMatch(t, true, doc, q(`<li><a href='#Func2'>func Func2(x int, y int, a string, ...) (int, error)</a></li>`))
260 checkMatch(t, true, doc, q(`<li><a href='#Type'>type Type</a></li>`))
261 checkMatch(t, true, doc, q(`<li><a href='#Constructor'>func Constructor() Type</a></li>`))
262 checkMatch(t, true, doc, q(`<li><a href='#Type.Method'>func (t Type) Method()</a></li>`))
263 checkMatch(t, true, doc, q(`<li><a href='#Type.PtrMethod'>func (p *Type) PtrMethod()</a></li>`))
264 })
265 }
266
267 // TestPkgDocContext tests that the gopls.doc command title and /pkg
268 // URL are appropriate for the current selection. It is effectively a
269 // test of golang.DocFragment.
270 func TestPkgDocContext(t *testing.T) {
271 const files = `
272 -- go.mod --
273 module example.com
274
275 -- a/a.go --
276 package a
277
278 import "fmt"
279 import "bytes"
280
281 func A() {
282 fmt.Println()
283 new(bytes.Buffer).Write(nil)
284 }
285
286 const K = 123
287
288 type T int
289 func (*T) M() { /*in T.M*/}
290
291 `
292
293 viewRE := regexp.MustCompile("view=[0-9]*")
294 Run(t, files, func(t *testing.T, env *Env) {
295 env.OpenFile("a/a.go")
296 for _, test := range []struct {
297 re string // regexp indicating selected portion of input file
298 want string // suffix of expected URL after /pkg/
299 }{
300 // current package
301 {"package a", "example.com/a?view=1"}, // outside any decl
302 {"in T.M", "example.com/a?view=1#T.M"}, // inside method (*T).M
303 {"123", "example.com/a?view=1#K"}, // inside const/var decl
304 {"T int", "example.com/a?view=1#T"}, // inside type decl
305
306 // imported
307 {"\"fmt\"", "fmt?view=1"}, // in import spec
308 {"fmt()[.]", "fmt?view=1"}, // use of PkgName
309 {"Println", "fmt?view=1#Println"}, // use of imported pkg-level symbol
310 {"fmt.Println", "fmt?view=1#Println"}, // qualified identifier
311 {"Write", "bytes?view=1#Buffer.Write"}, // use of imported method
312
313 // TODO(adonovan):
314 // - xtest package -> ForTest
315 // - field of imported struct -> nope
316 // - exported method of nonexported type from another package
317 // (e.g. types.Named.Obj) -> nope
318 // Also: assert that Command.Title looks nice.
319 } {
320 uri := viewPkgDoc(t, env, env.RegexpSearch("a/a.go", test.re))
321 _, got, ok := strings.Cut(uri, "/pkg/")
322 if !ok {
323 t.Errorf("pattern %q => %s (invalid /pkg URL)", test.re, uri)
324 continue
325 }
326
327 // Normalize the view ID, which varies by integration test mode.
328 got = viewRE.ReplaceAllString(got, "view=1")
329
330 if got != test.want {
331 t.Errorf("pattern %q => %s; want %s", test.re, got, test.want)
332 }
333 }
334 })
335 }
336
337 // TestPkgDocFileImports tests that the doc links are rendered
338 // as URLs based on the correct import mapping for the file in
339 // which they appear.
340 func TestPkgDocFileImports(t *testing.T) {
341 const files = `
342 -- go.mod --
343 module mod.com
344 go 1.20
345
346 -- a/a1.go --
347 // Package a refers to [b.T] [b.U] [alias.D] [d.D] [c.T] [c.U] [nope.Nope]
348 package a
349
350 import "mod.com/b"
351 import alias "mod.com/d"
352
353 // [b.T] indeed refers to b.T.
354 //
355 // [alias.D] refers to d.D
356 // but [d.D] also refers to d.D.
357 type A1 int
358
359 -- a/a2.go --
360 package a
361
362 import b "mod.com/c"
363
364 // [b.U] actually refers to c.U.
365 type A2 int
366
367 -- b/b.go --
368 package b
369
370 type T int
371 type U int
372
373 -- c/c.go --
374 package c
375
376 type T int
377 type U int
378
379 -- d/d.go --
380 package d
381
382 type D int
383 `
384 Run(t, files, func(t *testing.T, env *Env) {
385 env.OpenFile("a/a1.go")
386 uri1 := viewPkgDoc(t, env, env.Sandbox.Workdir.EntireFile("a/a1.go"))
387 doc := get(t, uri1)
388
389 // Check that the doc links are resolved using the
390 // appropriate import mapping for the file in which
391 // they appear.
392 checkMatch(t, true, doc, `pkg/mod.com/b\?.*#T">b.T</a> indeed refers to b.T`)
393 checkMatch(t, true, doc, `pkg/mod.com/c\?.*#U">b.U</a> actually refers to c.U`)
394
395 // Check that doc links can be resolved using either
396 // the original or the local name when they refer to a
397 // renaming import. (Local names are preferred.)
398 checkMatch(t, true, doc, `pkg/mod.com/d\?.*#D">alias.D</a> refers to d.D`)
399 checkMatch(t, true, doc, `pkg/mod.com/d\?.*#D">d.D</a> also refers to d.D`)
400
401 // Check that links in the package doc comment are
402 // resolved, and relative to the correct file (a1.go).
403 checkMatch(t, true, doc, `Package a refers to.*pkg/mod.com/b\?.*#T">b.T</a>`)
404 checkMatch(t, true, doc, `Package a refers to.*pkg/mod.com/b\?.*#U">b.U</a>`)
405 checkMatch(t, true, doc, `Package a refers to.*pkg/mod.com/d\?.*#D">alias.D</a>`)
406 checkMatch(t, true, doc, `Package a refers to.*pkg/mod.com/d\?.*#D">d.D</a>`)
407 checkMatch(t, true, doc, `Package a refers to.*pkg/mod.com/c\?.*#T">c.T</a>`)
408 checkMatch(t, true, doc, `Package a refers to.*pkg/mod.com/c\?.*#U">c.U</a>`)
409 checkMatch(t, true, doc, `Package a refers to.* \[nope.Nope\]`)
410 })
411 }
412
413 // TestPkgDocConstructorOfUnexported tests that exported constructor
414 // functions (NewT) whose result type (t) is unexported are not
415 // discarded but are presented as ordinary top-level functions (#69553).
416 func TestPkgDocConstructorOfUnexported(t *testing.T) {
417 const files = `
418 -- go.mod --
419 module mod.com
420 go 1.20
421
422 -- a/a.go --
423 package a
424
425 func A() {}
426 func Z() {}
427
428 type unexported int
429 func NewUnexported() unexported // exported constructor of unexported type
430
431 type Exported int
432 func NewExported() Exported // exported constructor of exported type
433 `
434 Run(t, files, func(t *testing.T, env *Env) {
435 env.OpenFile("a/a.go")
436 uri1 := viewPkgDoc(t, env, env.Sandbox.Workdir.EntireFile("a/a.go"))
437 doc := get(t, uri1)
438
439 want := regexp.QuoteMeta(`
440 <optgroup label='Functions'>
441 <option label='A()' value='#A'/>
442 <option label='NewUnexported()' value='#NewUnexported'/>
443 <option label='Z()' value='#Z'/>
444 </optgroup>
445 <optgroup label='Types'>
446 <option label='Exported' value='#Exported'/>
447 </optgroup>
448 <optgroup label='type Exported'>
449 <option label='NewExported()' value='#NewExported'/>
450 </optgroup>`)
451 checkMatch(t, true, doc, want)
452 })
453 }
454
455 // viewPkgDoc invokes the "Browse package documentation" code action
456 // at the specified location. It returns the URI of the document, or
457 // fails the test.
458 func viewPkgDoc(t *testing.T, env *Env, loc protocol.Location) protocol.URI {
459 // Invoke the "Browse package documentation" code
460 // action to start the server.
461 actions := env.CodeAction(loc, nil, 0)
462 docAction, err := CodeActionByKind(actions, settings.GoDoc)
463 if err != nil {
464 t.Fatal(err)
465 }
466
467 // Execute the command.
468 // Its side effect should be a single showDocument request.
469 params := &protocol.ExecuteCommandParams{
470 Command: docAction.Command.Command,
471 Arguments: docAction.Command.Arguments,
472 }
473 var result any
474 collectDocs := env.Awaiter.ListenToShownDocuments()
475 env.ExecuteCommand(params, &result)
476
477 doc := shownDocument(t, collectDocs(), "http:")
478 if doc == nil {
479 t.Fatalf("no showDocument call had 'http:' prefix")
480 }
481 if false {
482 t.Log("showDocument(package doc) URL:", doc.URI)
483 }
484 return doc.URI
485 }