Debian Codegraph @

gopls/internal/cmd/integration_test.go

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 // Copyright 2023 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 cmdtest contains the test suite for the command line behavior of gopls.
6 package cmd_test
7
8 // This file defines integration tests of each gopls subcommand that
9 // fork+exec the command in a separate process.
10 //
11 // (Rather than execute 'go build gopls' during the test, we reproduce
12 // the main entrypoint in the test executable.)
13 //
14 // The purpose of this test is to exercise client-side logic such as
15 // argument parsing and formatting of LSP RPC responses, not server
16 // behavior; see lsp_test for that.
17 //
18 // All tests run in parallel.
19 //
20 // TODO(adonovan):
21 // - Use markers to represent positions in the input and in assertions.
22 // - Coverage of cross-cutting things like cwd, environ, span parsing, etc.
23 // - Subcommands that accept -write and -diff flags implement them
24 // consistently; factor their tests.
25 // - Add missing test for 'vulncheck' subcommand.
26 // - Add tests for client-only commands: serve, help, api-json, licenses.
27
28 import (
29 "bytes"
30 "context"
31 "encoding/json"
32 "fmt"
33 "math/rand"
34 "os"
35 "os/exec"
36 "path/filepath"
37 "regexp"
38 "strings"
39 "testing"
40
41 "golang.org/x/tools/gopls/internal/cmd"
42 "golang.org/x/tools/gopls/internal/debug"
43 "golang.org/x/tools/gopls/internal/protocol"
44 "golang.org/x/tools/gopls/internal/tool"
45 "golang.org/x/tools/gopls/internal/util/bug"
46 "golang.org/x/tools/gopls/internal/version"
47 "golang.org/x/tools/internal/testenv"
48 "golang.org/x/tools/txtar"
49 )
50
51 // TestVersion tests the 'version' subcommand (info.go).
52 func TestVersion(t *testing.T) {
53 t.Parallel()
54
55 tree := writeTree(t, "")
56
57 // There's not much we can robustly assert about the actual version.
58 want := version.Version() // e.g. "master"
59
60 // basic
61 {
62 res := gopls(t, tree, "version")
63 res.checkExit(true)
64 res.checkStdout(want)
65 }
66
67 // basic, with version override
68 {
69 res := goplsWithEnv(t, tree, []string{"TEST_GOPLS_VERSION=v1.2.3"}, "version")
70 res.checkExit(true)
71 res.checkStdout(`v1\.2\.3`)
72 }
73
74 // -json flag
75 {
76 res := gopls(t, tree, "version", "-json")
77 res.checkExit(true)
78 var v debug.ServerVersion
79 if res.toJSON(&v) {
80 if v.Version != want {
81 t.Errorf("expected Version %q, got %q (%v)", want, v.Version, res)
82 }
83 }
84 }
85 }
86
87 // TestCheck tests the 'check' subcommand (check.go).
88 func TestCheck(t *testing.T) {
89 t.Parallel()
90
91 tree := writeTree(t, `
92 -- go.mod --
93 module example.com
94 go 1.18
95
96 -- a.go --
97 package a
98 import "fmt"
99 var _ = fmt.Sprintf("%s", 123)
100
101 -- b.go --
102 package a
103 import "fmt"
104 var _ = fmt.Sprintf("%d", "123")
105 -- c/c.go --
106 package c
107 var C int
108 -- c/c2.go --
109 package c
110 var C int
111 -- d/d.go --
112 package d
113
114 import "io/ioutil"
115
116 var _ = ioutil.ReadFile
117 `)
118
119 // no files
120 {
121 res := gopls(t, tree, "check")
122 res.checkExit(true)
123 if res.stdout != "" {
124 t.Errorf("unexpected output: %v", res)
125 }
126 }
127
128 // one file
129 {
130 res := gopls(t, tree, "check", "./a.go")
131 res.checkExit(true)
132 res.checkStdout("fmt.Sprintf format %s has arg 123 of wrong type int")
133 }
134
135 // two files
136 {
137 res := gopls(t, tree, "check", "./a.go", "./b.go")
138 res.checkExit(true)
139 res.checkStdout(`a.go:.* fmt.Sprintf format %s has arg 123 of wrong type int`)
140 res.checkStdout(`b.go:.* fmt.Sprintf format %d has arg "123" of wrong type string`)
141 }
142
143 // diagnostic with related information spanning files
144 {
145 res := gopls(t, tree, "check", "./c/c2.go")
146 res.checkExit(true)
147 res.checkStdout(`c2.go:2:5-6: C redeclared in this block`)
148 res.checkStdout(`c.go:2:5-6: - other declaration of C`)
149 }
150
151 // No deprecated (hint) diagnostic without -severity.
152 {
153 res := gopls(t, tree, "check", "./d/d.go")
154 res.checkExit(true)
155 if len(res.stdout) > 0 {
156 t.Errorf("check ./d/d.go returned unexpected output:\n%s", res.stdout)
157 }
158 }
159
160 // Deprecated (hint) diagnostics with -severity=hint
161 {
162 res := gopls(t, tree, "check", "-severity=hint", "./d/d.go")
163 res.checkExit(true)
164 res.checkStdout(`ioutil.ReadFile is deprecated`)
165 }
166 }
167
168 // TestCallHierarchy tests the 'call_hierarchy' subcommand (call_hierarchy.go).
169 func TestCallHierarchy(t *testing.T) {
170 t.Parallel()
171
172 tree := writeTree(t, `
173 -- go.mod --
174 module example.com
175 go 1.18
176
177 -- a.go --
178 package a
179 func f() {}
180 func g() {
181 f()
182 }
183 func h() {
184 f()
185 f()
186 }
187 `)
188 // missing position
189 {
190 res := gopls(t, tree, "call_hierarchy")
191 res.checkExit(false)
192 res.checkStderr("expects 1 argument")
193 }
194 // wrong place
195 {
196 res := gopls(t, tree, "call_hierarchy", "a.go:1")
197 res.checkExit(false)
198 res.checkStderr("identifier not found")
199 }
200 // f is called once from g and twice from h.
201 {
202 res := gopls(t, tree, "call_hierarchy", "a.go:2:6")
203 res.checkExit(true)
204 // We use regexp '.' as an OS-agnostic path separator.
205 res.checkStdout("ranges 7:2-3, 8:2-3 in ..a.go from/to function h in ..a.go:6:6-7")
206 res.checkStdout("ranges 4:2-3 in ..a.go from/to function g in ..a.go:3:6-7")
207 res.checkStdout("identifier: function f in ..a.go:2:6-7")
208 }
209 }
210
211 // TestCodeLens tests the 'codelens' subcommand (codelens.go).
212 func TestCodeLens(t *testing.T) {
213 t.Parallel()
214
215 tree := writeTree(t, `
216 -- go.mod --
217 module example.com
218 go 1.18
219
220 -- a/a.go --
221 package a
222 -- a/a_test.go --
223 package a_test
224 import "testing"
225 func TestPass(t *testing.T) {}
226 func TestFail(t *testing.T) { t.Fatal("fail") }
227 `)
228 // missing position
229 {
230 res := gopls(t, tree, "codelens")
231 res.checkExit(false)
232 res.checkStderr("requires a file name")
233 }
234 // list code lenses
235 {
236 res := gopls(t, tree, "codelens", "./a/a_test.go")
237 res.checkExit(true)
238 res.checkStdout(`a_test.go:3: "run test" \[gopls.run_tests\]`)
239 res.checkStdout(`a_test.go:4: "run test" \[gopls.run_tests\]`)
240 }
241 // no codelens with title/position
242 {
243 res := gopls(t, tree, "codelens", "-exec", "./a/a_test.go:1", "nope")
244 res.checkExit(false)
245 res.checkStderr(`no code lens at .* with title "nope"`)
246 }
247 // run the passing test
248 {
249 res := gopls(t, tree, "-v", "codelens", "-exec", "./a/a_test.go:3", "run test")
250 res.checkExit(true)
251 res.checkStderr(`PASS: TestPass`) // from go test
252 res.checkStderr("Info: all tests passed") // from gopls.test
253 }
254 // run the failing test
255 {
256 res := gopls(t, tree, "codelens", "-exec", "./a/a_test.go:4", "run test")
257 res.checkExit(false)
258 res.checkStderr(`FAIL example.com/a`)
259 res.checkStderr("Info: 1 / 1 tests failed")
260 }
261 }
262
263 // TestDefinition tests the 'definition' subcommand (definition.go).
264 func TestDefinition(t *testing.T) {
265 t.Parallel()
266
267 tree := writeTree(t, `
268 -- go.mod --
269 module example.com
270 go 1.18
271
272 -- a.go --
273 package a
274 import "fmt"
275 func f() {
276 fmt.Println()
277 }
278 func g() {
279 f()
280 }
281 `)
282 // missing position
283 {
284 res := gopls(t, tree, "definition")
285 res.checkExit(false)
286 res.checkStderr("expects 1 argument")
287 }
288 // intra-package
289 {
290 res := gopls(t, tree, "definition", "a.go:7:2") // "f()"
291 res.checkExit(true)
292 res.checkStdout("a.go:3:6-7: defined here as func f")
293 }
294 // cross-package
295 {
296 res := gopls(t, tree, "definition", "a.go:4:7") // "Println"
297 res.checkExit(true)
298 res.checkStdout("print.go.* defined here as func fmt.Println")
299 res.checkStdout("Println formats using the default formats for its operands")
300 }
301 // -json and -markdown
302 {
303 res := gopls(t, tree, "definition", "-json", "-markdown", "a.go:4:7")
304 res.checkExit(true)
305 var defn cmd.Definition
306 if res.toJSON(&defn) {
307 if !strings.HasPrefix(defn.Description, "```go\nfunc fmt.Println") {
308 t.Errorf("Description does not start with markdown code block. Got: %s", defn.Description)
309 }
310 }
311 }
312 }
313
314 // TestExecute tests the 'execute' subcommand (execute.go).
315 func TestExecute(t *testing.T) {
316 t.Parallel()
317
318 tree := writeTree(t, `
319 -- go.mod --
320 module example.com
321 go 1.18
322
323 -- hello.go --
324 package a
325 func main() {}
326
327 -- hello_test.go --
328 package a
329 import "testing"
330 func TestHello(t *testing.T) {
331 t.Fatal("oops")
332 }
333 `)
334 // missing command name
335 {
336 res := gopls(t, tree, "execute")
337 res.checkExit(false)
338 res.checkStderr("requires a command")
339 }
340 // bad command
341 {
342 res := gopls(t, tree, "execute", "gopls.foo")
343 res.checkExit(false)
344 res.checkStderr("unrecognized command: gopls.foo")
345 }
346 // too few arguments
347 {
348 res := gopls(t, tree, "execute", "gopls.run_tests")
349 res.checkExit(false)
350 res.checkStderr("expected 1 input arguments, got 0")
351 }
352 // too many arguments
353 {
354 res := gopls(t, tree, "execute", "gopls.run_tests", "null", "null")
355 res.checkExit(false)
356 res.checkStderr("expected 1 input arguments, got 2")
357 }
358 // argument is not JSON
359 {
360 res := gopls(t, tree, "execute", "gopls.run_tests", "hello")
361 res.checkExit(false)
362 res.checkStderr("argument 1 is not valid JSON: invalid character 'h'")
363 }
364 // add import, show diff
365 hello := "file://" + filepath.ToSlash(tree) + "/hello.go"
366 {
367 res := gopls(t, tree, "execute", "-d", "gopls.add_import", `{"ImportPath": "fmt", "URI": "`+hello+`"}`)
368 res.checkExit(true)
369 res.checkStdout(`[+]import "fmt"`)
370 }
371 // list known packages (has a result)
372 {
373 res := gopls(t, tree, "execute", "gopls.list_known_packages", `{"URI": "`+hello+`"}`)
374 res.checkExit(true)
375 res.checkStdout(`"fmt"`)
376 res.checkStdout(`"encoding/json"`)
377 }
378 // run tests
379 {
380 helloTest := "file://" + filepath.ToSlash(tree) + "/hello_test.go"
381 res := gopls(t, tree, "execute", "gopls.run_tests", `{"URI": "`+helloTest+`", "Tests": ["TestHello"]}`)
382 res.checkExit(false)
383 res.checkStderr(`hello_test.go:4: oops`)
384 res.checkStderr(`1 / 1 tests failed`)
385 }
386 }
387
388 // TestFoldingRanges tests the 'folding_ranges' subcommand (folding_range.go).
389 func TestFoldingRanges(t *testing.T) {
390 t.Parallel()
391
392 tree := writeTree(t, `
393 -- go.mod --
394 module example.com
395 go 1.18
396
397 -- a.go --
398 package a
399 func f(x int) {
400 // hello
401 }
402 `)
403 // missing filename
404 {
405 res := gopls(t, tree, "folding_ranges")
406 res.checkExit(false)
407 res.checkStderr("expects 1 argument")
408 }
409 // success
410 {
411 res := gopls(t, tree, "folding_ranges", "a.go")
412 res.checkExit(true)
413 res.checkStdout("2:8-2:13") // params (x int)
414 res.checkStdout("2:16-4:1") // body { ... }
415 }
416 }
417
418 // TestFormat tests the 'format' subcommand (format.go).
419 func TestFormat(t *testing.T) {
420 t.Parallel()
421
422 tree := writeTree(t, `
423 -- a.go --
424 package a ; func f ( ) { }
425 `)
426 const want = `package a
427
428 func f() {}
429 `
430
431 // no files => nop
432 {
433 res := gopls(t, tree, "format")
434 res.checkExit(true)
435 }
436 // default => print formatted result
437 {
438 res := gopls(t, tree, "format", "a.go")
439 res.checkExit(true)
440 if res.stdout != want {
441 t.Errorf("format: got <<%s>>, want <<%s>>", res.stdout, want)
442 }
443 }
444 // start/end position not supported (unless equal to start/end of file)
445 {
446 res := gopls(t, tree, "format", "a.go:1-2")
447 res.checkExit(false)
448 res.checkStderr("only full file formatting supported")
449 }
450 // -list: show only file names
451 {
452 res := gopls(t, tree, "format", "-list", "a.go")
453 res.checkExit(true)
454 res.checkStdout("a.go")
455 }
456 // -diff prints a unified diff
457 {
458 res := gopls(t, tree, "format", "-diff", "a.go")
459 res.checkExit(true)
460 // We omit the filenames as they vary by OS.
461 want := `
462 -package a ; func f ( ) { }
463 +package a
464 +
465 +func f() {}
466 `
467 res.checkStdout(regexp.QuoteMeta(want))
468 }
469 // -write updates the file
470 {
471 res := gopls(t, tree, "format", "-write", "a.go")
472 res.checkExit(true)
473 res.checkStdout("^$") // empty
474 checkContent(t, filepath.Join(tree, "a.go"), want)
475 }
476 }
477
478 // TestHighlight tests the 'highlight' subcommand (highlight.go).
479 func TestHighlight(t *testing.T) {
480 t.Parallel()
481
482 tree := writeTree(t, `
483 -- a.go --
484 package a
485 import "fmt"
486 func f() {
487 fmt.Println()
488 fmt.Println()
489 }
490 `)
491
492 // no arguments
493 {
494 res := gopls(t, tree, "highlight")
495 res.checkExit(false)
496 res.checkStderr("expects 1 argument")
497 }
498 // all occurrences of Println
499 {
500 res := gopls(t, tree, "highlight", "a.go:4:7")
501 res.checkExit(true)
502 res.checkStdout("a.go:4:6-13")
503 res.checkStdout("a.go:5:6-13")
504 }
505 }
506
507 // TestImplementations tests the 'implementation' subcommand (implementation.go).
508 func TestImplementations(t *testing.T) {
509 t.Parallel()
510
511 tree := writeTree(t, `
512 -- a.go --
513 package a
514 import "fmt"
515 type T int
516 func (T) String() string { return "" }
517 `)
518
519 // no arguments
520 {
521 res := gopls(t, tree, "implementation")
522 res.checkExit(false)
523 res.checkStderr("expects 1 argument")
524 }
525 // T.String
526 {
527 res := gopls(t, tree, "implementation", "a.go:4:10")
528 res.checkExit(true)
529 // TODO(adonovan): extract and check the content of the reported ranges?
530 // We use regexp '.' as an OS-agnostic path separator.
531 res.checkStdout("fmt.print.go:") // fmt.Stringer.String
532 res.checkStdout("runtime.error.go:") // runtime.stringer.String
533 }
534 }
535
536 // TestImports tests the 'imports' subcommand (imports.go).
537 func TestImports(t *testing.T) {
538 t.Parallel()
539
540 tree := writeTree(t, `
541 -- a.go --
542 package a
543 func _() {
544 fmt.Println()
545 }
546 `)
547
548 want := `
549 package a
550
551 import "fmt"
552 func _() {
553 fmt.Println()
554 }
555 `[1:]
556
557 // no arguments
558 {
559 res := gopls(t, tree, "imports")
560 res.checkExit(false)
561 res.checkStderr("expects 1 argument")
562 }
563 // default: print with imports
564 {
565 res := gopls(t, tree, "imports", "a.go")
566 res.checkExit(true)
567 if res.stdout != want {
568 t.Errorf("imports: got <<%s>>, want <<%s>>", res.stdout, want)
569 }
570 }
571 // -diff: show a unified diff
572 {
573 res := gopls(t, tree, "imports", "-diff", "a.go")
574 res.checkExit(true)
575 res.checkStdout(regexp.QuoteMeta(`+import "fmt"`))
576 }
577 // -write: update file
578 {
579 res := gopls(t, tree, "imports", "-write", "a.go")
580 res.checkExit(true)
581 checkContent(t, filepath.Join(tree, "a.go"), want)
582 }
583 }
584
585 // TestLinks tests the 'links' subcommand (links.go).
586 func TestLinks(t *testing.T) {
587 t.Parallel()
588
589 tree := writeTree(t, `
590 -- a.go --
591 // Link in package doc: https://pkg.go.dev/
592 package a
593
594 // Link in internal comment: https://go.dev/cl
595
596 // Doc comment link: https://blog.go.dev/
597 func f() {}
598 `)
599 // no arguments
600 {
601 res := gopls(t, tree, "links")
602 res.checkExit(false)
603 res.checkStderr("expects 1 argument")
604 }
605 // success
606 {
607 res := gopls(t, tree, "links", "a.go")
608 res.checkExit(true)
609 res.checkStdout("https://go.dev/cl")
610 res.checkStdout("https://pkg.go.dev")
611 res.checkStdout("https://blog.go.dev/")
612 }
613 // -json
614 {
615 res := gopls(t, tree, "links", "-json", "a.go")
616 res.checkExit(true)
617 res.checkStdout("https://pkg.go.dev")
618 res.checkStdout("https://go.dev/cl")
619 res.checkStdout("https://blog.go.dev/") // at 5:21-5:41
620 var links []protocol.DocumentLink
621 if res.toJSON(&links) {
622 // Check just one of the three locations.
623 if got, want := fmt.Sprint(links[2].Range), "5:21-5:41"; got != want {
624 t.Errorf("wrong link location: got %v, want %v", got, want)
625 }
626 }
627 }
628 }
629
630 // TestReferences tests the 'references' subcommand (references.go).
631 func TestReferences(t *testing.T) {
632 t.Parallel()
633
634 tree := writeTree(t, `
635 -- go.mod --
636 module example.com
637 go 1.18
638
639 -- a.go --
640 package a
641 import "fmt"
642 func f() {
643 fmt.Println()
644 }
645
646 -- b.go --
647 package a
648 import "fmt"
649 func g() {
650 fmt.Println()
651 }
652 `)
653 // no arguments
654 {
655 res := gopls(t, tree, "references")
656 res.checkExit(false)
657 res.checkStderr("expects 1 argument")
658 }
659 // fmt.Println
660 {
661 res := gopls(t, tree, "references", "a.go:4:10")
662 res.checkExit(true)
663 res.checkStdout("a.go:4:6-13")
664 res.checkStdout("b.go:4:6-13")
665 }
666 }
667
668 // TestSignature tests the 'signature' subcommand (signature.go).
669 func TestSignature(t *testing.T) {
670 t.Parallel()
671
672 tree := writeTree(t, `
673 -- go.mod --
674 module example.com
675 go 1.18
676
677 -- a.go --
678 package a
679 import "fmt"
680 func f() {
681 fmt.Println(123)
682 }
683 `)
684 // no arguments
685 {
686 res := gopls(t, tree, "signature")
687 res.checkExit(false)
688 res.checkStderr("expects 1 argument")
689 }
690 // at 123 inside fmt.Println() call
691 {
692 res := gopls(t, tree, "signature", "a.go:4:15")
693 res.checkExit(true)
694 res.checkStdout("Println\\(a ...")
695 res.checkStdout("Println formats using the default formats...")
696 }
697 }
698
699 // TestPrepareRename tests the 'prepare_rename' subcommand (prepare_rename.go).
700 func TestPrepareRename(t *testing.T) {
701 t.Parallel()
702
703 tree := writeTree(t, `
704 -- go.mod --
705 module example.com
706 go 1.18
707
708 -- a.go --
709 package a
710 func oldname() {}
711 `)
712 // no arguments
713 {
714 res := gopls(t, tree, "prepare_rename")
715 res.checkExit(false)
716 res.checkStderr("expects 1 argument")
717 }
718 // in 'package' keyword
719 {
720 res := gopls(t, tree, "prepare_rename", "a.go:1:3")
721 res.checkExit(false)
722 res.checkStderr("request is not valid at the given position")
723 }
724 // in 'package' identifier (not supported by client)
725 {
726 res := gopls(t, tree, "prepare_rename", "a.go:1:9")
727 res.checkExit(false)
728 res.checkStderr("can't rename package")
729 }
730 // in func oldname
731 {
732 res := gopls(t, tree, "prepare_rename", "a.go:2:9")
733 res.checkExit(true)
734 res.checkStdout("a.go:2:6-13") // all of "oldname"
735 }
736 }
737
738 // TestRename tests the 'rename' subcommand (rename.go).
739 func TestRename(t *testing.T) {
740 t.Parallel()
741
742 tree := writeTree(t, `
743 -- go.mod --
744 module example.com
745 go 1.18
746
747 -- a.go --
748 package a
749 func oldname() {}
750 `)
751 // no arguments
752 {
753 res := gopls(t, tree, "rename")
754 res.checkExit(false)
755 res.checkStderr("expects 2 arguments")
756 }
757 // missing newname
758 {
759 res := gopls(t, tree, "rename", "a.go:1:3")
760 res.checkExit(false)
761 res.checkStderr("expects 2 arguments")
762 }
763 // in 'package' keyword
764 {
765 res := gopls(t, tree, "rename", "a.go:1:3", "newname")
766 res.checkExit(false)
767 res.checkStderr("no identifier found")
768 }
769 // in 'package' identifier
770 {
771 res := gopls(t, tree, "rename", "a.go:1:9", "newname")
772 res.checkExit(false)
773 res.checkStderr(`cannot rename package: module path .* same as the package path, so .* no effect`)
774 }
775 // success, func oldname (and -diff)
776 {
777 res := gopls(t, tree, "rename", "-diff", "a.go:2:9", "newname")
778 res.checkExit(true)
779 res.checkStdout(regexp.QuoteMeta("-func oldname() {}"))
780 res.checkStdout(regexp.QuoteMeta("+func newname() {}"))
781 }
782 }
783
784 // TestSymbols tests the 'symbols' subcommand (symbols.go).
785 func TestSymbols(t *testing.T) {
786 t.Parallel()
787
788 tree := writeTree(t, `
789 -- go.mod --
790 module example.com
791 go 1.18
792
793 -- a.go --
794 package a
795 func f()
796 var v int
797 const c = 0
798 `)
799 // no files
800 {
801 res := gopls(t, tree, "symbols")
802 res.checkExit(false)
803 res.checkStderr("expects 1 argument")
804 }
805 // success
806 {
807 res := gopls(t, tree, "symbols", "a.go:123:456") // (line/col ignored)
808 res.checkExit(true)
809 res.checkStdout("f Function 2:6-2:7")
810 res.checkStdout("v Variable 3:5-3:6")
811 res.checkStdout("c Constant 4:7-4:8")
812 }
813 }
814
815 // TestSemtok tests the 'semtok' subcommand (semantictokens.go).
816 func TestSemtok(t *testing.T) {
817 t.Parallel()
818
819 tree := writeTree(t, `
820 -- go.mod --
821 module example.com
822 go 1.18
823
824 -- a.go --
825 package a
826 func f()
827 var v int
828 const c = 0
829 `)
830 // no files
831 {
832 res := gopls(t, tree, "semtok")
833 res.checkExit(false)
834 res.checkStderr("expected one file name")
835 }
836 // success
837 {
838 res := gopls(t, tree, "semtok", "a.go")
839 res.checkExit(true)
840 got := res.stdout
841 want := `
842 /*⇒7,keyword,[]*/package /*⇒1,namespace,[]*/a
843 /*⇒4,keyword,[]*/func /*⇒1,function,[definition signature]*/f()
844 /*⇒3,keyword,[]*/var /*⇒1,variable,[definition static number]*/v /*⇒3,type,[defaultLibrary number]*/int
845 /*⇒5,keyword,[]*/const /*⇒1,variable,[definition readonly number]*/c = /*⇒1,number,[]*/0
846 `[1:]
847 if got != want {
848 t.Errorf("semtok: got <<%s>>, want <<%s>>", got, want)
849 }
850 }
851 }
852
853 func TestStats(t *testing.T) {
854 t.Parallel()
855
856 tree := writeTree(t, `
857 -- go.mod --
858 module example.com
859 go 1.18
860
861 -- a.go --
862 package a
863 -- b/b.go --
864 package b
865 -- testdata/foo.go --
866 package foo
867 `)
868
869 // Trigger a bug report with a distinctive string
870 // and check that it was durably recorded.
871 oops := fmt.Sprintf("oops-%d", rand.Int())
872 {
873 env := []string{"TEST_GOPLS_BUG=" + oops}
874 res := goplsWithEnv(t, tree, env, "execute")
875 res.checkExit(true)
876 }
877
878 res := gopls(t, tree, "stats")
879 res.checkExit(true)
880
881 var stats cmd.GoplsStats
882 if err := json.Unmarshal([]byte(res.stdout), &stats); err != nil {
883 t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
884 }
885
886 // a few sanity checks
887 checks := []struct {
888 field string
889 got int
890 want int
891 }{
892 {
893 "WorkspaceStats.Views[0].WorkspaceModules",
894 stats.WorkspaceStats.Views[0].WorkspacePackages.Modules,
895 1,
896 },
897 {
898 "WorkspaceStats.Views[0].WorkspacePackages",
899 stats.WorkspaceStats.Views[0].WorkspacePackages.Packages,
900 2,
901 },
902 {"DirStats.Files", stats.DirStats.Files, 4},
903 {"DirStats.GoFiles", stats.DirStats.GoFiles, 2},
904 {"DirStats.ModFiles", stats.DirStats.ModFiles, 1},
905 {"DirStats.TestdataFiles", stats.DirStats.TestdataFiles, 1},
906 }
907 for _, check := range checks {
908 if check.got != check.want {
909 t.Errorf("stats.%s = %d, want %d", check.field, check.got, check.want)
910 }
911 }
912
913 // Check that we got a BugReport with the expected message.
914 {
915 got := fmt.Sprint(stats.BugReports)
916 wants := []string{
917 "cmd/execute.go", // File containing call to bug.Report
918 oops, // Description
919 }
920 for _, want := range wants {
921 if !strings.Contains(got, want) {
922 t.Errorf("BugReports does not contain %q. Got:<<%s>>", want, got)
923 break
924 }
925 }
926 }
927
928 // Check that -anon suppresses fields containing user information.
929 {
930 res2 := gopls(t, tree, "stats", "-anon")
931 res2.checkExit(true)
932
933 var stats2 cmd.GoplsStats
934 if err := json.Unmarshal([]byte(res2.stdout), &stats2); err != nil {
935 t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
936 }
937 if got := len(stats2.BugReports); got > 0 {
938 t.Errorf("Got %d bug reports with -anon, want 0. Reports:%+v", got, stats2.BugReports)
939 }
940 var stats2AsMap map[string]any
941 if err := json.Unmarshal([]byte(res2.stdout), &stats2AsMap); err != nil {
942 t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
943 }
944 // GOPACKAGESDRIVER is user information, but is ok to print zero value.
945 if v, ok := stats2AsMap["GOPACKAGESDRIVER"]; ok && v != "" {
946 t.Errorf(`Got GOPACKAGESDRIVER=(%v, %v); want ("", true(found))`, v, ok)
947 }
948 }
949
950 // Check that -anon suppresses fields containing non-zero user information.
951 {
952 res3 := goplsWithEnv(t, tree, []string{"GOPACKAGESDRIVER=off"}, "stats", "-anon")
953 res3.checkExit(true)
954
955 var statsAsMap3 map[string]any
956 if err := json.Unmarshal([]byte(res3.stdout), &statsAsMap3); err != nil {
957 t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
958 }
959 // GOPACKAGESDRIVER is user information, want non-empty value to be omitted.
960 if v, ok := statsAsMap3["GOPACKAGESDRIVER"]; ok {
961 t.Errorf(`Got GOPACKAGESDRIVER=(%q, %v); want ("", false(not found))`, v, ok)
962 }
963 }
964 }
965
966 // TestCodeAction tests the 'codeaction' subcommand (codeaction.go).
967 func TestCodeAction(t *testing.T) {
968 t.Parallel()
969
970 tree := writeTree(t, `
971 -- go.mod --
972 module example.com
973 go 1.18
974
975 -- a/a.go --
976 package a
977 type T int
978 func f() (int, string) { return }
979
980 -- a/b.go --
981 package a
982 import "io"
983 var _ io.Reader = C{}
984 type C struct{}
985 `)
986
987 // no arguments
988 {
989 res := gopls(t, tree, "codeaction")
990 res.checkExit(false)
991 res.checkStderr("expects at least 1 argument")
992 }
993 // list code actions in file
994 {
995 res := gopls(t, tree, "codeaction", "a/a.go")
996 res.checkExit(true)
997 res.checkStdout(`edit "Fill in return values" \[quickfix\]`)
998 res.checkStdout(`command "Browse documentation for package a" \[source.doc\]`)
999 }
1000 // list code actions in file, filtering by title
1001 {
1002 res := gopls(t, tree, "codeaction", "-title=Browse.*doc", "a/a.go")
1003 res.checkExit(true)
1004 got := res.stdout
1005 want := `command "Browse documentation for package a" [source.doc]` +
1006 "\n" +
1007 `command "Browse gopls feature documentation" [gopls.doc.features]` +
1008 "\n"
1009 if got != want {
1010 t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr)
1011 }
1012 }
1013 // list code actions in file, filtering (hierarchically) by kind
1014 {
1015 res := gopls(t, tree, "codeaction", "-kind=source", "a/a.go")
1016 res.checkExit(true)
1017 got := res.stdout
1018 want := `command "Browse documentation for package a" [source.doc]` +
1019 "\n" +
1020 `command "Split package \"a\"" [source.splitPackage]` +
1021 "\n" +
1022 `command "Show compiler optimization details for \"a\"" [source.toggleCompilerOptDetails]` +
1023 "\n"
1024 if got != want {
1025 t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr)
1026 }
1027 }
1028 // list code actions at position (of io.Reader)
1029 {
1030 res := gopls(t, tree, "codeaction", "a/b.go:#31")
1031 res.checkExit(true)
1032 res.checkStdout(`command "Browse documentation for type io.Reader" \[source.doc]`)
1033 }
1034 // list quick fixes at position (of type T)
1035 {
1036 res := gopls(t, tree, "codeaction", "-kind=quickfix", "a/a.go:#15")
1037 res.checkExit(true)
1038 got := res.stdout
1039 want := `edit "Fill in return values" [quickfix]` + "\n"
1040 if got != want {
1041 t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr)
1042 }
1043 }
1044 // success, with explicit CodeAction kind and diagnostics span.
1045 {
1046 res := gopls(t, tree, "codeaction", "-kind=quickfix", "-exec", "a/b.go:#40")
1047 res.checkExit(true)
1048 got := res.stdout
1049 want := `
1050 package a
1051
1052 import "io"
1053
1054 var _ io.Reader = C{}
1055
1056 type C struct{}
1057
1058 // Read implements [io.Reader].
1059 func (c C) Read(p []byte) (n int, err error) {
1060 panic("unimplemented")
1061 }
1062 `[1:]
1063 if got != want {
1064 t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr)
1065 }
1066 }
1067 }
1068
1069 // TestWorkspaceSymbol tests the 'workspace_symbol' subcommand (workspace_symbol.go).
1070 func TestWorkspaceSymbol(t *testing.T) {
1071 t.Parallel()
1072
1073 tree := writeTree(t, `
1074 -- go.mod --
1075 module example.com
1076 go 1.18
1077
1078 -- a.go --
1079 package a
1080 func someFunctionName()
1081 `)
1082 // no files
1083 {
1084 res := gopls(t, tree, "workspace_symbol")
1085 res.checkExit(false)
1086 res.checkStderr("expects 1 argument")
1087 }
1088 // success
1089 {
1090 res := gopls(t, tree, "workspace_symbol", "meFun")
1091 res.checkExit(true)
1092 res.checkStdout("a.go:2:6-22 someFunctionName Function")
1093 }
1094 }
1095
1096 // -- test framework --
1097
1098 func TestMain(m *testing.M) {
1099 switch os.Getenv("ENTRYPOINT") {
1100 case "goplsMain":
1101 goplsMain()
1102 default:
1103 os.Exit(m.Run())
1104 }
1105 }
1106
1107 // This function is a stand-in for gopls.main in ../../../../main.go.
1108 func goplsMain() {
1109 // Panic on bugs (unlike the production gopls command),
1110 // except in tests that inject calls to bug.Report.
1111 if os.Getenv("TEST_GOPLS_BUG") == "" {
1112 bug.PanicOnBugs = true
1113 }
1114
1115 if v := os.Getenv("TEST_GOPLS_VERSION"); v != "" {
1116 version.VersionOverride = v
1117 }
1118
1119 tool.Main(context.Background(), cmd.New(), os.Args[1:])
1120 }
1121
1122 // writeTree extracts a txtar archive into a new directory and returns its path.
1123 func writeTree(t *testing.T, archive string) string {
1124 root := t.TempDir()
1125
1126 // This unfortunate step is required because gopls output
1127 // expands symbolic links in its input file names (arguably it
1128 // should not), and on macOS the temp dir is in /var -> private/var.
1129 root, err := filepath.EvalSymlinks(root)
1130 if err != nil {
1131 t.Fatal(err)
1132 }
1133
1134 for _, f := range txtar.Parse([]byte(archive)).Files {
1135 filename := filepath.Join(root, f.Name)
1136 if err := os.MkdirAll(filepath.Dir(filename), 0777); err != nil {
1137 t.Fatal(err)
1138 }
1139 if err := os.WriteFile(filename, f.Data, 0666); err != nil {
1140 t.Fatal(err)
1141 }
1142 }
1143 return root
1144 }
1145
1146 // gopls executes gopls in a child process.
1147 func gopls(t *testing.T, dir string, args ...string) *result {
1148 return goplsWithEnv(t, dir, nil, args...)
1149 }
1150
1151 func goplsWithEnv(t *testing.T, dir string, env []string, args ...string) *result {
1152 testenv.NeedsTool(t, "go")
1153
1154 // Catch inadvertent use of dir=".", which would make
1155 // the ReplaceAll below unpredictable.
1156 if !filepath.IsAbs(dir) {
1157 t.Fatalf("dir is not absolute: %s", dir)
1158 }
1159
1160 goplsCmd := exec.Command(os.Args[0], args...)
1161 goplsCmd.Env = append(os.Environ(), "ENTRYPOINT=goplsMain")
1162 goplsCmd.Env = append(goplsCmd.Env, "GOPACKAGESDRIVER=off")
1163 goplsCmd.Env = append(goplsCmd.Env, env...)
1164 goplsCmd.Dir = dir
1165 goplsCmd.Stdout = new(bytes.Buffer)
1166 goplsCmd.Stderr = new(bytes.Buffer)
1167
1168 cmdErr := goplsCmd.Run()
1169
1170 stdout := strings.ReplaceAll(fmt.Sprint(goplsCmd.Stdout), dir, ".")
1171 stderr := strings.ReplaceAll(fmt.Sprint(goplsCmd.Stderr), dir, ".")
1172 exitcode := 0
1173 if cmdErr != nil {
1174 if exitErr, ok := cmdErr.(*exec.ExitError); ok {
1175 exitcode = exitErr.ExitCode()
1176 } else {
1177 stderr = cmdErr.Error() // (execve failure)
1178 exitcode = -1
1179 }
1180 }
1181 res := &result{
1182 t: t,
1183 command: "gopls " + strings.Join(args, " "),
1184 exitcode: exitcode,
1185 stdout: stdout,
1186 stderr: stderr,
1187 }
1188 if false {
1189 t.Log(res)
1190 }
1191 return res
1192 }
1193
1194 // A result holds the result of a gopls invocation, and provides assertion helpers.
1195 type result struct {
1196 t *testing.T
1197 command string
1198 exitcode int
1199 stdout, stderr string
1200 }
1201
1202 func (res *result) String() string {
1203 return fmt.Sprintf("%s: exit=%d stdout=<<%s>> stderr=<<%s>>",
1204 res.command, res.exitcode, res.stdout, res.stderr)
1205 }
1206
1207 // checkExit asserts that gopls returned the expected exit code.
1208 func (res *result) checkExit(success bool) {
1209 res.t.Helper()
1210 if (res.exitcode == 0) != success {
1211 res.t.Errorf("%s: exited with code %d, want success: %t (%s)",
1212 res.command, res.exitcode, success, res)
1213 }
1214 }
1215
1216 // checkStdout asserts that the gopls standard output matches the pattern.
1217 func (res *result) checkStdout(pattern string) {
1218 res.t.Helper()
1219 res.checkOutput(pattern, "stdout", res.stdout)
1220 }
1221
1222 // checkStderr asserts that the gopls standard error matches the pattern.
1223 func (res *result) checkStderr(pattern string) {
1224 res.t.Helper()
1225 res.checkOutput(pattern, "stderr", res.stderr)
1226 }
1227
1228 func (res *result) checkOutput(pattern, name, content string) {
1229 res.t.Helper()
1230 if match, err := regexp.MatchString(pattern, content); err != nil {
1231 res.t.Errorf("invalid regexp: %v", err)
1232 } else if !match {
1233 res.t.Errorf("%s: %s does not match [%s]; got <<%s>>",
1234 res.command, name, pattern, content)
1235 }
1236 }
1237
1238 // toJSON decodes res.stdout as JSON into to *ptr and reports its success.
1239 func (res *result) toJSON(ptr any) bool {
1240 if err := json.Unmarshal([]byte(res.stdout), ptr); err != nil {
1241 res.t.Errorf("invalid JSON %v", err)
1242 return false
1243 }
1244 return true
1245 }
1246
1247 // checkContent checks that the contents of the file are as expected.
1248 func checkContent(t *testing.T, filename, want string) {
1249 data, err := os.ReadFile(filename)
1250 if err != nil {
1251 t.Error(err)
1252 return
1253 }
1254 if got := string(data); got != want {
1255 t.Errorf("content of %s is <<%s>>, want <<%s>>", filename, got, want)
1256 }
1257 }