// Copyright 2025 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package web_test import ( "fmt" "html" "regexp" "strings" "testing" "golang.org/x/tools/gopls/internal/protocol" "golang.org/x/tools/gopls/internal/settings" . "golang.org/x/tools/gopls/internal/test/integration" ) // TODO(adonovan): define marker test verbs for checking package docs. // TestBrowsePkgDoc provides basic coverage of the "Browse package // documentation", which creates a web server on demand. func TestBrowsePkgDoc(t *testing.T) { const files = ` -- go.mod -- module example.com -- a/a.go -- package a const A = 1 type G[T any] int func (G[T]) F(int, int, int, int, int, int, int, ...int) {} // EOF ` Run(t, files, func(t *testing.T, env *Env) { // Assert that the HTML page contains the expected const declaration. // (We may need to make allowances for HTML markup.) env.OpenFile("a/a.go") uri1 := viewPkgDoc(t, env, env.Sandbox.Workdir.EntireFile("a/a.go")) doc1 := get(t, uri1) checkMatch(t, true, doc1, "const A =.*1") // Regression test for signature truncation (#67287, #67294). checkMatch(t, true, doc1, regexp.QuoteMeta("func (G[T]) F(int, int, int, ...)")) // Check that edits to the buffer (even unsaved) are // reflected in the HTML document. env.RegexpReplace("a/a.go", "// EOF", "func NewFunc() {}") env.Await(env.DoneDiagnosingChanges()) doc2 := get(t, uri1) checkMatch(t, true, doc2, "func NewFunc") // TODO(adonovan): assert some basic properties of the // HTML document using something like // golang.org/x/pkgsite/internal/testing/htmlcheck. // Grab the URL in the HTML source link for NewFunc. // (We don't have a DOM or JS interpreter so we have // to know something of the document internals here.) rx := regexp.MustCompile(`

`)) checkMatch(t, true, doc, q(` `) checkMatch(t, true, doc, want) }) } // viewPkgDoc invokes the "Browse package documentation" code action // at the specified location. It returns the URI of the document, or // fails the test. func viewPkgDoc(t *testing.T, env *Env, loc protocol.Location) protocol.URI { // Invoke the "Browse package documentation" code // action to start the server. actions := env.CodeAction(loc, nil, 0) docAction, err := CodeActionByKind(actions, settings.GoDoc) if err != nil { t.Fatal(err) } // Execute the command. // Its side effect should be a single showDocument request. params := &protocol.ExecuteCommandParams{ Command: docAction.Command.Command, Arguments: docAction.Command.Arguments, } var result any collectDocs := env.Awaiter.ListenToShownDocuments() env.ExecuteCommand(params, &result) doc := shownDocument(t, collectDocs(), "http:") if doc == nil { t.Fatalf("no showDocument call had 'http:' prefix") } if false { t.Log("showDocument(package doc) URL:", doc.URI) } return doc.URI }