Debian Codegraph @

gopls/internal/cmd/integration_test.go

raw symbols ◀ ▶
Source reconstructed at patch state 1 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.Skip("in 'package' identifier gives different error message without Go mod")
741 t.Parallel()
742
743 tree := writeTree(t, `
744 -- go.mod --
745 module example.com
746 go 1.18
747
748 -- a.go --
749 package a
750 func oldname() {}
751 `)
752 // no arguments
753 {
754 res := gopls(t, tree, "rename")
755 res.checkExit(false)
756 res.checkStderr("expects 2 arguments")
757 }
758 // missing newname
759 {
760 res := gopls(t, tree, "rename", "a.go:1:3")
761 res.checkExit(false)
762 res.checkStderr("expects 2 arguments")
763 }
764 // in 'package' keyword
765 {
766 res := gopls(t, tree, "rename", "a.go:1:3", "newname")
767 res.checkExit(false)
768 res.checkStderr("no identifier found")
769 }
770 // in 'package' identifier
771 {
772 res := gopls(t, tree, "rename", "a.go:1:9", "newname")
773 res.checkExit(false)
774 res.checkStderr(`cannot rename package: module path .* same as the package path, so .* no effect`)
775 }
776 // success, func oldname (and -diff)
777 {
778 res := gopls(t, tree, "rename", "-diff", "a.go:2:9", "newname")
779 res.checkExit(true)
780 res.checkStdout(regexp.QuoteMeta("-func oldname() {}"))
781 res.checkStdout(regexp.QuoteMeta("+func newname() {}"))
782 }
783 }
784
785 // TestSymbols tests the 'symbols' subcommand (symbols.go).
786 func TestSymbols(t *testing.T) {
787 t.Parallel()
788
789 tree := writeTree(t, `
790 -- go.mod --
791 module example.com
792 go 1.18
793
794 -- a.go --
795 package a
796 func f()
797 var v int
798 const c = 0
799 `)
800 // no files
801 {
802 res := gopls(t, tree, "symbols")
803 res.checkExit(false)
804 res.checkStderr("expects 1 argument")
805 }
806 // success
807 {
808 res := gopls(t, tree, "symbols", "a.go:123:456") // (line/col ignored)
809 res.checkExit(true)
810 res.checkStdout("f Function 2:6-2:7")
811 res.checkStdout("v Variable 3:5-3:6")
812 res.checkStdout("c Constant 4:7-4:8")
813 }
814 }
815
816 // TestSemtok tests the 'semtok' subcommand (semantictokens.go).
817 func TestSemtok(t *testing.T) {
818 t.Parallel()
819
820 tree := writeTree(t, `
821 -- go.mod --
822 module example.com
823 go 1.18
824
825 -- a.go --
826 package a
827 func f()
828 var v int
829 const c = 0
830 `)
831 // no files
832 {
833 res := gopls(t, tree, "semtok")
834 res.checkExit(false)
835 res.checkStderr("expected one file name")
836 }
837 // success
838 {
839 res := gopls(t, tree, "semtok", "a.go")
840 res.checkExit(true)
841 got := res.stdout
842 want := `
843 /*⇒7,keyword,[]*/package /*⇒1,namespace,[]*/a
844 /*⇒4,keyword,[]*/func /*⇒1,function,[definition signature]*/f()
845 /*⇒3,keyword,[]*/var /*⇒1,variable,[definition static number]*/v /*⇒3,type,[defaultLibrary number]*/int
846 /*⇒5,keyword,[]*/const /*⇒1,variable,[definition readonly number]*/c = /*⇒1,number,[]*/0
847 `[1:]
848 if got != want {
849 t.Errorf("semtok: got <<%s>>, want <<%s>>", got, want)
850 }
851 }
852 }
853
854 func TestStats(t *testing.T) {
855 t.Skip("gives different results without Go mod")
856 t.Parallel()
857
858 tree := writeTree(t, `
859 -- go.mod --
860 module example.com
861 go 1.18
862
863 -- a.go --
864 package a
865 -- b/b.go --
866 package b
867 -- testdata/foo.go --
868 package foo
869 `)
870
871 // Trigger a bug report with a distinctive string
872 // and check that it was durably recorded.
873 oops := fmt.Sprintf("oops-%d", rand.Int())
874 {
875 env := []string{"TEST_GOPLS_BUG=" + oops}
876 res := goplsWithEnv(t, tree, env, "execute")
877 res.checkExit(true)
878 }
879
880 res := gopls(t, tree, "stats")
881 res.checkExit(true)
882
883 var stats cmd.GoplsStats
884 if err := json.Unmarshal([]byte(res.stdout), &stats); err != nil {
885 t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
886 }
887
888 // a few sanity checks
889 checks := []struct {
890 field string
891 got int
892 want int
893 }{
894 {
895 "WorkspaceStats.Views[0].WorkspaceModules",
896 stats.WorkspaceStats.Views[0].WorkspacePackages.Modules,
897 1,
898 },
899 {
900 "WorkspaceStats.Views[0].WorkspacePackages",
901 stats.WorkspaceStats.Views[0].WorkspacePackages.Packages,
902 2,
903 },
904 {"DirStats.Files", stats.DirStats.Files, 4},
905 {"DirStats.GoFiles", stats.DirStats.GoFiles, 2},
906 {"DirStats.ModFiles", stats.DirStats.ModFiles, 1},
907 {"DirStats.TestdataFiles", stats.DirStats.TestdataFiles, 1},
908 }
909 for _, check := range checks {
910 if check.got != check.want {
911 t.Errorf("stats.%s = %d, want %d", check.field, check.got, check.want)
912 }
913 }
914
915 // Check that we got a BugReport with the expected message.
916 {
917 got := fmt.Sprint(stats.BugReports)
918 wants := []string{
919 "cmd/execute.go", // File containing call to bug.Report
920 oops, // Description
921 }
922 for _, want := range wants {
923 if !strings.Contains(got, want) {
924 t.Errorf("BugReports does not contain %q. Got:<<%s>>", want, got)
925 break
926 }
927 }
928 }
929
930 // Check that -anon suppresses fields containing user information.
931 {
932 res2 := gopls(t, tree, "stats", "-anon")
933 res2.checkExit(true)
934
935 var stats2 cmd.GoplsStats
936 if err := json.Unmarshal([]byte(res2.stdout), &stats2); err != nil {
937 t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
938 }
939 if got := len(stats2.BugReports); got > 0 {
940 t.Errorf("Got %d bug reports with -anon, want 0. Reports:%+v", got, stats2.BugReports)
941 }
942 var stats2AsMap map[string]any
943 if err := json.Unmarshal([]byte(res2.stdout), &stats2AsMap); err != nil {
944 t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
945 }
946 // GOPACKAGESDRIVER is user information, but is ok to print zero value.
947 if v, ok := stats2AsMap["GOPACKAGESDRIVER"]; ok && v != "" {
948 t.Errorf(`Got GOPACKAGESDRIVER=(%v, %v); want ("", true(found))`, v, ok)
949 }
950 }
951
952 // Check that -anon suppresses fields containing non-zero user information.
953 {
954 res3 := goplsWithEnv(t, tree, []string{"GOPACKAGESDRIVER=off"}, "stats", "-anon")
955 res3.checkExit(true)
956
957 var statsAsMap3 map[string]any
958 if err := json.Unmarshal([]byte(res3.stdout), &statsAsMap3); err != nil {
959 t.Fatalf("failed to unmarshal JSON output of stats command: %v", err)
960 }
961 // GOPACKAGESDRIVER is user information, want non-empty value to be omitted.
962 if v, ok := statsAsMap3["GOPACKAGESDRIVER"]; ok {
963 t.Errorf(`Got GOPACKAGESDRIVER=(%q, %v); want ("", false(not found))`, v, ok)
964 }
965 }
966 }
967
968 // TestCodeAction tests the 'codeaction' subcommand (codeaction.go).
969 func TestCodeAction(t *testing.T) {
970 t.Parallel()
971
972 tree := writeTree(t, `
973 -- go.mod --
974 module example.com
975 go 1.18
976
977 -- a/a.go --
978 package a
979 type T int
980 func f() (int, string) { return }
981
982 -- a/b.go --
983 package a
984 import "io"
985 var _ io.Reader = C{}
986 type C struct{}
987 `)
988
989 // no arguments
990 {
991 res := gopls(t, tree, "codeaction")
992 res.checkExit(false)
993 res.checkStderr("expects at least 1 argument")
994 }
995 // list code actions in file
996 {
997 res := gopls(t, tree, "codeaction", "a/a.go")
998 res.checkExit(true)
999 res.checkStdout(`edit "Fill in return values" \[quickfix\]`)
1000 res.checkStdout(`command "Browse documentation for package a" \[source.doc\]`)
1001 }
1002 // list code actions in file, filtering by title
1003 {
1004 res := gopls(t, tree, "codeaction", "-title=Browse.*doc", "a/a.go")
1005 res.checkExit(true)
1006 got := res.stdout
1007 want := `command "Browse documentation for package a" [source.doc]` +
1008 "\n" +
1009 `command "Browse gopls feature documentation" [gopls.doc.features]` +
1010 "\n"
1011 if got != want {
1012 t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr)
1013 }
1014 }
1015 // list code actions in file, filtering (hierarchically) by kind
1016 {
1017 res := gopls(t, tree, "codeaction", "-kind=source", "a/a.go")
1018 res.checkExit(true)
1019 got := res.stdout
1020 want := `command "Browse documentation for package a" [source.doc]` +
1021 "\n" +
1022 `command "Split package \"a\"" [source.splitPackage]` +
1023 "\n" +
1024 `command "Show compiler optimization details for \"a\"" [source.toggleCompilerOptDetails]` +
1025 "\n"
1026 if got != want {
1027 t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr)
1028 }
1029 }
1030 // list code actions at position (of io.Reader)
1031 {
1032 res := gopls(t, tree, "codeaction", "a/b.go:#31")
1033 res.checkExit(true)
1034 res.checkStdout(`command "Browse documentation for type io.Reader" \[source.doc]`)
1035 }
1036 // list quick fixes at position (of type T)
1037 {
1038 res := gopls(t, tree, "codeaction", "-kind=quickfix", "a/a.go:#15")
1039 res.checkExit(true)
1040 got := res.stdout
1041 want := `edit "Fill in return values" [quickfix]` + "\n"
1042 if got != want {
1043 t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr)
1044 }
1045 }
1046 // success, with explicit CodeAction kind and diagnostics span.
1047 {
1048 res := gopls(t, tree, "codeaction", "-kind=quickfix", "-exec", "a/b.go:#40")
1049 res.checkExit(true)
1050 got := res.stdout
1051 want := `
1052 package a
1053
1054 import "io"
1055
1056 var _ io.Reader = C{}
1057
1058 type C struct{}
1059
1060 // Read implements [io.Reader].
1061 func (c C) Read(p []byte) (n int, err error) {
1062 panic("unimplemented")
1063 }
1064 `[1:]
1065 if got != want {
1066 t.Errorf("codeaction: got <<%s>>, want <<%s>>\nstderr:\n%s", got, want, res.stderr)
1067 }
1068 }
1069 }
1070
1071 // TestWorkspaceSymbol tests the 'workspace_symbol' subcommand (workspace_symbol.go).
1072 func TestWorkspaceSymbol(t *testing.T) {
1073 t.Parallel()
1074
1075 tree := writeTree(t, `
1076 -- go.mod --
1077 module example.com
1078 go 1.18
1079
1080 -- a.go --
1081 package a
1082 func someFunctionName()
1083 `)
1084 // no files
1085 {
1086 res := gopls(t, tree, "workspace_symbol")
1087 res.checkExit(false)
1088 res.checkStderr("expects 1 argument")
1089 }
1090 // success
1091 {
1092 res := gopls(t, tree, "workspace_symbol", "meFun")
1093 res.checkExit(true)
1094 res.checkStdout("a.go:2:6-22 someFunctionName Function")
1095 }
1096 }
1097
1098 // -- test framework --
1099
1100 func TestMain(m *testing.M) {
1101 switch os.Getenv("ENTRYPOINT") {
1102 case "goplsMain":
1103 goplsMain()
1104 default:
1105 os.Exit(m.Run())
1106 }
1107 }
1108
1109 // This function is a stand-in for gopls.main in ../../../../main.go.
1110 func goplsMain() {
1111 // Panic on bugs (unlike the production gopls command),
1112 // except in tests that inject calls to bug.Report.
1113 if os.Getenv("TEST_GOPLS_BUG") == "" {
1114 bug.PanicOnBugs = true
1115 }
1116
1117 if v := os.Getenv("TEST_GOPLS_VERSION"); v != "" {
1118 version.VersionOverride = v
1119 }
1120
1121 tool.Main(context.Background(), cmd.New(), os.Args[1:])
1122 }
1123
1124 // writeTree extracts a txtar archive into a new directory and returns its path.
1125 func writeTree(t *testing.T, archive string) string {
1126 root := t.TempDir()
1127
1128 // This unfortunate step is required because gopls output
1129 // expands symbolic links in its input file names (arguably it
1130 // should not), and on macOS the temp dir is in /var -> private/var.
1131 root, err := filepath.EvalSymlinks(root)
1132 if err != nil {
1133 t.Fatal(err)
1134 }
1135
1136 for _, f := range txtar.Parse([]byte(archive)).Files {
1137 filename := filepath.Join(root, f.Name)
1138 if err := os.MkdirAll(filepath.Dir(filename), 0777); err != nil {
1139 t.Fatal(err)
1140 }
1141 if err := os.WriteFile(filename, f.Data, 0666); err != nil {
1142 t.Fatal(err)
1143 }
1144 }
1145 return root
1146 }
1147
1148 // gopls executes gopls in a child process.
1149 func gopls(t *testing.T, dir string, args ...string) *result {
1150 return goplsWithEnv(t, dir, nil, args...)
1151 }
1152
1153 func goplsWithEnv(t *testing.T, dir string, env []string, args ...string) *result {
1154 testenv.NeedsTool(t, "go")
1155
1156 // Catch inadvertent use of dir=".", which would make
1157 // the ReplaceAll below unpredictable.
1158 if !filepath.IsAbs(dir) {
1159 t.Fatalf("dir is not absolute: %s", dir)
1160 }
1161
1162 goplsCmd := exec.Command(os.Args[0], args...)
1163 goplsCmd.Env = append(os.Environ(), "ENTRYPOINT=goplsMain")
1164 goplsCmd.Env = append(goplsCmd.Env, "GOPACKAGESDRIVER=off")
1165 goplsCmd.Env = append(goplsCmd.Env, env...)
1166 goplsCmd.Dir = dir
1167 goplsCmd.Stdout = new(bytes.Buffer)
1168 goplsCmd.Stderr = new(bytes.Buffer)
1169
1170 cmdErr := goplsCmd.Run()
1171
1172 stdout := strings.ReplaceAll(fmt.Sprint(goplsCmd.Stdout), dir, ".")
1173 stderr := strings.ReplaceAll(fmt.Sprint(goplsCmd.Stderr), dir, ".")
1174 exitcode := 0
1175 if cmdErr != nil {
1176 if exitErr, ok := cmdErr.(*exec.ExitError); ok {
1177 exitcode = exitErr.ExitCode()
1178 } else {
1179 stderr = cmdErr.Error() // (execve failure)
1180 exitcode = -1
1181 }
1182 }
1183 res := &result{
1184 t: t,
1185 command: "gopls " + strings.Join(args, " "),
1186 exitcode: exitcode,
1187 stdout: stdout,
1188 stderr: stderr,
1189 }
1190 if false {
1191 t.Log(res)
1192 }
1193 return res
1194 }
1195
1196 // A result holds the result of a gopls invocation, and provides assertion helpers.
1197 type result struct {
1198 t *testing.T
1199 command string
1200 exitcode int
1201 stdout, stderr string
1202 }
1203
1204 func (res *result) String() string {
1205 return fmt.Sprintf("%s: exit=%d stdout=<<%s>> stderr=<<%s>>",
1206 res.command, res.exitcode, res.stdout, res.stderr)
1207 }
1208
1209 // checkExit asserts that gopls returned the expected exit code.
1210 func (res *result) checkExit(success bool) {
1211 res.t.Helper()
1212 if (res.exitcode == 0) != success {
1213 res.t.Errorf("%s: exited with code %d, want success: %t (%s)",
1214 res.command, res.exitcode, success, res)
1215 }
1216 }
1217
1218 // checkStdout asserts that the gopls standard output matches the pattern.
1219 func (res *result) checkStdout(pattern string) {
1220 res.t.Helper()
1221 res.checkOutput(pattern, "stdout", res.stdout)
1222 }
1223
1224 // checkStderr asserts that the gopls standard error matches the pattern.
1225 func (res *result) checkStderr(pattern string) {
1226 res.t.Helper()
1227 res.checkOutput(pattern, "stderr", res.stderr)
1228 }
1229
1230 func (res *result) checkOutput(pattern, name, content string) {
1231 res.t.Helper()
1232 if match, err := regexp.MatchString(pattern, content); err != nil {
1233 res.t.Errorf("invalid regexp: %v", err)
1234 } else if !match {
1235 res.t.Errorf("%s: %s does not match [%s]; got <<%s>>",
1236 res.command, name, pattern, content)
1237 }
1238 }
1239
1240 // toJSON decodes res.stdout as JSON into to *ptr and reports its success.
1241 func (res *result) toJSON(ptr any) bool {
1242 if err := json.Unmarshal([]byte(res.stdout), ptr); err != nil {
1243 res.t.Errorf("invalid JSON %v", err)
1244 return false
1245 }
1246 return true
1247 }
1248
1249 // checkContent checks that the contents of the file are as expected.
1250 func checkContent(t *testing.T, filename, want string) {
1251 data, err := os.ReadFile(filename)
1252 if err != nil {
1253 t.Error(err)
1254 return
1255 }
1256 if got := string(data); got != want {
1257 t.Errorf("content of %s is <<%s>>, want <<%s>>", filename, got, want)
1258 }
1259 }