Debian Codegraph @

gopls/internal/test/integration/diagnostics/diagnostics_test.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 diagnostics
6
7 import (
8 "context"
9 "fmt"
10 "os"
11 "os/exec"
12 "testing"
13
14 "golang.org/x/tools/gopls/internal/protocol"
15 "golang.org/x/tools/gopls/internal/server"
16 . "golang.org/x/tools/gopls/internal/test/integration"
17 "golang.org/x/tools/gopls/internal/test/integration/fake"
18 "golang.org/x/tools/gopls/internal/util/bug"
19 "golang.org/x/tools/internal/testenv"
20 )
21
22 func TestMain(m *testing.M) {
23 bug.PanicOnBugs = true
24 os.Exit(Main(m))
25 }
26
27 // Use mod.com for all go.mod files due to golang/go#35230.
28 const exampleProgram = `
29 -- go.mod --
30 module mod.com
31
32 go 1.12
33 -- main.go --
34 package main
35
36 import "fmt"
37
38 func main() {
39 fmt.Println("Hello World.")
40 }`
41
42 func TestDiagnosticErrorInEditedFile(t *testing.T) {
43 // This test is very basic: start with a clean Go program, make an error, and
44 // get a diagnostic for that error. However, it also demonstrates how to
45 // combine Expectations to await more complex state in the editor.
46 RunMultiple{
47 {"golist", WithOptions(Modes(Default))},
48 {"gopackages", WithOptions(
49 Modes(Default),
50 FakeGoPackagesDriver(t),
51 )},
52 }.Run(t, exampleProgram, func(t *testing.T, env *Env) {
53 // Deleting the 'n' at the end of Println should generate a single error
54 // diagnostic.
55 env.OpenFile("main.go")
56 env.RegexpReplace("main.go", "Printl(n)", "")
57 env.AfterChange(
58 Diagnostics(env.AtRegexp("main.go", "Printl")),
59 // Assert that this test has sent no error logs to the client. This is not
60 // strictly necessary for testing this regression, but is included here
61 // as an example of using the NoErrorLogs() expectation. Feel free to
62 // delete.
63 NoErrorLogs(),
64 )
65 })
66 }
67
68 func TestMissingImportDiagsClearOnFirstFile(t *testing.T) {
69 const onlyMod = `
70 -- go.mod --
71 module mod.com
72
73 go 1.12
74 `
75 WithOptions(
76 Settings{
77 "pullDiagnostics": true,
78 },
79 ).Run(t, onlyMod, func(t *testing.T, env *Env) {
80 env.CreateBuffer("main.go", `package main
81
82 func _() {
83 log.Println()
84 }
85 `)
86 env.AfterChange(Diagnostics(env.AtRegexp("main.go", "log")))
87 env.SaveBuffer("main.go")
88 if got := env.Diagnostics("main.go"); len(got) != 0 {
89 t.Errorf("got %d diagnostics, want 0", len(got))
90 }
91 env.AfterChange(NoDiagnostics(ForFile("main.go")))
92 })
93 }
94
95 func TestDiagnosticErrorInNewFile(t *testing.T) {
96 const brokenFile = `package main
97
98 const Foo = "abc
99 `
100 RunMultiple{
101 {"golist", WithOptions(Modes(Default))},
102 // Since this test requires loading an overlay,
103 // it verifies that the fake go/packages driver honors overlays.
104 {"gopackages", WithOptions(
105 Modes(Default),
106 FakeGoPackagesDriver(t),
107 )},
108 }.Run(t, brokenFile, func(t *testing.T, env *Env) {
109 env.CreateBuffer("broken.go", brokenFile)
110 env.AfterChange(Diagnostics(env.AtRegexp("broken.go", "\"abc")))
111 })
112 }
113
114 // badPackage contains a duplicate definition of the 'A' const.
115 const badPackage = `
116 -- go.mod --
117 module mod.com
118
119 go 1.12
120 -- a.go --
121 package consts
122
123 const A = 1
124 -- b.go --
125 package consts
126
127 const A = 2
128 `
129
130 func TestDiagnosticClearingOnEdit(t *testing.T) {
131 WithOptions(
132 Settings{
133 "pullDiagnostics": true,
134 },
135 ).Run(t, badPackage, func(t *testing.T, env *Env) {
136 env.OpenFile("b.go")
137
138 for _, f := range []string{"a.go", "b.go"} {
139 if got := env.Diagnostics(f); len(got) != 1 {
140 t.Errorf("textDocument/diagnostic(%s) returned %d diagnostics, want 1. Got %v", f, len(got), got)
141 }
142 }
143 env.AfterChange(
144 Diagnostics(env.AtRegexp("a.go", "A = 1")),
145 Diagnostics(env.AtRegexp("b.go", "A = 2")),
146 )
147
148 // Fix the error by editing the const name A in b.go to `B`.
149 env.RegexpReplace("b.go", "(A) = 2", "B")
150 for _, f := range []string{"a.go", "b.go"} {
151 if got := env.Diagnostics(f); len(got) != 0 {
152 t.Errorf("textDocument/diagnostic(%s) returned %d diagnostics, want 0. Got %v", f, len(got), got)
153 }
154 }
155 env.AfterChange(
156 NoDiagnostics(ForFile("a.go")),
157 NoDiagnostics(ForFile("b.go")),
158 )
159 })
160 }
161
162 func TestDiagnosticClearingOnDelete_Issue37049(t *testing.T) {
163 Run(t, badPackage, func(t *testing.T, env *Env) {
164 env.OpenFile("a.go")
165 env.AfterChange(
166 Diagnostics(env.AtRegexp("a.go", "A = 1")),
167 Diagnostics(env.AtRegexp("b.go", "A = 2")),
168 )
169 env.RemoveWorkspaceFile("b.go")
170
171 env.AfterChange(
172 NoDiagnostics(ForFile("a.go")),
173 NoDiagnostics(ForFile("b.go")),
174 )
175 })
176 }
177
178 func TestDiagnosticClearingOnClose(t *testing.T) {
179 Run(t, badPackage, func(t *testing.T, env *Env) {
180 env.CreateBuffer("c.go", `package consts
181
182 const A = 3`)
183 env.AfterChange(
184 Diagnostics(env.AtRegexp("a.go", "A = 1")),
185 Diagnostics(env.AtRegexp("b.go", "A = 2")),
186 Diagnostics(env.AtRegexp("c.go", "A = 3")),
187 )
188 env.CloseBuffer("c.go")
189 env.AfterChange(
190 Diagnostics(env.AtRegexp("a.go", "A = 1")),
191 Diagnostics(env.AtRegexp("b.go", "A = 2")),
192 NoDiagnostics(ForFile("c.go")),
193 )
194 })
195 }
196
197 // Tests golang/go#37978.
198 func TestIssue37978(t *testing.T) {
199 Run(t, exampleProgram, func(t *testing.T, env *Env) {
200 // Create a new workspace-level directory and empty file.
201 env.CreateBuffer("c/c.go", "")
202
203 // Write the file contents with a missing import.
204 env.EditBuffer("c/c.go", protocol.TextEdit{
205 NewText: `package c
206
207 const A = http.MethodGet
208 `,
209 })
210 env.AfterChange(
211 Diagnostics(env.AtRegexp("c/c.go", "http.MethodGet")),
212 )
213 // Save file, which will organize imports, adding the expected import.
214 // Expect the diagnostics to clear.
215 env.SaveBuffer("c/c.go")
216 env.AfterChange(
217 NoDiagnostics(ForFile("c/c.go")),
218 )
219 })
220 }
221
222 // Tests golang/go#38878: good a.go, bad a_test.go, remove a_test.go but its errors remain
223 // If the file is open in the editor, this is working as intended
224 // If the file is not open in the editor, the errors go away
225 const test38878 = `
226 -- go.mod --
227 module foo
228
229 go 1.12
230 -- a.go --
231 package x
232
233 // import "fmt"
234
235 func f() {}
236
237 -- a_test.go --
238 package x
239
240 import "testing"
241
242 func TestA(t *testing.T) {
243 f(3)
244 }
245 `
246
247 // Tests golang/go#38878: deleting a test file should clear its errors, and
248 // not break the workspace.
249 func TestDeleteTestVariant(t *testing.T) {
250 Run(t, test38878, func(t *testing.T, env *Env) {
251 env.AfterChange(Diagnostics(env.AtRegexp("a_test.go", `f\((3)\)`)))
252 env.RemoveWorkspaceFile("a_test.go")
253 env.AfterChange(NoDiagnostics(ForFile("a_test.go")))
254
255 // Make sure the test variant has been removed from the workspace by
256 // triggering a metadata load.
257 env.OpenFile("a.go")
258 env.RegexpReplace("a.go", `// import`, "import")
259 env.AfterChange(Diagnostics(env.AtRegexp("a.go", `"fmt"`)))
260 })
261 }
262
263 // Tests golang/go#38878: deleting a test file on disk while it's still open
264 // should not clear its errors.
265 func TestDeleteTestVariant_DiskOnly(t *testing.T) {
266 Run(t, test38878, func(t *testing.T, env *Env) {
267 env.OpenFile("a_test.go")
268 env.AfterChange(Diagnostics(AtPosition("a_test.go", 5, 3)))
269 env.Sandbox.Workdir.RemoveFile(context.Background(), "a_test.go") // ignore error
270 env.AfterChange(Diagnostics(AtPosition("a_test.go", 5, 3)))
271 })
272 }
273
274 // TestNoMod confirms that gopls continues to work when a user adds a go.mod
275 // file to their workspace.
276 func TestNoMod(t *testing.T) {
277 const noMod = `
278 -- main.go --
279 package main
280
281 import "mod.com/bob"
282
283 func main() {
284 bob.Hello()
285 }
286 -- bob/bob.go --
287 package bob
288
289 func Hello() {
290 var x int
291 }
292 `
293
294 t.Run("manual", func(t *testing.T) {
295 Run(t, noMod, func(t *testing.T, env *Env) {
296 env.OnceMet(
297 InitialWorkspaceLoad,
298 Diagnostics(env.AtRegexp("main.go", `"mod.com/bob"`)),
299 )
300 env.CreateBuffer("go.mod", `module mod.com
301
302 go 1.12
303 `)
304 env.SaveBuffer("go.mod")
305 var d protocol.PublishDiagnosticsParams
306 env.AfterChange(
307 NoDiagnostics(ForFile("main.go")),
308 Diagnostics(env.AtRegexp("bob/bob.go", "x")),
309 ReadDiagnostics("bob/bob.go", &d),
310 )
311 if len(d.Diagnostics) != 1 {
312 t.Fatalf("expected 1 diagnostic, got %v", len(d.Diagnostics))
313 }
314 })
315 })
316 t.Run("initialized", func(t *testing.T) {
317 Run(t, noMod, func(t *testing.T, env *Env) {
318 env.OnceMet(
319 InitialWorkspaceLoad,
320 Diagnostics(env.AtRegexp("main.go", `"mod.com/bob"`)),
321 )
322 env.RunGoCommand("mod", "init", "mod.com")
323 env.AfterChange(
324 NoDiagnostics(ForFile("main.go")),
325 Diagnostics(env.AtRegexp("bob/bob.go", "x")),
326 )
327 })
328 })
329
330 t.Run("without workspace module", func(t *testing.T) {
331 WithOptions(
332 Modes(Default),
333 ).Run(t, noMod, func(t *testing.T, env *Env) {
334 env.OnceMet(
335 InitialWorkspaceLoad,
336 Diagnostics(env.AtRegexp("main.go", `"mod.com/bob"`)),
337 )
338 if _, err := env.Sandbox.RunGoCommand(env.Ctx, "", "mod", []string{"init", "mod.com"}, nil, true); err != nil {
339 t.Fatal(err)
340 }
341 env.AfterChange(
342 NoDiagnostics(ForFile("main.go")),
343 Diagnostics(env.AtRegexp("bob/bob.go", "x")),
344 )
345 })
346 })
347 }
348
349 // Tests golang/go#38267.
350 func TestIssue38267(t *testing.T) {
351 const testPackage = `
352 -- go.mod --
353 module mod.com
354
355 go 1.12
356 -- lib.go --
357 package lib
358
359 func Hello(x string) {
360 _ = x
361 }
362 -- lib_test.go --
363 package lib
364
365 import "testing"
366
367 type testStruct struct{
368 name string
369 }
370
371 func TestHello(t *testing.T) {
372 testStructs := []*testStruct{
373 &testStruct{"hello"},
374 &testStruct{"goodbye"},
375 }
376 for y := range testStructs {
377 _ = y
378 }
379 }
380 `
381
382 Run(t, testPackage, func(t *testing.T, env *Env) {
383 env.OpenFile("lib_test.go")
384 env.AfterChange(
385 Diagnostics(AtPosition("lib_test.go", 10, 2)),
386 Diagnostics(AtPosition("lib_test.go", 11, 2)),
387 )
388 env.OpenFile("lib.go")
389 env.RegexpReplace("lib.go", "_ = x", "var y int")
390 env.AfterChange(
391 Diagnostics(env.AtRegexp("lib.go", "y int")),
392 NoDiagnostics(ForFile("lib_test.go")),
393 )
394 })
395 }
396
397 // Tests golang/go#38328.
398 func TestPackageChange_Issue38328(t *testing.T) {
399 const packageChange = `
400 -- go.mod --
401 module fake
402
403 go 1.12
404 -- a.go --
405 package foo
406 func main() {}
407 `
408 Run(t, packageChange, func(t *testing.T, env *Env) {
409 env.OpenFile("a.go")
410 env.RegexpReplace("a.go", "foo", "foox")
411 env.AfterChange(
412 NoDiagnostics(ForFile("a.go")),
413 )
414 })
415 }
416
417 const testPackageWithRequire = `
418 -- go.mod --
419 module mod.com
420
421 go 1.12
422
423 require foo.test v1.2.3
424 -- print.go --
425 package lib
426
427 import (
428 "fmt"
429
430 "foo.test/bar"
431 )
432
433 func PrintAnswer() {
434 fmt.Printf("answer: %s", bar.Answer)
435 }
436 `
437
438 const testPackageWithRequireProxy = `
439 -- [email protected]/go.mod --
440 module foo.test
441
442 go 1.12
443 -- [email protected]/bar/const.go --
444 package bar
445
446 const Answer = 42
447 `
448
449 func TestResolveDiagnosticWithDownload(t *testing.T) {
450 WithOptions(
451 WriteGoSum("."),
452 ProxyFiles(testPackageWithRequireProxy),
453 ).Run(t, testPackageWithRequire, func(t *testing.T, env *Env) {
454 env.OpenFile("print.go")
455 // Check that gopackages correctly loaded this dependency. We should get a
456 // diagnostic for the wrong formatting type.
457 env.AfterChange(
458 Diagnostics(
459 env.AtRegexp("print.go", "%s"),
460 WithMessage("wrong type int"),
461 ),
462 )
463 })
464 }
465
466 func TestMissingDependency(t *testing.T) {
467 Run(t, testPackageWithRequire, func(t *testing.T, env *Env) {
468 env.OpenFile("print.go")
469 env.Await(
470 // Log messages are asynchronous to other events on the LSP stream, so we
471 // can't use OnceMet or AfterChange here.
472 LogMatching(protocol.Error, "initial workspace load failed", 1, false),
473 )
474 })
475 }
476
477 // Tests golang/go#36951.
478 func TestAdHocPackages_Issue36951(t *testing.T) {
479 const adHoc = `
480 -- b/b.go --
481 package b
482
483 func Hello() {
484 var x int
485 }
486 `
487 Run(t, adHoc, func(t *testing.T, env *Env) {
488 env.OpenFile("b/b.go")
489 env.AfterChange(
490 Diagnostics(env.AtRegexp("b/b.go", "x")),
491 )
492 })
493 }
494
495 // Tests golang/go#37984: GOPATH should be read from the go command.
496 func TestNoGOPATH_Issue37984(t *testing.T) {
497 const files = `
498 -- main.go --
499 package main
500
501 func _() {
502 fmt.Println("Hello World")
503 }
504 `
505 WithOptions(
506 EnvVars{
507 "GOPATH": "",
508 "GO111MODULE": "off",
509 },
510 ).Run(t, files, func(t *testing.T, env *Env) {
511 env.OpenFile("main.go")
512 env.AfterChange(Diagnostics(env.AtRegexp("main.go", "fmt")))
513 env.SaveBuffer("main.go")
514 env.AfterChange(NoDiagnostics(ForFile("main.go")))
515 })
516 }
517
518 // Tests golang/go#38669.
519 func TestEqualInEnv_Issue38669(t *testing.T) {
520 const files = `
521 -- go.mod --
522 module mod.com
523
524 go 1.12
525 -- main.go --
526 package main
527
528 var _ = x.X
529 -- x/x.go --
530 package x
531
532 var X = 0
533 `
534 WithOptions(
535 EnvVars{"GOFLAGS": "-tags=foo"},
536 ).Run(t, files, func(t *testing.T, env *Env) {
537 env.OpenFile("main.go")
538 env.OrganizeImports("main.go")
539 env.AfterChange(NoDiagnostics(ForFile("main.go")))
540 })
541 }
542
543 // Tests golang/go#38467.
544 func TestNoSuggestedFixesForGeneratedFiles_Issue38467(t *testing.T) {
545 // This test ensures that gopls' CodeAction handler suppresses
546 // diagnostics in generated code. Beware that many analyzers
547 // themselves suppress diagnostics in generated files, in
548 // particular the low-status "simplifiers" (modernize,
549 // simplify{range,slice,compositelit}), so we use the hostport
550 // analyzer here.
551 const generated = `
552 -- go.mod --
553 module mod.com
554
555 go 1.12
556 -- main.go --
557 // Code generated by generator.go. DO NOT EDIT.
558
559 package main
560
561 import ("fmt"; "net")
562
563 func _() {
564 addr := fmt.Sprintf("%s:%d", "localhost", 12345)
565 net.Dial("tcp", addr)
566 }
567 `
568 Run(t, generated, func(t *testing.T, env *Env) {
569 env.OpenFile("main.go")
570 var d protocol.PublishDiagnosticsParams
571 env.AfterChange(
572 Diagnostics(AtPosition("main.go", 7, 21)),
573 ReadDiagnostics("main.go", &d),
574 )
575 if fixes := env.GetQuickFixes("main.go", d.Diagnostics); len(fixes) != 0 {
576 t.Errorf("got quick fixes %v, wanted none", fixes)
577 }
578 })
579 }
580
581 // Expect a module/GOPATH error if there is an error in the file at startup.
582 // Tests golang/go#37279.
583 func TestBrokenWorkspace_OutsideModule(t *testing.T) {
584 const noModule = `
585 -- a.go --
586 package foo
587
588 import "mod.com/hello"
589
590 func f() {
591 hello.Goodbye()
592 }
593 `
594 Run(t, noModule, func(t *testing.T, env *Env) {
595 env.OpenFile("a.go")
596 env.AfterChange(
597 // AdHoc views are not critical errors, but their missing import
598 // diagnostics should specifically mention GOROOT or GOPATH (and not
599 // modules).
600 NoOutstandingWork(IgnoreTelemetryPromptWork),
601 Diagnostics(
602 env.AtRegexp("a.go", `"mod.com`),
603 WithMessage("in GOROOT"),
604 ),
605 )
606 // Deleting the import dismisses the warning.
607 env.RegexpReplace("a.go", `import "mod.com/hello"`, "")
608 env.AfterChange(
609 NoOutstandingWork(IgnoreTelemetryPromptWork),
610 )
611 })
612 }
613
614 func TestNonGoFolder(t *testing.T) {
615 const files = `
616 -- hello.txt --
617 hi mom
618 `
619 for _, go111module := range []string{"on", "off", ""} {
620 t.Run(fmt.Sprintf("GO111MODULE_%v", go111module), func(t *testing.T) {
621 WithOptions(
622 EnvVars{"GO111MODULE": go111module},
623 ).Run(t, files, func(t *testing.T, env *Env) {
624 env.OnceMet(
625 InitialWorkspaceLoad,
626 NoOutstandingWork(IgnoreTelemetryPromptWork),
627 )
628 })
629 })
630 }
631 }
632
633 // Tests the repro case from golang/go#38602. Diagnostics are now handled properly,
634 // which blocks type checking.
635 func TestConflictingMainPackageErrors(t *testing.T) {
636 const collision = `
637 -- x/x.go --
638 package x
639
640 import "x/hello"
641
642 func Hello() {
643 hello.HiThere()
644 }
645 -- x/main.go --
646 package main
647
648 func main() {
649 fmt.Println("")
650 }
651 `
652 WithOptions(
653 InGOPATH(),
654 EnvVars{"GO111MODULE": "off"},
655 ).Run(t, collision, func(t *testing.T, env *Env) {
656 env.OpenFile("x/x.go")
657 env.AfterChange(
658 Diagnostics(env.AtRegexp("x/x.go", `^`), WithMessage("found packages main (main.go) and x (x.go)")),
659 Diagnostics(env.AtRegexp("x/main.go", `^`), WithMessage("found packages main (main.go) and x (x.go)")),
660 )
661
662 // We don't recover cleanly from the errors without good overlay support.
663 if testenv.Go1Point() >= 16 {
664 env.RegexpReplace("x/x.go", `package x`, `package main`)
665 env.AfterChange(
666 Diagnostics(env.AtRegexp("x/main.go", `fmt`)),
667 )
668 }
669 })
670 }
671
672 const ardanLabsProxy = `
673 -- github.com/ardanlabs/[email protected]/go.mod --
674 module github.com/ardanlabs/conf
675
676 go 1.12
677 -- github.com/ardanlabs/[email protected]/conf.go --
678 package conf
679
680 var ErrHelpWanted error
681 `
682
683 // Test for golang/go#38211.
684 func Test_issue38211(t *testing.T) {
685 const ardanLabs = `
686 -- go.mod --
687 module mod.com
688
689 go 1.14
690 -- main.go --
691 package main
692
693 import "github.com/ardanlabs/conf"
694
695 func main() {
696 _ = conf.ErrHelpWanted
697 }
698 `
699
700 modcache := t.TempDir()
701 defer CleanModCache(t, modcache)
702
703 opts := []RunOption{
704 EnvVars{"GOMODCACHE": modcache},
705 ProxyFiles(ardanLabsProxy),
706 //WriteGoSum("."), // TODO(golang/go#74594): uncommenting this causes mysterious failure; investigate and make the error clearer (go list?)
707 }
708
709 t.Run("setup", func(t *testing.T) {
710 // Forcibly populate GOMODCACHE
711 // so OrganizeImports can later rely on it.
712 WithOptions(opts...).Run(t, ardanLabs, func(t *testing.T, env *Env) {
713 // TODO(adonovan): why doesn't RunGoCommand respect EnvVars??
714 // (That was the motivation to use Sandbox.RunGoCommand
715 // rather than execute go mod download directly!)
716 // See comment at CleanModCache and golang/go#74595.
717 environ := []string{"GOMODCACHE=" + modcache}
718 _, err := env.Sandbox.RunGoCommand(env.Ctx, "", "get", []string{"github.com/ardanlabs/[email protected]"}, environ, false)
719 if err != nil {
720 t.Error(err)
721 }
722 })
723 })
724
725 WithOptions(opts...).Run(t, ardanLabs, func(t *testing.T, env *Env) {
726 // Expect a "no module provides package" diagnostic.
727 env.OpenFile("go.mod")
728 env.OpenFile("main.go")
729 var d protocol.PublishDiagnosticsParams
730 env.AfterChange(
731 Diagnostics(
732 env.AtRegexp("main.go", `"github.com/ardanlabs/conf"`),
733 WithMessage("no required module provides package")),
734 ReadDiagnostics("main.go", &d),
735 )
736
737 // Apply the suggested fix to make the go.mod file
738 // require "github.com/ardanlabs/conf".
739 env.ApplyQuickFixes("main.go", d.Diagnostics)
740 env.SaveBuffer("go.mod")
741 env.AfterChange(
742 NoDiagnostics(ForFile("main.go")),
743 )
744
745 // Comment out the sole use of conf,
746 // causing an "unused import" diagnostic.
747 env.RegexpReplace("main.go", "_ = conf.ErrHelpWanted", "//_ = conf.ErrHelpWanted")
748 env.AfterChange(
749 Diagnostics(
750 env.AtRegexp("main.go", `"github.com/ardanlabs/conf"`),
751 WithMessage("imported and not used")),
752 )
753
754 // Remove the import using OrganizeImports, leading
755 // to an "unused require" diagnostic in the go.mod.
756 env.SaveBuffer("main.go") // => OrganizeImports
757 env.AfterChange(
758 NoDiagnostics(ForFile("main.go")),
759 Diagnostics(
760 env.AtRegexp("go.mod", "require github.com/ardanlabs/conf"),
761 WithMessage("not used in this module")),
762 ReadDiagnostics("go.mod", &d),
763 )
764
765 // Apply the suggested fix to remove the "require" directive.
766 env.ApplyQuickFixes("go.mod", d.Diagnostics)
767 env.SaveBuffer("go.mod")
768 env.AfterChange(
769 NoDiagnostics(ForFile("go.mod")),
770 )
771
772 // Uncomment the use of the import.
773 // OrganizeImports should add the import.
774 // Expect another "no required module provides package"
775 // diagnostic, bringing us full circle.
776 env.RegexpReplace("main.go", "//_ = conf.ErrHelpWanted", "_ = conf.ErrHelpWanted")
777 env.SaveBuffer("main.go") // => OrganizeImports
778 env.AfterChange(
779 Diagnostics(
780 env.AtRegexp("main.go", `"github.com/ardanlabs/conf"`),
781 WithMessage("no required module provides package")),
782 )
783 })
784 }
785
786 // Test for golang/go#38207.
787 func TestNewModule_Issue38207(t *testing.T) {
788 const emptyFile = `
789 -- go.mod --
790 module mod.com
791
792 go 1.12
793 -- main.go --
794 `
795 WithOptions(
796 ProxyFiles(ardanLabsProxy),
797 ).Run(t, emptyFile, func(t *testing.T, env *Env) {
798 env.CreateBuffer("main.go", `package main
799
800 import "github.com/ardanlabs/conf"
801
802 func main() {
803 _ = conf.ErrHelpWanted
804 }
805 `)
806 env.SaveBuffer("main.go")
807 var d protocol.PublishDiagnosticsParams
808 env.AfterChange(
809 Diagnostics(env.AtRegexp("main.go", `"github.com/ardanlabs/conf"`), WithMessage("no required module")),
810 ReadDiagnostics("main.go", &d),
811 )
812 env.ApplyQuickFixes("main.go", d.Diagnostics)
813 env.AfterChange(
814 NoDiagnostics(ForFile("main.go")),
815 )
816 })
817 }
818
819 // Test for golang/go#36960.
820 func TestNewFileBadImports_Issue36960(t *testing.T) {
821 const simplePackage = `
822 -- go.mod --
823 module mod.com
824
825 go 1.14
826 -- a/a1.go --
827 package a
828
829 import "fmt"
830
831 func _() {
832 fmt.Println("hi")
833 }
834 `
835 Run(t, simplePackage, func(t *testing.T, env *Env) {
836 env.OpenFile("a/a1.go")
837 env.CreateBuffer("a/a2.go", ``)
838 env.SaveBufferWithoutActions("a/a2.go")
839 env.AfterChange(
840 NoDiagnostics(ForFile("a/a1.go")),
841 )
842 env.EditBuffer("a/a2.go", fake.NewEdit(0, 0, 0, 0, `package a`))
843 env.AfterChange(
844 NoDiagnostics(ForFile("a/a1.go")),
845 )
846 })
847 }
848
849 // This test tries to replicate the workflow of a user creating a new x test.
850 // It also tests golang/go#39315.
851 func TestManuallyCreatingXTest(t *testing.T) {
852 // Create a package that already has a test variant (in-package test).
853 const testVariant = `
854 -- go.mod --
855 module mod.com
856
857 go 1.15
858 -- hello/hello.go --
859 package hello
860
861 func Hello() {
862 var x int
863 }
864 -- hello/hello_test.go --
865 package hello
866
867 import "testing"
868
869 func TestHello(t *testing.T) {
870 var x int
871 Hello()
872 }
873 `
874 Run(t, testVariant, func(t *testing.T, env *Env) {
875 // Open the file, triggering the workspace load.
876 // There are errors in the code to ensure all is working as expected.
877 env.OpenFile("hello/hello.go")
878 env.AfterChange(
879 Diagnostics(env.AtRegexp("hello/hello.go", "x")),
880 Diagnostics(env.AtRegexp("hello/hello_test.go", "x")),
881 )
882
883 // Create an empty file with the intention of making it an x test.
884 // This resembles a typical flow in an editor like VS Code, in which
885 // a user would create an empty file and add content, saving
886 // intermittently.
887 // TODO(rstambler): There might be more edge cases here, as file
888 // content can be added incrementally.
889 env.CreateBuffer("hello/hello_x_test.go", ``)
890
891 // Save the empty file (no actions since formatting will fail).
892 env.SaveBufferWithoutActions("hello/hello_x_test.go")
893
894 // Add the content. The missing import is for the package under test.
895 env.EditBuffer("hello/hello_x_test.go", fake.NewEdit(0, 0, 0, 0, `package hello_test
896
897 import (
898 "testing"
899 )
900
901 func TestHello(t *testing.T) {
902 hello.Hello()
903 }
904 `))
905 // Expect a diagnostic for the missing import. Save, which should
906 // trigger import organization. The diagnostic should clear.
907 env.AfterChange(
908 Diagnostics(env.AtRegexp("hello/hello_x_test.go", "hello.Hello")),
909 )
910 env.SaveBuffer("hello/hello_x_test.go")
911 env.AfterChange(
912 NoDiagnostics(ForFile("hello/hello_x_test.go")),
913 )
914 })
915 }
916
917 // Reproduce golang/go#40690.
918 func TestCreateOnlyXTest(t *testing.T) {
919 const mod = `
920 -- go.mod --
921 module mod.com
922
923 go 1.12
924 -- foo/foo.go --
925 package foo
926 -- foo/bar_test.go --
927 `
928 Run(t, mod, func(t *testing.T, env *Env) {
929 env.OpenFile("foo/bar_test.go")
930 env.EditBuffer("foo/bar_test.go", fake.NewEdit(0, 0, 0, 0, "package foo"))
931 env.Await(env.DoneWithChange())
932 env.RegexpReplace("foo/bar_test.go", "package foo", `package foo_test
933
934 import "testing"
935
936 func TestX(t *testing.T) {
937 var x int
938 }
939 `)
940 env.AfterChange(
941 Diagnostics(env.AtRegexp("foo/bar_test.go", "x")),
942 )
943 })
944 }
945
946 func TestChangePackageName(t *testing.T) {
947 const mod = `
948 -- go.mod --
949 module mod.com
950
951 go 1.12
952 -- foo/foo.go --
953 package foo
954 -- foo/bar_test.go --
955 package foo_
956 `
957 Run(t, mod, func(t *testing.T, env *Env) {
958 env.OpenFile("foo/bar_test.go")
959 env.AfterChange()
960 env.RegexpReplace("foo/bar_test.go", "package foo_", "package foo_test")
961 env.AfterChange(
962 NoDiagnostics(ForFile("foo/bar_test.go")),
963 NoDiagnostics(ForFile("foo/foo.go")),
964 )
965 })
966 }
967
968 func TestIgnoredFiles(t *testing.T) {
969 const ws = `
970 -- go.mod --
971 module mod.com
972
973 go 1.12
974 -- _foo/x.go --
975 package x
976
977 var _ = foo.Bar
978 `
979 Run(t, ws, func(t *testing.T, env *Env) {
980 env.OpenFile("_foo/x.go")
981 env.AfterChange(
982 NoDiagnostics(ForFile("_foo/x.go")),
983 )
984 })
985 }
986
987 // Partially reproduces golang/go#38977, moving a file between packages.
988 // It also gets hit by some go command bug fixed in 1.15, but we don't
989 // care about that so much here.
990 func TestDeletePackage(t *testing.T) {
991 const ws = `
992 -- go.mod --
993 module mod.com
994
995 go 1.15
996 -- a/a.go --
997 package a
998
999 const A = 1
1000
1001 -- b/b.go --
1002 package b
1003
1004 import "mod.com/a"
1005
1006 const B = a.A
1007
1008 -- c/c.go --
1009 package c
1010
1011 import "mod.com/a"
1012
1013 const C = a.A
1014 `
1015 Run(t, ws, func(t *testing.T, env *Env) {
1016 env.OpenFile("b/b.go")
1017 env.Await(env.DoneWithOpen())
1018 // Delete c/c.go, the only file in package c.
1019 env.RemoveWorkspaceFile("c/c.go")
1020
1021 // We should still get diagnostics for files that exist.
1022 env.RegexpReplace("b/b.go", `a.A`, "a.Nonexistant")
1023 env.AfterChange(
1024 Diagnostics(env.AtRegexp("b/b.go", `Nonexistant`)),
1025 )
1026 })
1027 }
1028
1029 // This is a copy of the scenario_default/quickfix_empty_files.txt test from
1030 // govim. Reproduces golang/go#39646.
1031 func TestQuickFixEmptyFiles(t *testing.T) {
1032 const mod = `
1033 -- go.mod --
1034 module mod.com
1035
1036 go 1.12
1037 `
1038 // To fully recreate the govim tests, we create files by inserting
1039 // a newline, adding to the file, and then deleting the newline.
1040 // Wait for each event to process to avoid cancellations and force
1041 // package loads.
1042 writeGoVim := func(env *Env, name, content string) {
1043 env.WriteWorkspaceFile(name, "")
1044 env.Await(env.DoneWithChangeWatchedFiles())
1045
1046 env.CreateBuffer(name, "\n")
1047 env.Await(env.DoneWithOpen())
1048
1049 env.EditBuffer(name, fake.NewEdit(1, 0, 1, 0, content))
1050 env.Await(env.DoneWithChange())
1051
1052 env.EditBuffer(name, fake.NewEdit(0, 0, 1, 0, ""))
1053 env.Await(env.DoneWithChange())
1054 }
1055
1056 const p = `package p; func DoIt(s string) {};`
1057 const main = `package main
1058
1059 import "mod.com/p"
1060
1061 func main() {
1062 p.DoIt(5)
1063 }
1064 `
1065 // A simple version of the test that reproduces most of the problems it
1066 // exposes.
1067 t.Run("short", func(t *testing.T) {
1068 Run(t, mod, func(t *testing.T, env *Env) {
1069 writeGoVim(env, "p/p.go", p)
1070 writeGoVim(env, "main.go", main)
1071 env.AfterChange(
1072 Diagnostics(env.AtRegexp("main.go", "5")),
1073 )
1074 })
1075 })
1076
1077 // A full version that replicates the whole flow of the test.
1078 t.Run("full", func(t *testing.T) {
1079 Run(t, mod, func(t *testing.T, env *Env) {
1080 writeGoVim(env, "p/p.go", p)
1081 writeGoVim(env, "main.go", main)
1082 writeGoVim(env, "p/p_test.go", `package p
1083
1084 import "testing"
1085
1086 func TestDoIt(t *testing.T) {
1087 DoIt(5)
1088 }
1089 `)
1090 writeGoVim(env, "p/x_test.go", `package p_test
1091
1092 import (
1093 "testing"
1094
1095 "mod.com/p"
1096 )
1097
1098 func TestDoIt(t *testing.T) {
1099 p.DoIt(5)
1100 }
1101 `)
1102 env.AfterChange(
1103 Diagnostics(env.AtRegexp("main.go", "5")),
1104 Diagnostics(env.AtRegexp("p/p_test.go", "5")),
1105 Diagnostics(env.AtRegexp("p/x_test.go", "5")),
1106 )
1107 env.RegexpReplace("p/p.go", "s string", "i int")
1108 env.AfterChange(
1109 NoDiagnostics(ForFile("main.go")),
1110 NoDiagnostics(ForFile("p/p_test.go")),
1111 NoDiagnostics(ForFile("p/x_test.go")),
1112 )
1113 })
1114 })
1115 }
1116
1117 func TestSingleFile(t *testing.T) {
1118 const mod = `
1119 -- go.mod --
1120 module mod.com
1121
1122 go 1.13
1123 -- a/a.go --
1124 package a
1125
1126 func _() {
1127 var x int
1128 }
1129 `
1130 WithOptions(
1131 // Empty workspace folders.
1132 WorkspaceFolders(),
1133 ).Run(t, mod, func(t *testing.T, env *Env) {
1134 env.OpenFile("a/a.go")
1135 env.AfterChange(
1136 Diagnostics(env.AtRegexp("a/a.go", "x")),
1137 )
1138 })
1139 }
1140
1141 // Reproduces the case described in
1142 // https://github.com/golang/go/issues/39296#issuecomment-652058883.
1143 func TestPkgm(t *testing.T) {
1144 const basic = `
1145 -- go.mod --
1146 module mod.com
1147
1148 go 1.15
1149 -- foo/foo.go --
1150 package foo
1151
1152 import "fmt"
1153
1154 func Foo() {
1155 fmt.Println("")
1156 }
1157 `
1158 Run(t, basic, func(t *testing.T, env *Env) {
1159 env.WriteWorkspaceFile("foo/foo_test.go", `package main
1160
1161 func main() {
1162
1163 }`)
1164 env.OpenFile("foo/foo_test.go")
1165 env.RegexpReplace("foo/foo_test.go", `package main`, `package foo`)
1166 env.AfterChange(NoDiagnostics(ForFile("foo/foo.go")))
1167 })
1168 }
1169
1170 func TestClosingBuffer(t *testing.T) {
1171 const basic = `
1172 -- go.mod --
1173 module mod.com
1174
1175 go 1.14
1176 -- main.go --
1177 package main
1178
1179 func main() {}
1180 `
1181 Run(t, basic, func(t *testing.T, env *Env) {
1182 env.CreateBuffer("foo.go", `package main`)
1183 env.AfterChange()
1184 env.CloseBuffer("foo.go")
1185 env.AfterChange(NoLogMatching(protocol.Info, "packages=0"))
1186 })
1187 }
1188
1189 // Reproduces golang/go#38424.
1190 func TestCutAndPaste(t *testing.T) {
1191 const basic = `
1192 -- go.mod --
1193 module mod.com
1194
1195 go 1.14
1196 -- main2.go --
1197 package main
1198 `
1199 Run(t, basic, func(t *testing.T, env *Env) {
1200 env.CreateBuffer("main.go", "")
1201 env.Await(env.DoneWithOpen())
1202
1203 env.SaveBufferWithoutActions("main.go")
1204 env.Await(env.DoneWithSave(), env.DoneWithChangeWatchedFiles())
1205
1206 env.EditBuffer("main.go", fake.NewEdit(0, 0, 0, 0, `package main
1207
1208 func main() {
1209 }
1210 `))
1211 env.Await(env.DoneWithChange())
1212
1213 env.SaveBuffer("main.go")
1214 env.Await(env.DoneWithSave(), env.DoneWithChangeWatchedFiles())
1215
1216 env.EditBuffer("main.go", fake.NewEdit(0, 0, 4, 0, ""))
1217 env.Await(env.DoneWithChange())
1218
1219 env.EditBuffer("main.go", fake.NewEdit(0, 0, 0, 0, `package main
1220
1221 func main() {
1222 var x int
1223 }
1224 `))
1225 env.AfterChange(
1226 Diagnostics(env.AtRegexp("main.go", "x")),
1227 )
1228 })
1229 }
1230
1231 // Reproduces golang/go#39763.
1232 func TestInvalidPackageName(t *testing.T) {
1233 const pkgDefault = `
1234 -- go.mod --
1235 module mod.com
1236
1237 go 1.12
1238 -- main.go --
1239 package default
1240
1241 func main() {}
1242 `
1243 Run(t, pkgDefault, func(t *testing.T, env *Env) {
1244 env.OpenFile("main.go")
1245 env.AfterChange(
1246 Diagnostics(
1247 env.AtRegexp("main.go", "default"),
1248 WithMessage("expected 'IDENT'"),
1249 ),
1250 )
1251 })
1252 }
1253
1254 // This test verifies that the workspace scope is effectively limited to the
1255 // workspace folder, if expandWorkspaceToModule is set.
1256 func TestExpandWorkspaceToModule(t *testing.T) {
1257 const mod = `
1258 -- go.mod --
1259 module mod.com
1260
1261 go 1.12
1262 -- a/main.go --
1263 package main
1264
1265 func main() {}
1266 -- main.go --
1267 package main
1268
1269 func main() {
1270 var x int
1271 }
1272 `
1273 WithOptions(
1274 WorkspaceFolders("a"),
1275 ).Run(t, mod, func(t *testing.T, env *Env) {
1276 env.OpenFile("a/main.go")
1277 env.AfterChange(
1278 Diagnostics(env.AtRegexp("main.go", "x")),
1279 )
1280 })
1281 WithOptions(
1282 WorkspaceFolders("a"),
1283 Settings{"expandWorkspaceToModule": false},
1284 ).Run(t, mod, func(t *testing.T, env *Env) {
1285 env.OpenFile("a/main.go")
1286 env.AfterChange(
1287 NoDiagnostics(ForFile("main.go")),
1288 )
1289 })
1290 }
1291
1292 // This test verifies that the workspace scope is effectively limited to the
1293 // set of active modules.
1294 //
1295 // We should not get diagnostics or file watching patterns for paths outside of
1296 // the active workspace.
1297 func TestWorkspaceModules(t *testing.T) {
1298 const mod = `
1299 -- go.work --
1300 go 1.18
1301
1302 use a
1303 -- a/go.mod --
1304 module mod.com/a
1305
1306 go 1.12
1307 -- a/a.go --
1308 package a
1309
1310 func _() {
1311 var x int
1312 }
1313 -- b/go.mod --
1314 module mod.com/b
1315
1316 go 1.18
1317 `
1318 WithOptions(
1319 Settings{
1320 "subdirWatchPatterns": "on",
1321 },
1322 ).Run(t, mod, func(t *testing.T, env *Env) {
1323 env.OpenFile("a/a.go")
1324 // Writing this file may cause the snapshot to 'know' about the file b, but
1325 // that shouldn't cause it to watch the 'b' directory.
1326 env.WriteWorkspaceFile("b/b.go", `package b
1327
1328 func _() {
1329 var x int
1330 }
1331 `)
1332 env.AfterChange(
1333 Diagnostics(env.AtRegexp("a/a.go", "x")),
1334 NoDiagnostics(ForFile("b/b.go")),
1335 FileWatchMatching("a$"),
1336 NoFileWatchMatching("b$"),
1337 )
1338 })
1339 }
1340
1341 func TestSimplifyCompositeLitDiagnostic(t *testing.T) {
1342 const files = `
1343 -- go.mod --
1344 module mod.com
1345
1346 go 1.12
1347 -- main.go --
1348 package main
1349
1350 import "fmt"
1351
1352 type t struct {
1353 msg string
1354 }
1355
1356 func main() {
1357 x := []t{t{"msg"}}
1358 fmt.Println(x)
1359 }
1360 `
1361
1362 WithOptions(
1363 Settings{"staticcheck": true},
1364 ).Run(t, files, func(t *testing.T, env *Env) {
1365 env.OpenFile("main.go")
1366 var d protocol.PublishDiagnosticsParams
1367 env.AfterChange(
1368 Diagnostics(env.AtRegexp("main.go", `t{"msg"}`), WithMessage("redundant type")),
1369 ReadDiagnostics("main.go", &d),
1370 )
1371 if tags := d.Diagnostics[0].Tags; len(tags) == 0 || tags[0] != protocol.Unnecessary {
1372 t.Errorf("wanted Unnecessary tag on diagnostic, got %v", tags)
1373 }
1374 env.ApplyQuickFixes("main.go", d.Diagnostics)
1375 env.AfterChange(NoDiagnostics(ForFile("main.go")))
1376 })
1377 }
1378
1379 // Test some secondary diagnostics
1380 func TestSecondaryDiagnostics(t *testing.T) {
1381 const dir = `
1382 -- go.mod --
1383 module mod.com
1384
1385 go 1.12
1386 -- main.go --
1387 package main
1388 func main() {
1389 panic("not here")
1390 }
1391 -- other.go --
1392 package main
1393 func main() {}
1394 `
1395 Run(t, dir, func(t *testing.T, env *Env) {
1396 env.OpenFile("main.go")
1397 env.OpenFile("other.go")
1398 var mainDiags, otherDiags protocol.PublishDiagnosticsParams
1399 env.AfterChange(
1400 ReadDiagnostics("main.go", &mainDiags),
1401 ReadDiagnostics("other.go", &otherDiags),
1402 )
1403 if len(mainDiags.Diagnostics) != 1 {
1404 t.Fatalf("main.go, got %d diagnostics, expected 1", len(mainDiags.Diagnostics))
1405 }
1406 keep := mainDiags.Diagnostics[0]
1407 if len(otherDiags.Diagnostics) != 1 {
1408 t.Fatalf("other.go: got %d diagnostics, expected 1", len(otherDiags.Diagnostics))
1409 }
1410 if len(otherDiags.Diagnostics[0].RelatedInformation) != 1 {
1411 t.Fatalf("got %d RelatedInformations, expected 1", len(otherDiags.Diagnostics[0].RelatedInformation))
1412 }
1413 // check that the RelatedInformation matches the error from main.go
1414 c := otherDiags.Diagnostics[0].RelatedInformation[0]
1415 if c.Location.Range != keep.Range {
1416 t.Errorf("locations don't match. Got %v expected %v", c.Location.Range, keep.Range)
1417 }
1418 })
1419 }
1420
1421 func TestOrphanedFiles(t *testing.T) {
1422 const files = `
1423 -- go.mod --
1424 module mod.com
1425
1426 go 1.12
1427 -- a/a.go --
1428 package a
1429
1430 func main() {
1431 var x int
1432 }
1433 -- a/a_exclude.go --
1434 // +build exclude
1435
1436 package a
1437
1438 func _() {
1439 var x int
1440 }
1441 `
1442 Run(t, files, func(t *testing.T, env *Env) {
1443 env.OpenFile("a/a.go")
1444 env.AfterChange(
1445 Diagnostics(env.AtRegexp("a/a.go", "x")),
1446 )
1447 env.OpenFile("a/a_exclude.go")
1448
1449 loadOnce := LogMatching(protocol.Info, "query=.*file=.*a_exclude.go", 1, false)
1450
1451 // can't use OnceMet or AfterChange as logs are async
1452 env.Await(loadOnce)
1453 // ...but ensure that the change has been fully processed before editing.
1454 // Otherwise, there may be a race where the snapshot is cloned before all
1455 // state changes resulting from the load have been processed
1456 // (golang/go#61521).
1457 env.AfterChange()
1458
1459 // Check that orphaned files are not reloaded, by making a change in
1460 // a.go file and confirming that the workspace diagnosis did not reload
1461 // a_exclude.go.
1462 //
1463 // This is racy (but fails open) because logs are asynchronous to other LSP
1464 // operations. There's a chance gopls _did_ log, and we just haven't seen
1465 // it yet.
1466 env.RegexpReplace("a/a.go", "package a", "package a // arbitrary comment")
1467 env.AfterChange(loadOnce)
1468 })
1469 }
1470
1471 func TestSwig(t *testing.T) {
1472 if _, err := exec.LookPath("swig"); err != nil {
1473 t.Skip("skipping test: swig not available")
1474 }
1475 if _, err := exec.LookPath("g++"); err != nil {
1476 t.Skip("skipping test: g++ not available")
1477 }
1478
1479 const mod = `
1480 -- go.mod --
1481 module mod.com
1482
1483 go 1.12
1484 -- pkg/simple/export_swig.go --
1485 package simple
1486
1487 func ExportSimple(x, y int) int {
1488 return Gcd(x, y)
1489 }
1490 -- pkg/simple/simple.swigcxx --
1491 %module simple
1492
1493 %inline %{
1494 extern int gcd(int x, int y)
1495 {
1496 int g;
1497 g = y;
1498 while (x > 0) {
1499 g = x;
1500 x = y % x;
1501 y = g;
1502 }
1503 return g;
1504 }
1505 %}
1506 -- main.go --
1507 package a
1508
1509 func main() {
1510 var x int
1511 }
1512 `
1513 Run(t, mod, func(t *testing.T, env *Env) {
1514 env.OnceMet(
1515 InitialWorkspaceLoad,
1516 NoDiagnostics(WithMessage("illegal character U+0023 '#'")),
1517 )
1518 })
1519 }
1520
1521 // When foo_test.go is opened, gopls will object to the borked package name.
1522 // This test asserts that when the package name is fixed, gopls will soon after
1523 // have no more complaints about it.
1524 // https://github.com/golang/go/issues/41061
1525 func TestRenamePackage(t *testing.T) {
1526 const proxy = `
1527 -- [email protected]/go.mod --
1528 module example.com
1529
1530 go 1.12
1531 -- [email protected]/blah/blah.go --
1532 package blah
1533
1534 const Name = "Blah"
1535 -- [email protected]/go.mod --
1536 module random.org
1537
1538 go 1.12
1539 -- [email protected]/blah/blah.go --
1540 package hello
1541
1542 const Name = "Hello"
1543 `
1544
1545 const contents = `
1546 -- go.mod --
1547 module mod.com
1548
1549 go 1.12
1550 -- main.go --
1551 package main
1552
1553 import "example.com/blah"
1554
1555 func main() {
1556 blah.Hello()
1557 }
1558 -- bob.go --
1559 package main
1560 -- foo/foo.go --
1561 package foo
1562 -- foo/foo_test.go --
1563 package foo_
1564 `
1565
1566 WithOptions(
1567 ProxyFiles(proxy),
1568 InGOPATH(),
1569 EnvVars{"GO111MODULE": "off"},
1570 ).Run(t, contents, func(t *testing.T, env *Env) {
1571 // Simulate typing character by character.
1572 env.OpenFile("foo/foo_test.go")
1573 env.Await(env.DoneWithOpen())
1574 env.RegexpReplace("foo/foo_test.go", "_", "_t")
1575 env.Await(env.DoneWithChange())
1576 env.RegexpReplace("foo/foo_test.go", "_t", "_test")
1577 env.AfterChange(
1578 NoDiagnostics(ForFile("foo/foo_test.go")),
1579 NoOutstandingWork(IgnoreTelemetryPromptWork),
1580 )
1581 })
1582 }
1583
1584 // TestProgressBarErrors confirms that critical workspace load errors are shown
1585 // and updated via progress reports.
1586 func TestProgressBarErrors(t *testing.T) {
1587 const pkg = `
1588 -- go.mod --
1589 modul mod.com
1590
1591 go 1.12
1592 -- main.go --
1593 package main
1594 `
1595 Run(t, pkg, func(t *testing.T, env *Env) {
1596 env.OpenFile("go.mod")
1597 env.AfterChange(
1598 OutstandingWork(server.WorkspaceLoadFailure, "unknown directive"),
1599 )
1600 env.EditBuffer("go.mod", fake.NewEdit(0, 0, 3, 0, `module mod.com
1601
1602 go 1.hello
1603 `))
1604 // As of golang/go#42529, go.mod changes do not reload the workspace until
1605 // they are saved.
1606 env.SaveBufferWithoutActions("go.mod")
1607 env.AfterChange(
1608 OutstandingWork(server.WorkspaceLoadFailure, "invalid go version"),
1609 )
1610 env.RegexpReplace("go.mod", "go 1.hello", "go 1.12")
1611 env.SaveBufferWithoutActions("go.mod")
1612 env.AfterChange(
1613 NoOutstandingWork(IgnoreTelemetryPromptWork),
1614 )
1615 })
1616 }
1617
1618 func TestDeleteDirectory(t *testing.T) {
1619 const mod = `
1620 -- bob/bob.go --
1621 package bob
1622
1623 func Hello() {
1624 var x int
1625 }
1626 -- go.mod --
1627 module mod.com
1628 -- cmd/main.go --
1629 package main
1630
1631 import "mod.com/bob"
1632
1633 func main() {
1634 bob.Hello()
1635 }
1636 `
1637 WithOptions(
1638 Settings{
1639 // Now that we don't watch subdirs by default (except for VS Code),
1640 // we must explicitly ask gopls to requests subdir watch patterns.
1641 "subdirWatchPatterns": "on",
1642 },
1643 ).Run(t, mod, func(t *testing.T, env *Env) {
1644 env.OnceMet(
1645 InitialWorkspaceLoad,
1646 FileWatchMatching("bob"),
1647 )
1648 env.RemoveWorkspaceFile("bob")
1649 env.AfterChange(
1650 Diagnostics(env.AtRegexp("cmd/main.go", `"mod.com/bob"`)),
1651 NoDiagnostics(ForFile("bob/bob.go")),
1652 NoFileWatchMatching("bob"),
1653 )
1654 })
1655 }
1656
1657 // Confirms that circular imports are tested and reported.
1658 func TestCircularImports(t *testing.T) {
1659 const mod = `
1660 -- go.mod --
1661 module mod.com
1662
1663 go 1.12
1664 -- self/self.go --
1665 package self
1666
1667 import _ "mod.com/self"
1668 func Hello() {}
1669 -- double/a/a.go --
1670 package a
1671
1672 import _ "mod.com/double/b"
1673 -- double/b/b.go --
1674 package b
1675
1676 import _ "mod.com/double/a"
1677 -- triple/a/a.go --
1678 package a
1679
1680 import _ "mod.com/triple/b"
1681 -- triple/b/b.go --
1682 package b
1683
1684 import _ "mod.com/triple/c"
1685 -- triple/c/c.go --
1686 package c
1687
1688 import _ "mod.com/triple/a"
1689 `
1690 Run(t, mod, func(t *testing.T, env *Env) {
1691 env.OnceMet(
1692 InitialWorkspaceLoad,
1693 Diagnostics(env.AtRegexp("self/self.go", `_ "mod.com/self"`), WithMessage("import cycle not allowed")),
1694 Diagnostics(env.AtRegexp("double/a/a.go", `_ "mod.com/double/b"`), WithMessage("import cycle not allowed")),
1695 Diagnostics(env.AtRegexp("triple/a/a.go", `_ "mod.com/triple/b"`), WithMessage("import cycle not allowed")),
1696 )
1697 })
1698 }
1699
1700 // Tests golang/go#46667: deleting a problematic import path should resolve
1701 // import cycle errors.
1702 func TestResolveImportCycle(t *testing.T) {
1703 const mod = `
1704 -- go.mod --
1705 module mod.test
1706
1707 go 1.16
1708 -- a/a.go --
1709 package a
1710
1711 import "mod.test/b"
1712
1713 const A = b.A
1714 const B = 2
1715 -- b/b.go --
1716 package b
1717
1718 import "mod.test/a"
1719
1720 const A = 1
1721 const B = a.B
1722 `
1723 Run(t, mod, func(t *testing.T, env *Env) {
1724 env.OpenFile("a/a.go")
1725 env.OpenFile("b/b.go")
1726 env.AfterChange(
1727 // The Go command sometimes tells us about only one of the import cycle
1728 // errors below. Also, sometimes we get an error during type checking
1729 // instead of during list, due to missing metadata. This is likely due to
1730 // a race.
1731 // For robustness of this test, succeed if we get any reasonable error.
1732 //
1733 // TODO(golang/go#52904): we should get *both* of these errors.
1734 // TODO(golang/go#64899): we should always get an import cycle error
1735 // rather than a missing metadata error.
1736 AnyOf(
1737 Diagnostics(env.AtRegexp("a/a.go", `"mod.test/b"`)),
1738 Diagnostics(env.AtRegexp("b/b.go", `"mod.test/a"`)),
1739 ),
1740 )
1741 env.RegexpReplace("b/b.go", `const B = a\.B`, "")
1742 env.SaveBuffer("b/b.go")
1743 env.AfterChange(
1744 NoDiagnostics(ForFile("a/a.go")),
1745 NoDiagnostics(ForFile("b/b.go")),
1746 )
1747 })
1748 }
1749
1750 func TestBadImport(t *testing.T) {
1751 const mod = `
1752 -- go.mod --
1753 module mod.com
1754
1755 go 1.12
1756 -- main.go --
1757 package main
1758
1759 import (
1760 _ "nosuchpkg"
1761 )
1762 `
1763 t.Run("module", func(t *testing.T) {
1764 Run(t, mod, func(t *testing.T, env *Env) {
1765 env.OnceMet(
1766 InitialWorkspaceLoad,
1767 Diagnostics(env.AtRegexp("main.go", `"nosuchpkg"`), WithMessage(`could not import nosuchpkg (no required module provides package "nosuchpkg"`)),
1768 )
1769 })
1770 })
1771 t.Run("GOPATH", func(t *testing.T) {
1772 WithOptions(
1773 InGOPATH(),
1774 EnvVars{"GO111MODULE": "off"},
1775 Modes(Default),
1776 ).Run(t, mod, func(t *testing.T, env *Env) {
1777 env.OnceMet(
1778 InitialWorkspaceLoad,
1779 Diagnostics(env.AtRegexp("main.go", `"nosuchpkg"`), WithMessage(`cannot find package "nosuchpkg"`)),
1780 )
1781 })
1782 })
1783 }
1784
1785 func TestNestedModules(t *testing.T) {
1786 const proxy = `
1787 -- [email protected]/go.mod --
1788 module nested.com
1789
1790 go 1.12
1791 -- [email protected]/hello/hello.go --
1792 package hello
1793
1794 func Hello() {}
1795 `
1796
1797 const nested = `
1798 -- go.mod --
1799 module mod.com
1800
1801 go 1.12
1802
1803 require nested.com v1.0.0
1804 -- main.go --
1805 package main
1806
1807 import "nested.com/hello"
1808
1809 func main() {
1810 hello.Hello()
1811 }
1812 -- nested/go.mod --
1813 module nested.com
1814
1815 -- nested/hello/hello.go --
1816 package hello
1817
1818 func Hello() {
1819 helloHelper()
1820 }
1821 -- nested/hello/hello_helper.go --
1822 package hello
1823
1824 func helloHelper() {}
1825 `
1826 WithOptions(
1827 WriteGoSum("."),
1828 ProxyFiles(proxy),
1829 Modes(Default),
1830 ).Run(t, nested, func(t *testing.T, env *Env) {
1831 // Expect a diagnostic in a nested module.
1832 env.OpenFile("nested/hello/hello.go")
1833 env.AfterChange(
1834 NoDiagnostics(ForFile("nested/hello/hello.go")),
1835 )
1836 loc := env.FirstDefinition(env.RegexpSearch("nested/hello/hello.go", "helloHelper"))
1837 want := "nested/hello/hello_helper.go"
1838 if got := env.Sandbox.Workdir.URIToPath(loc.URI); got != want {
1839 t.Errorf("Definition() returned %q, want %q", got, want)
1840 }
1841 })
1842 }
1843
1844 func TestAdHocPackagesReloading(t *testing.T) {
1845 const nomod = `
1846 -- main.go --
1847 package main
1848
1849 func main() {}
1850 `
1851 Run(t, nomod, func(t *testing.T, env *Env) {
1852 env.OpenFile("main.go")
1853 env.RegexpReplace("main.go", "{}", "{ var x int; }") // simulate typing
1854 env.AfterChange(NoLogMatching(protocol.Info, "packages=1"))
1855 })
1856 }
1857
1858 func TestBuildTagChange(t *testing.T) {
1859 const files = `
1860 -- go.mod --
1861 module mod.com
1862
1863 go 1.12
1864 -- foo.go --
1865 // decoy comment
1866 // +build hidden
1867 // decoy comment
1868
1869 package foo
1870 var Foo = 1
1871 -- bar.go --
1872 package foo
1873 var Bar = Foo
1874 `
1875
1876 Run(t, files, func(t *testing.T, env *Env) {
1877 env.OpenFile("foo.go")
1878 env.AfterChange(Diagnostics(env.AtRegexp("bar.go", `Foo`)))
1879 env.RegexpReplace("foo.go", `\+build`, "")
1880 env.AfterChange(NoDiagnostics(ForFile("bar.go")))
1881 })
1882
1883 }
1884
1885 func TestIssue44736(t *testing.T) {
1886 const files = `
1887 -- go.mod --
1888 module blah.com
1889
1890 go 1.16
1891 -- main.go --
1892 package main
1893
1894 import "fmt"
1895
1896 func main() {
1897 asdf
1898 fmt.Printf("This is a test %v")
1899 fdas
1900 }
1901 -- other.go --
1902 package main
1903
1904 `
1905 Run(t, files, func(t *testing.T, env *Env) {
1906 env.OpenFile("main.go")
1907 env.OpenFile("other.go")
1908 env.AfterChange(
1909 Diagnostics(env.AtRegexp("main.go", "asdf")),
1910 Diagnostics(env.AtRegexp("main.go", "fdas")),
1911 )
1912 env.SetBufferContent("other.go", "package main\n\nasdf")
1913 // The new diagnostic in other.go should not suppress diagnostics in main.go.
1914 env.AfterChange(
1915 Diagnostics(env.AtRegexp("other.go", "asdf"), WithMessage("expected declaration")),
1916 Diagnostics(env.AtRegexp("main.go", "asdf")),
1917 )
1918 })
1919 }
1920
1921 func TestInitialization(t *testing.T) {
1922 const files = `
1923 -- go.mod --
1924 module mod.com
1925
1926 go 1.16
1927 -- main.go --
1928 package main
1929 `
1930 Run(t, files, func(t *testing.T, env *Env) {
1931 env.OpenFile("go.mod")
1932 env.Await(env.DoneWithOpen())
1933 env.RegexpReplace("go.mod", "module", "modul")
1934 env.SaveBufferWithoutActions("go.mod")
1935 env.AfterChange(
1936 NoLogMatching(protocol.Error, "initial workspace load failed"),
1937 )
1938 })
1939 }
1940
1941 // This test confirms that the view does not reinitialize when a go.mod file is
1942 // opened.
1943 func TestNoReinitialize(t *testing.T) {
1944 const files = `
1945 -- go.mod --
1946 module mod.com
1947
1948 go 1.12
1949 -- main.go --
1950 package main
1951
1952 func main() {}
1953 `
1954 Run(t, files, func(t *testing.T, env *Env) {
1955 env.OpenFile("go.mod")
1956 env.Await(
1957 // Check that we have only loaded "<dir>/..." once.
1958 // Log messages are asynchronous to other events on the LSP stream, so we
1959 // can't use OnceMet or AfterChange here.
1960 LogMatching(protocol.Info, `.*query=.*\.\.\..*`, 1, false),
1961 )
1962 })
1963 }
1964
1965 func TestLangVersion(t *testing.T) {
1966 const files = `
1967 -- go.mod --
1968 module mod.com
1969
1970 go 1.12
1971 -- main.go --
1972 package main
1973
1974 const C = 0b10
1975 `
1976 Run(t, files, func(t *testing.T, env *Env) {
1977 env.OnceMet(
1978 InitialWorkspaceLoad,
1979 Diagnostics(env.AtRegexp("main.go", `0b10`), WithMessage("go1.13 or later")),
1980 )
1981 env.WriteWorkspaceFile("go.mod", "module mod.com \n\ngo 1.13\n")
1982 env.AfterChange(
1983 NoDiagnostics(ForFile("main.go")),
1984 )
1985 })
1986 }
1987
1988 func TestNoQuickFixForUndeclaredConstraint(t *testing.T) {
1989 const files = `
1990 -- go.mod --
1991 module mod.com
1992
1993 go 1.18
1994 -- main.go --
1995 package main
1996
1997 func F[T C](_ T) {
1998 }
1999 `
2000
2001 Run(t, files, func(t *testing.T, env *Env) {
2002 var d protocol.PublishDiagnosticsParams
2003 env.OnceMet(
2004 InitialWorkspaceLoad,
2005 Diagnostics(env.AtRegexp("main.go", `C`)),
2006 ReadDiagnostics("main.go", &d),
2007 )
2008 if fixes := env.GetQuickFixes("main.go", d.Diagnostics); len(fixes) != 0 {
2009 t.Errorf("got quick fixes %v, wanted none", fixes)
2010 }
2011 })
2012 }
2013
2014 func TestEditGoDirective(t *testing.T) {
2015 const files = `
2016 -- go.mod --
2017 module mod.com
2018
2019 go 1.16
2020 -- main.go --
2021 package main
2022
2023 func F[T any](_ T) {
2024 }
2025 `
2026 Run(t, files, func(_ *testing.T, env *Env) { // Create a new workspace-level directory and empty file.
2027 var d protocol.PublishDiagnosticsParams
2028 env.OnceMet(
2029 InitialWorkspaceLoad,
2030 Diagnostics(env.AtRegexp("main.go", `T any`), WithMessage("type parameter")),
2031 ReadDiagnostics("main.go", &d),
2032 )
2033
2034 env.ApplyQuickFixes("main.go", d.Diagnostics)
2035 env.AfterChange(
2036 NoDiagnostics(ForFile("main.go")),
2037 )
2038 })
2039 }
2040
2041 func TestEditGoDirectiveWorkspace(t *testing.T) {
2042 const files = `
2043 -- go.mod --
2044 module mod.com
2045
2046 go 1.16
2047 -- go.work --
2048 go 1.18
2049
2050 use .
2051 -- main.go --
2052 package main
2053
2054 func F[T any](_ T) {
2055 }
2056 `
2057 Run(t, files, func(_ *testing.T, env *Env) { // Create a new workspace-level directory and empty file.
2058 var d protocol.PublishDiagnosticsParams
2059
2060 // We should have a diagnostic because generics are not supported at 1.16.
2061 env.OnceMet(
2062 InitialWorkspaceLoad,
2063 Diagnostics(env.AtRegexp("main.go", `T any`), WithMessage("type parameter")),
2064 ReadDiagnostics("main.go", &d),
2065 )
2066
2067 // This diagnostic should have a quick fix to edit the go version.
2068 env.ApplyQuickFixes("main.go", d.Diagnostics)
2069
2070 // Once the edit is applied, the problematic diagnostics should be
2071 // resolved.
2072 env.AfterChange(
2073 NoDiagnostics(ForFile("main.go")),
2074 )
2075 })
2076 }
2077
2078 // This test demonstrates that analysis facts are correctly propagated
2079 // across packages.
2080 func TestInterpackageAnalysis(t *testing.T) {
2081 const src = `
2082 -- go.mod --
2083 module example.com
2084 -- a/a.go --
2085 package a
2086
2087 import "example.com/b"
2088
2089 func _() {
2090 new(b.B).Printf("%d", "s") // printf error
2091 }
2092
2093 -- b/b.go --
2094 package b
2095
2096 import "example.com/c"
2097
2098 type B struct{}
2099
2100 func (B) Printf(format string, args ...interface{}) {
2101 c.MyPrintf(format, args...)
2102 }
2103
2104 -- c/c.go --
2105 package c
2106
2107 import "fmt"
2108
2109 func MyPrintf(format string, args ...interface{}) {
2110 fmt.Printf(format, args...)
2111 }
2112 `
2113 Run(t, src, func(t *testing.T, env *Env) {
2114 env.OpenFile("a/a.go")
2115 env.AfterChange(
2116 Diagnostics(
2117 env.AtRegexp("a/a.go", "%d"),
2118 WithMessage("format %d has arg \"s\" of wrong type string"),
2119 ),
2120 )
2121 })
2122 }
2123
2124 // This test ensures that only Analyzers with RunDespiteErrors=true
2125 // are invoked on a package that would not compile, even if the errors
2126 // are distant and localized.
2127 func TestErrorsThatPreventAnalysis(t *testing.T) {
2128 const src = `
2129 -- go.mod --
2130 module example.com
2131 -- a/a.go --
2132 package a
2133
2134 import "fmt"
2135 import "sync"
2136 import _ "example.com/b"
2137
2138 func _() {
2139 // The copylocks analyzer (RunDespiteErrors, FactTypes={}) does run.
2140 var mu sync.Mutex
2141 mu2 := mu // copylocks error, reported
2142 _ = &mu2
2143
2144 // The printf analyzer (!RunDespiteErrors, FactTypes!={}) does not run:
2145 // (c, printf) failed because of type error in c
2146 // (b, printf) and (a, printf) do not run because of failed prerequisites.
2147 fmt.Printf("%d", "s") // printf error, unreported
2148
2149 // The bools analyzer (!RunDespiteErrors, FactTypes={}) does not run:
2150 var cond bool
2151 _ = cond != true && cond != true // bools error, unreported
2152 }
2153
2154 -- b/b.go --
2155 package b
2156
2157 import _ "example.com/c"
2158
2159 -- c/c.go --
2160 package c
2161
2162 var _ = 1 / "" // type error
2163
2164 `
2165 Run(t, src, func(t *testing.T, env *Env) {
2166 var diags protocol.PublishDiagnosticsParams
2167 env.OpenFile("a/a.go")
2168 env.AfterChange(
2169 Diagnostics(env.AtRegexp("a/a.go", "mu2 := (mu)"), WithMessage("assignment copies lock value")),
2170 ReadDiagnostics("a/a.go", &diags))
2171
2172 // Assert that there were no other diagnostics.
2173 // In particular:
2174 // - "fmt.Printf" does not trigger a [printf] finding;
2175 // - "cond != true" does not trigger a [bools] finding.
2176 //
2177 // We use this check in preference to NoDiagnosticAtRegexp
2178 // as it is robust in case of minor mistakes in the position
2179 // regexp, and because it reports unexpected diagnostics.
2180 if got, want := len(diags.Diagnostics), 1; got != want {
2181 t.Errorf("got %d diagnostics in a/a.go, want %d:", got, want)
2182 for i, diag := range diags.Diagnostics {
2183 t.Logf("Diagnostics[%d] = %+v", i, diag)
2184 }
2185 }
2186 })
2187 }
2188
2189 // This test demonstrates the deprecated symbol analyzer
2190 // produces deprecation notices with expected severity and tags.
2191 func TestDeprecatedAnalysis(t *testing.T) {
2192 const src = `
2193 -- go.mod --
2194 module example.com
2195 -- a/a.go --
2196 package a
2197
2198 import "example.com/b"
2199
2200 func _() {
2201 new(b.B).Obsolete() // deprecated
2202 }
2203
2204 -- b/b.go --
2205 package b
2206
2207 type B struct{}
2208
2209 // Deprecated: use New instead.
2210 func (B) Obsolete() {}
2211
2212 func (B) New() {}
2213 `
2214 Run(t, src, func(t *testing.T, env *Env) {
2215 env.OpenFile("a/a.go")
2216 env.AfterChange(
2217 Diagnostics(
2218 env.AtRegexp("a/a.go", "new.*Obsolete"),
2219 WithMessage("use New instead."),
2220 WithSeverityTags("deprecated", protocol.SeverityHint, []protocol.DiagnosticTag{protocol.Deprecated}),
2221 ),
2222 )
2223 })
2224 }
2225
2226 func TestDiagnosticsOnlyOnSaveFile(t *testing.T) {
2227 // This functionality is broken because the new orphaned file diagnostics
2228 // logic wants to publish diagnostics for changed files, independent of any
2229 // snapshot diagnostics pass, and this causes stale diagnostics to be
2230 // invalidated.
2231 //
2232 // We can fix this behavior more correctly by also honoring the
2233 // diagnosticsTrigger in DiagnoseOrphanedFiles, but that would require
2234 // resolving configuration that is independent of the snapshot. In other
2235 // words, we need to figure out which cache.Folder.Options applies to the
2236 // changed file, even if it does not have a snapshot.
2237 t.Skip("temporary skip for golang/go#57979: revisit after zero-config logic is in place")
2238
2239 const onlyMod = `
2240 -- go.mod --
2241 module mod.com
2242
2243 go 1.12
2244 -- main.go --
2245 package main
2246
2247 func main() {
2248 Foo()
2249 }
2250 -- foo.go --
2251 package main
2252
2253 func Foo() {}
2254 `
2255 WithOptions(
2256 Settings{
2257 "diagnosticsTrigger": "Save",
2258 },
2259 ).Run(t, onlyMod, func(t *testing.T, env *Env) {
2260 env.OpenFile("foo.go")
2261 env.RegexpReplace("foo.go", "(Foo)", "Bar") // Makes reference to Foo undefined/undeclared.
2262 env.AfterChange(NoDiagnostics()) // No diagnostics update until file save.
2263
2264 env.SaveBuffer("foo.go")
2265 // Compiler's error message about undeclared names vary depending on the version,
2266 // but must be explicit about the problematic name.
2267 env.AfterChange(Diagnostics(env.AtRegexp("main.go", "Foo"), WithMessage("Foo")))
2268
2269 env.OpenFile("main.go")
2270 env.RegexpReplace("main.go", "(Foo)", "Bar")
2271 // No diagnostics update until file save. That results in outdated diagnostic.
2272 env.AfterChange(Diagnostics(env.AtRegexp("main.go", "Bar"), WithMessage("Foo")))
2273
2274 env.SaveBuffer("main.go")
2275 env.AfterChange(NoDiagnostics())
2276 })
2277 }