1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
|
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package workspace
import (
"context"
"fmt"
"path/filepath"
"strings"
"testing"
"golang.org/x/tools/gopls/internal/hooks"
"golang.org/x/tools/gopls/internal/lsp"
"golang.org/x/tools/gopls/internal/lsp/fake"
"golang.org/x/tools/gopls/internal/lsp/protocol"
"golang.org/x/tools/internal/bug"
"golang.org/x/tools/internal/gocommand"
"golang.org/x/tools/internal/testenv"
. "golang.org/x/tools/gopls/internal/lsp/regtest"
)
func TestMain(m *testing.M) {
bug.PanicOnBugs = true
Main(m, hooks.Options)
}
const workspaceProxy = `
-- example.com@v1.2.3/go.mod --
module example.com
go 1.12
-- example.com@v1.2.3/blah/blah.go --
package blah
import "fmt"
func SaySomething() {
fmt.Println("something")
}
-- random.org@v1.2.3/go.mod --
module random.org
go 1.12
-- random.org@v1.2.3/bye/bye.go --
package bye
func Goodbye() {
println("Bye")
}
`
// TODO: Add a replace directive.
const workspaceModule = `
-- pkg/go.mod --
module mod.com
go 1.14
require (
example.com v1.2.3
random.org v1.2.3
)
-- pkg/go.sum --
example.com v1.2.3 h1:veRD4tUnatQRgsULqULZPjeoBGFr2qBhevSCZllD2Ds=
example.com v1.2.3/go.mod h1:Y2Rc5rVWjWur0h3pd9aEvK5Pof8YKDANh9gHA2Maujo=
random.org v1.2.3 h1:+JE2Fkp7gS0zsHXGEQJ7hraom3pNTlkxC4b2qPfA+/Q=
random.org v1.2.3/go.mod h1:E9KM6+bBX2g5ykHZ9H27w16sWo3QwgonyjM44Dnej3I=
-- pkg/main.go --
package main
import (
"example.com/blah"
"mod.com/inner"
"random.org/bye"
)
func main() {
blah.SaySomething()
inner.Hi()
bye.Goodbye()
}
-- pkg/main2.go --
package main
import "fmt"
func _() {
fmt.Print("%s")
}
-- pkg/inner/inner.go --
package inner
import "example.com/blah"
func Hi() {
blah.SaySomething()
}
-- goodbye/bye/bye.go --
package bye
func Bye() {}
-- goodbye/go.mod --
module random.org
go 1.12
`
// Confirm that find references returns all of the references in the module,
// regardless of what the workspace root is.
func TestReferences(t *testing.T) {
for _, tt := range []struct {
name, rootPath string
}{
{
name: "module root",
rootPath: "pkg",
},
{
name: "subdirectory",
rootPath: "pkg/inner",
},
} {
t.Run(tt.name, func(t *testing.T) {
opts := []RunOption{ProxyFiles(workspaceProxy)}
if tt.rootPath != "" {
opts = append(opts, WorkspaceFolders(tt.rootPath))
}
WithOptions(opts...).Run(t, workspaceModule, func(t *testing.T, env *Env) {
f := "pkg/inner/inner.go"
env.OpenFile(f)
locations := env.References(f, env.RegexpSearch(f, `SaySomething`))
want := 3
if got := len(locations); got != want {
t.Fatalf("expected %v locations, got %v", want, got)
}
})
})
}
}
// Make sure that analysis diagnostics are cleared for the whole package when
// the only opened file is closed. This test was inspired by the experience in
// VS Code, where clicking on a reference result triggers a
// textDocument/didOpen without a corresponding textDocument/didClose.
func TestClearAnalysisDiagnostics(t *testing.T) {
WithOptions(
ProxyFiles(workspaceProxy),
WorkspaceFolders("pkg/inner"),
).Run(t, workspaceModule, func(t *testing.T, env *Env) {
env.OpenFile("pkg/main.go")
env.Await(
env.DiagnosticAtRegexp("pkg/main2.go", "fmt.Print"),
)
env.CloseBuffer("pkg/main.go")
env.Await(
EmptyDiagnostics("pkg/main2.go"),
)
})
}
// TestReloadOnlyOnce checks that changes to the go.mod file do not result in
// redundant package loads (golang/go#54473).
//
// Note that this test may be fragile, as it depends on specific structure to
// log messages around reinitialization. Nevertheless, it is important for
// guarding against accidentally duplicate reloading.
func TestReloadOnlyOnce(t *testing.T) {
WithOptions(
ProxyFiles(workspaceProxy),
WorkspaceFolders("pkg"),
).Run(t, workspaceModule, func(t *testing.T, env *Env) {
dir := env.Sandbox.Workdir.URI("goodbye").SpanURI().Filename()
goModWithReplace := fmt.Sprintf(`%s
replace random.org => %s
`, env.ReadWorkspaceFile("pkg/go.mod"), dir)
env.WriteWorkspaceFile("pkg/go.mod", goModWithReplace)
env.Await(
OnceMet(
env.DoneWithChangeWatchedFiles(),
LogMatching(protocol.Info, `packages\.Load #\d+\n`, 2, false),
),
)
})
}
// This test checks that gopls updates the set of files it watches when a
// replace target is added to the go.mod.
func TestWatchReplaceTargets(t *testing.T) {
t.Skipf("skipping known-flaky test: see https://go.dev/issue/50748")
WithOptions(
ProxyFiles(workspaceProxy),
WorkspaceFolders("pkg"),
).Run(t, workspaceModule, func(t *testing.T, env *Env) {
// Add a replace directive and expect the files that gopls is watching
// to change.
dir := env.Sandbox.Workdir.URI("goodbye").SpanURI().Filename()
goModWithReplace := fmt.Sprintf(`%s
replace random.org => %s
`, env.ReadWorkspaceFile("pkg/go.mod"), dir)
env.WriteWorkspaceFile("pkg/go.mod", goModWithReplace)
env.Await(
env.DoneWithChangeWatchedFiles(),
UnregistrationMatching("didChangeWatchedFiles"),
RegistrationMatching("didChangeWatchedFiles"),
)
})
}
const workspaceModuleProxy = `
-- example.com@v1.2.3/go.mod --
module example.com
go 1.12
-- example.com@v1.2.3/blah/blah.go --
package blah
import "fmt"
func SaySomething() {
fmt.Println("something")
}
-- b.com@v1.2.3/go.mod --
module b.com
go 1.12
-- b.com@v1.2.3/b/b.go --
package b
func Hello() {}
`
func TestAutomaticWorkspaceModule_Interdependent(t *testing.T) {
testenv.NeedsGo1Point(t, 18) // uses go.work
const multiModule = `
-- moda/a/go.mod --
module a.com
require b.com v1.2.3
-- moda/a/go.sum --
b.com v1.2.3 h1:tXrlXP0rnjRpKNmkbLYoWBdq0ikb3C3bKK9//moAWBI=
b.com v1.2.3/go.mod h1:D+J7pfFBZK5vdIdZEFquR586vKKIkqG7Qjw9AxG5BQ8=
-- moda/a/a.go --
package a
import (
"b.com/b"
)
func main() {
var x int
_ = b.Hello()
}
-- modb/go.mod --
module b.com
-- modb/b/b.go --
package b
func Hello() int {
var x int
}
`
WithOptions(
ProxyFiles(workspaceModuleProxy),
).Run(t, multiModule, func(t *testing.T, env *Env) {
env.RunGoCommand("work", "init")
env.RunGoCommand("work", "use", "-r", ".")
env.AfterChange(
env.DiagnosticAtRegexp("moda/a/a.go", "x"),
env.DiagnosticAtRegexp("modb/b/b.go", "x"),
env.NoDiagnosticAtRegexp("moda/a/a.go", `"b.com/b"`),
)
})
}
func TestModuleWithExclude(t *testing.T) {
const proxy = `
-- c.com@v1.2.3/go.mod --
module c.com
go 1.12
require b.com v1.2.3
-- c.com@v1.2.3/blah/blah.go --
package blah
import "fmt"
func SaySomething() {
fmt.Println("something")
}
-- b.com@v1.2.3/go.mod --
module b.com
go 1.12
-- b.com@v1.2.4/b/b.go --
package b
func Hello() {}
-- b.com@v1.2.4/go.mod --
module b.com
go 1.12
`
const multiModule = `
-- go.mod --
module a.com
require c.com v1.2.3
exclude b.com v1.2.3
-- go.sum --
c.com v1.2.3 h1:n07Dz9fYmpNqvZMwZi5NEqFcSHbvLa9lacMX+/g25tw=
c.com v1.2.3/go.mod h1:/4TyYgU9Nu5tA4NymP5xyqE8R2VMzGD3TbJCwCOvHAg=
-- main.go --
package a
func main() {
var x int
}
`
WithOptions(
ProxyFiles(proxy),
).Run(t, multiModule, func(t *testing.T, env *Env) {
env.Await(
env.DiagnosticAtRegexp("main.go", "x"),
)
})
}
// This change tests that the version of the module used changes after it has
// been deleted from the workspace.
//
// TODO(golang/go#55331): delete this placeholder along with experimental
// workspace module.
func TestDeleteModule_Interdependent(t *testing.T) {
testenv.NeedsGo1Point(t, 18) // uses go.work
const multiModule = `
-- go.work --
go 1.18
use (
moda/a
modb
)
-- moda/a/go.mod --
module a.com
require b.com v1.2.3
-- moda/a/go.sum --
b.com v1.2.3 h1:tXrlXP0rnjRpKNmkbLYoWBdq0ikb3C3bKK9//moAWBI=
b.com v1.2.3/go.mod h1:D+J7pfFBZK5vdIdZEFquR586vKKIkqG7Qjw9AxG5BQ8=
-- moda/a/a.go --
package a
import (
"b.com/b"
)
func main() {
var x int
_ = b.Hello()
}
-- modb/go.mod --
module b.com
-- modb/b/b.go --
package b
func Hello() int {
var x int
}
`
WithOptions(
ProxyFiles(workspaceModuleProxy),
).Run(t, multiModule, func(t *testing.T, env *Env) {
env.OpenFile("moda/a/a.go")
env.Await(env.DoneWithOpen())
original, _ := env.GoToDefinition("moda/a/a.go", env.RegexpSearch("moda/a/a.go", "Hello"))
if want := "modb/b/b.go"; !strings.HasSuffix(original, want) {
t.Errorf("expected %s, got %v", want, original)
}
env.CloseBuffer(original)
env.AfterChange()
env.RemoveWorkspaceFile("modb/b/b.go")
env.RemoveWorkspaceFile("modb/go.mod")
env.WriteWorkspaceFile("go.work", "go 1.18\nuse moda/a")
env.AfterChange()
got, _ := env.GoToDefinition("moda/a/a.go", env.RegexpSearch("moda/a/a.go", "Hello"))
if want := "b.com@v1.2.3/b/b.go"; !strings.HasSuffix(got, want) {
t.Errorf("expected %s, got %v", want, got)
}
})
}
// Tests that the version of the module used changes after it has been added
// to the workspace.
func TestCreateModule_Interdependent(t *testing.T) {
testenv.NeedsGo1Point(t, 18) // uses go.work
const multiModule = `
-- go.work --
go 1.18
use (
moda/a
)
-- moda/a/go.mod --
module a.com
require b.com v1.2.3
-- moda/a/go.sum --
b.com v1.2.3 h1:tXrlXP0rnjRpKNmkbLYoWBdq0ikb3C3bKK9//moAWBI=
b.com v1.2.3/go.mod h1:D+J7pfFBZK5vdIdZEFquR586vKKIkqG7Qjw9AxG5BQ8=
-- moda/a/a.go --
package a
import (
"b.com/b"
)
func main() {
var x int
_ = b.Hello()
}
`
WithOptions(
ProxyFiles(workspaceModuleProxy),
).Run(t, multiModule, func(t *testing.T, env *Env) {
env.OpenFile("moda/a/a.go")
original, _ := env.GoToDefinition("moda/a/a.go", env.RegexpSearch("moda/a/a.go", "Hello"))
if want := "b.com@v1.2.3/b/b.go"; !strings.HasSuffix(original, want) {
t.Errorf("expected %s, got %v", want, original)
}
env.CloseBuffer(original)
env.WriteWorkspaceFiles(map[string]string{
"go.work": `go 1.18
use (
moda/a
modb
)
`,
"modb/go.mod": "module b.com",
"modb/b/b.go": `package b
func Hello() int {
var x int
}
`,
})
env.AfterChange(env.DiagnosticAtRegexp("modb/b/b.go", "x"))
got, _ := env.GoToDefinition("moda/a/a.go", env.RegexpSearch("moda/a/a.go", "Hello"))
if want := "modb/b/b.go"; !strings.HasSuffix(got, want) {
t.Errorf("expected %s, got %v", want, original)
}
})
}
// This test confirms that a gopls workspace can recover from initialization
// with one invalid module.
func TestOneBrokenModule(t *testing.T) {
t.Skip("golang/go#55331: this test is temporarily broken as go.work handling tries to build the workspace module")
testenv.NeedsGo1Point(t, 18) // uses go.work
const multiModule = `
-- go.work --
go 1.18
use (
moda/a
modb
)
-- moda/a/go.mod --
module a.com
require b.com v1.2.3
-- moda/a/a.go --
package a
import (
"b.com/b"
)
func main() {
var x int
_ = b.Hello()
}
-- modb/go.mod --
modul b.com // typo here
-- modb/b/b.go --
package b
func Hello() int {
var x int
}
`
WithOptions(
ProxyFiles(workspaceModuleProxy),
).Run(t, multiModule, func(t *testing.T, env *Env) {
env.OpenFile("modb/go.mod")
env.Await(
OnceMet(
env.DoneWithOpen(),
DiagnosticAt("modb/go.mod", 0, 0),
),
)
env.RegexpReplace("modb/go.mod", "modul", "module")
env.SaveBufferWithoutActions("modb/go.mod")
env.Await(
env.DiagnosticAtRegexp("modb/b/b.go", "x"),
)
})
}
func TestUseGoplsMod(t *testing.T) {
// This test validates certain functionality related to using a gopls.mod
// file to specify workspace modules.
const multiModule = `
-- moda/a/go.mod --
module a.com
require b.com v1.2.3
-- moda/a/go.sum --
b.com v1.2.3 h1:tXrlXP0rnjRpKNmkbLYoWBdq0ikb3C3bKK9//moAWBI=
b.com v1.2.3/go.mod h1:D+J7pfFBZK5vdIdZEFquR586vKKIkqG7Qjw9AxG5BQ8=
-- moda/a/a.go --
package a
import (
"b.com/b"
)
func main() {
var x int
_ = b.Hello()
}
-- modb/go.mod --
module b.com
require example.com v1.2.3
-- modb/go.sum --
example.com v1.2.3 h1:veRD4tUnatQRgsULqULZPjeoBGFr2qBhevSCZllD2Ds=
example.com v1.2.3/go.mod h1:Y2Rc5rVWjWur0h3pd9aEvK5Pof8YKDANh9gHA2Maujo=
-- modb/b/b.go --
package b
func Hello() int {
var x int
}
-- gopls.mod --
module gopls-workspace
require (
a.com v0.0.0-goplsworkspace
b.com v1.2.3
)
replace a.com => $SANDBOX_WORKDIR/moda/a
`
WithOptions(
ProxyFiles(workspaceModuleProxy),
Modes(Experimental),
).Run(t, multiModule, func(t *testing.T, env *Env) {
// Initially, the gopls.mod should cause only the a.com module to be
// loaded. Validate this by jumping to a definition in b.com and ensuring
// that we go to the module cache.
env.OpenFile("moda/a/a.go")
env.Await(env.DoneWithOpen())
// To verify which modules are loaded, we'll jump to the definition of
// b.Hello.
checkHelloLocation := func(want string) error {
location, _ := env.GoToDefinition("moda/a/a.go", env.RegexpSearch("moda/a/a.go", "Hello"))
if !strings.HasSuffix(location, want) {
return fmt.Errorf("expected %s, got %v", want, location)
}
return nil
}
// Initially this should be in the module cache, as b.com is not replaced.
if err := checkHelloLocation("b.com@v1.2.3/b/b.go"); err != nil {
t.Fatal(err)
}
// Now, modify the gopls.mod file on disk to activate the b.com module in
// the workspace.
workdir := env.Sandbox.Workdir.RootURI().SpanURI().Filename()
env.WriteWorkspaceFile("gopls.mod", fmt.Sprintf(`module gopls-workspace
require (
a.com v1.9999999.0-goplsworkspace
b.com v1.9999999.0-goplsworkspace
)
replace a.com => %s/moda/a
replace b.com => %s/modb
`, workdir, workdir))
// As of golang/go#54069, writing a gopls.mod to the workspace triggers a
// workspace reload.
env.Await(
OnceMet(
env.DoneWithChangeWatchedFiles(),
env.DiagnosticAtRegexp("modb/b/b.go", "x"),
),
)
// Jumping to definition should now go to b.com in the workspace.
if err := checkHelloLocation("modb/b/b.go"); err != nil {
t.Fatal(err)
}
// Now, let's modify the gopls.mod *overlay* (not on disk), and verify that
// this change is only picked up once it is saved.
env.OpenFile("gopls.mod")
env.Await(env.DoneWithOpen())
env.SetBufferContent("gopls.mod", fmt.Sprintf(`module gopls-workspace
require (
a.com v0.0.0-goplsworkspace
)
replace a.com => %s/moda/a
`, workdir))
// Editing the gopls.mod removes modb from the workspace modules, and so
// should clear outstanding diagnostics...
env.Await(OnceMet(
env.DoneWithChange(),
EmptyDiagnostics("modb/go.mod"),
))
// ...but does not yet cause a workspace reload, so we should still jump to modb.
if err := checkHelloLocation("modb/b/b.go"); err != nil {
t.Fatal(err)
}
// Saving should reload the workspace.
env.SaveBufferWithoutActions("gopls.mod")
if err := checkHelloLocation("b.com@v1.2.3/b/b.go"); err != nil {
t.Fatal(err)
}
})
}
// TestBadGoWork exercises the panic from golang/vscode-go#2121.
func TestBadGoWork(t *testing.T) {
const files = `
-- go.work --
use ./bar
-- bar/go.mod --
module example.com/bar
`
Run(t, files, func(t *testing.T, env *Env) {
env.OpenFile("go.work")
})
}
func TestUseGoWork(t *testing.T) {
// This test validates certain functionality related to using a go.work
// file to specify workspace modules.
const multiModule = `
-- moda/a/go.mod --
module a.com
require b.com v1.2.3
-- moda/a/go.sum --
b.com v1.2.3 h1:tXrlXP0rnjRpKNmkbLYoWBdq0ikb3C3bKK9//moAWBI=
b.com v1.2.3/go.mod h1:D+J7pfFBZK5vdIdZEFquR586vKKIkqG7Qjw9AxG5BQ8=
-- moda/a/a.go --
package a
import (
"b.com/b"
)
func main() {
var x int
_ = b.Hello()
}
-- modb/go.mod --
module b.com
require example.com v1.2.3
-- modb/go.sum --
example.com v1.2.3 h1:Yryq11hF02fEf2JlOS2eph+ICE2/ceevGV3C9dl5V/c=
example.com v1.2.3/go.mod h1:Y2Rc5rVWjWur0h3pd9aEvK5Pof8YKDANh9gHA2Maujo=
-- modb/b/b.go --
package b
func Hello() int {
var x int
}
-- go.work --
go 1.17
use (
./moda/a
)
`
WithOptions(
ProxyFiles(workspaceModuleProxy),
).Run(t, multiModule, func(t *testing.T, env *Env) {
// Initially, the go.work should cause only the a.com module to be
// loaded. Validate this by jumping to a definition in b.com and ensuring
// that we go to the module cache.
env.OpenFile("moda/a/a.go")
env.Await(env.DoneWithOpen())
// To verify which modules are loaded, we'll jump to the definition of
// b.Hello.
checkHelloLocation := func(want string) error {
location, _ := env.GoToDefinition("moda/a/a.go", env.RegexpSearch("moda/a/a.go", "Hello"))
if !strings.HasSuffix(location, want) {
return fmt.Errorf("expected %s, got %v", want, location)
}
return nil
}
// Initially this should be in the module cache, as b.com is not replaced.
if err := checkHelloLocation("b.com@v1.2.3/b/b.go"); err != nil {
t.Fatal(err)
}
// Now, modify the go.work file on disk to activate the b.com module in
// the workspace.
env.WriteWorkspaceFile("go.work", `
go 1.17
use (
./moda/a
./modb
)
`)
// As of golang/go#54069, writing go.work to the workspace triggers a
// workspace reload.
env.Await(
OnceMet(
env.DoneWithChangeWatchedFiles(),
env.DiagnosticAtRegexp("modb/b/b.go", "x"),
),
)
// Jumping to definition should now go to b.com in the workspace.
if err := checkHelloLocation("modb/b/b.go"); err != nil {
t.Fatal(err)
}
// Now, let's modify the go.work *overlay* (not on disk), and verify that
// this change is only picked up once it is saved.
env.OpenFile("go.work")
env.Await(env.DoneWithOpen())
env.SetBufferContent("go.work", `go 1.17
use (
./moda/a
)`)
// Simply modifying the go.work file does not cause a reload, so we should
// still jump within the workspace.
//
// TODO: should editing the go.work above cause modb diagnostics to be
// suppressed?
env.Await(env.DoneWithChange())
if err := checkHelloLocation("modb/b/b.go"); err != nil {
t.Fatal(err)
}
// Saving should reload the workspace.
env.SaveBufferWithoutActions("go.work")
if err := checkHelloLocation("b.com@v1.2.3/b/b.go"); err != nil {
t.Fatal(err)
}
// This fails if guarded with a OnceMet(DoneWithSave(), ...), because it is
// debounced (and therefore not synchronous with the change).
env.Await(EmptyOrNoDiagnostics("modb/go.mod"))
// Test Formatting.
env.SetBufferContent("go.work", `go 1.18
use (
./moda/a
)
`) // TODO(matloob): For some reason there's a "start position 7:0 is out of bounds" error when the ")" is on the last character/line in the file. Rob probably knows what's going on.
env.SaveBuffer("go.work")
env.Await(env.DoneWithSave())
gotWorkContents := env.ReadWorkspaceFile("go.work")
wantWorkContents := `go 1.18
use (
./moda/a
)
`
if gotWorkContents != wantWorkContents {
t.Fatalf("formatted contents of workspace: got %q; want %q", gotWorkContents, wantWorkContents)
}
})
}
func TestUseGoWorkDiagnosticMissingModule(t *testing.T) {
const files = `
-- go.work --
go 1.18
use ./foo
-- bar/go.mod --
module example.com/bar
`
Run(t, files, func(t *testing.T, env *Env) {
env.OpenFile("go.work")
env.Await(
env.DiagnosticAtRegexpWithMessage("go.work", "use", "directory ./foo does not contain a module"),
)
// The following tests is a regression test against an issue where we weren't
// copying the workFile struct field on workspace when a new one was created in
// (*workspace).invalidate. Set the buffer content to a working file so that
// invalidate recognizes the workspace to be change and copies over the workspace
// struct, and then set the content back to the old contents to make sure
// the diagnostic still shows up.
env.SetBufferContent("go.work", "go 1.18 \n\n use ./bar\n")
env.Await(
env.NoDiagnosticAtRegexp("go.work", "use"),
)
env.SetBufferContent("go.work", "go 1.18 \n\n use ./foo\n")
env.Await(
env.DiagnosticAtRegexpWithMessage("go.work", "use", "directory ./foo does not contain a module"),
)
})
}
func TestUseGoWorkDiagnosticSyntaxError(t *testing.T) {
const files = `
-- go.work --
go 1.18
usa ./foo
replace
`
Run(t, files, func(t *testing.T, env *Env) {
env.OpenFile("go.work")
env.Await(
env.DiagnosticAtRegexpWithMessage("go.work", "usa", "unknown directive: usa"),
env.DiagnosticAtRegexpWithMessage("go.work", "replace", "usage: replace"),
)
})
}
func TestUseGoWorkHover(t *testing.T) {
const files = `
-- go.work --
go 1.18
use ./foo
use (
./bar
./bar/baz
)
-- foo/go.mod --
module example.com/foo
-- bar/go.mod --
module example.com/bar
-- bar/baz/go.mod --
module example.com/bar/baz
`
Run(t, files, func(t *testing.T, env *Env) {
env.OpenFile("go.work")
tcs := map[string]string{
`\./foo`: "example.com/foo",
`(?m)\./bar$`: "example.com/bar",
`\./bar/baz`: "example.com/bar/baz",
}
for hoverRE, want := range tcs {
pos := env.RegexpSearch("go.work", hoverRE)
got, _ := env.Hover("go.work", pos)
if got.Value != want {
t.Errorf(`hover on %q: got %q, want %q`, hoverRE, got, want)
}
}
})
}
func TestExpandToGoWork(t *testing.T) {
testenv.NeedsGo1Point(t, 18)
const workspace = `
-- moda/a/go.mod --
module a.com
require b.com v1.2.3
-- moda/a/a.go --
package a
import (
"b.com/b"
)
func main() {
var x int
_ = b.Hello()
}
-- modb/go.mod --
module b.com
require example.com v1.2.3
-- modb/b/b.go --
package b
func Hello() int {
var x int
}
-- go.work --
go 1.17
use (
./moda/a
./modb
)
`
WithOptions(
WorkspaceFolders("moda/a"),
).Run(t, workspace, func(t *testing.T, env *Env) {
env.OpenFile("moda/a/a.go")
env.Await(env.DoneWithOpen())
location, _ := env.GoToDefinition("moda/a/a.go", env.RegexpSearch("moda/a/a.go", "Hello"))
want := "modb/b/b.go"
if !strings.HasSuffix(location, want) {
t.Errorf("expected %s, got %v", want, location)
}
})
}
func TestNonWorkspaceFileCreation(t *testing.T) {
const files = `
-- go.mod --
module mod.com
go 1.12
-- x.go --
package x
`
const code = `
package foo
import "fmt"
var _ = fmt.Printf
`
Run(t, files, func(t *testing.T, env *Env) {
env.CreateBuffer("/tmp/foo.go", "")
env.EditBuffer("/tmp/foo.go", fake.NewEdit(0, 0, 0, 0, code))
env.GoToDefinition("/tmp/foo.go", env.RegexpSearch("/tmp/foo.go", `Printf`))
})
}
func TestGoWork_V2Module(t *testing.T) {
testenv.NeedsGo1Point(t, 18) // uses go.work
// When using a go.work, we must have proxy content even if it is replaced.
const proxy = `
-- b.com/v2@v2.1.9/go.mod --
module b.com/v2
go 1.12
-- b.com/v2@v2.1.9/b/b.go --
package b
func Ciao()() int {
return 0
}
`
const multiModule = `
-- go.work --
go 1.18
use (
moda/a
modb
modb/v2
modc
)
-- moda/a/go.mod --
module a.com
require b.com/v2 v2.1.9
-- moda/a/a.go --
package a
import (
"b.com/v2/b"
)
func main() {
var x int
_ = b.Hi()
}
-- modb/go.mod --
module b.com
-- modb/b/b.go --
package b
func Hello() int {
var x int
}
-- modb/v2/go.mod --
module b.com/v2
-- modb/v2/b/b.go --
package b
func Hi() int {
var x int
}
-- modc/go.mod --
module gopkg.in/yaml.v1 // test gopkg.in versions
-- modc/main.go --
package main
func main() {
var x int
}
`
WithOptions(
ProxyFiles(proxy),
).Run(t, multiModule, func(t *testing.T, env *Env) {
env.Await(
OnceMet(
InitialWorkspaceLoad,
// TODO(rfindley): assert on the full set of diagnostics here. We
// should ensure that we don't have a diagnostic at b.Hi in a.go.
env.DiagnosticAtRegexp("moda/a/a.go", "x"),
env.DiagnosticAtRegexp("modb/b/b.go", "x"),
env.DiagnosticAtRegexp("modb/v2/b/b.go", "x"),
env.DiagnosticAtRegexp("modc/main.go", "x"),
),
)
})
}
// Confirm that a fix for a tidy module will correct all modules in the
// workspace.
func TestMultiModule_OneBrokenModule(t *testing.T) {
// In the earlier 'experimental workspace mode', gopls would aggregate go.sum
// entries for the workspace module, allowing it to correctly associate
// missing go.sum with diagnostics. With go.work files, this doesn't work:
// the go.command will happily write go.work.sum.
t.Skip("golang/go#57509: go.mod diagnostics do not work in go.work mode")
testenv.NeedsGo1Point(t, 18) // uses go.work
const files = `
-- go.work --
go 1.18
use (
a
b
)
-- go.work.sum --
-- a/go.mod --
module a.com
go 1.12
-- a/main.go --
package main
-- b/go.mod --
module b.com
go 1.12
require (
example.com v1.2.3
)
-- b/go.sum --
-- b/main.go --
package b
import "example.com/blah"
func main() {
blah.Hello()
}
`
WithOptions(
ProxyFiles(workspaceProxy),
).Run(t, files, func(t *testing.T, env *Env) {
params := &protocol.PublishDiagnosticsParams{}
env.OpenFile("b/go.mod")
env.Await(
OnceMet(
env.GoSumDiagnostic("b/go.mod", `example.com v1.2.3`),
ReadDiagnostics("b/go.mod", params),
),
)
for _, d := range params.Diagnostics {
if !strings.Contains(d.Message, "go.sum is out of sync") {
continue
}
actions := env.GetQuickFixes("b/go.mod", []protocol.Diagnostic{d})
if len(actions) != 2 {
t.Fatalf("expected 2 code actions, got %v", len(actions))
}
env.ApplyQuickFixes("b/go.mod", []protocol.Diagnostic{d})
}
env.Await(
EmptyDiagnostics("b/go.mod"),
)
})
}
// Sometimes users may have their module cache within the workspace.
// We shouldn't consider any module in the module cache to be in the workspace.
func TestGOMODCACHEInWorkspace(t *testing.T) {
const mod = `
-- a/go.mod --
module a.com
go 1.12
-- a/a.go --
package a
func _() {}
-- a/c/c.go --
package c
-- gopath/src/b/b.go --
package b
-- gopath/pkg/mod/example.com/go.mod --
module example.com
go 1.12
-- gopath/pkg/mod/example.com/main.go --
package main
`
WithOptions(
EnvVars{"GOPATH": filepath.FromSlash("$SANDBOX_WORKDIR/gopath")},
Modes(Default),
).Run(t, mod, func(t *testing.T, env *Env) {
env.Await(
// Confirm that the build configuration is seen as valid,
// even though there are technically multiple go.mod files in the
// worskpace.
LogMatching(protocol.Info, ".*valid build configuration = true.*", 1, false),
)
})
}
func TestAddAndRemoveGoWork(t *testing.T) {
// Use a workspace with a module in the root directory to exercise the case
// where a go.work is added to the existing root directory. This verifies
// that we're detecting changes to the module source, not just the root
// directory.
const nomod = `
-- go.mod --
module a.com
go 1.16
-- main.go --
package main
func main() {}
-- b/go.mod --
module b.com
go 1.16
-- b/main.go --
package main
func main() {}
`
WithOptions(
Modes(Default),
).Run(t, nomod, func(t *testing.T, env *Env) {
env.OpenFile("main.go")
env.OpenFile("b/main.go")
// Since b/main.go is not in the workspace, it should have a warning on its
// package declaration.
env.AfterChange(
EmptyDiagnostics("main.go"),
DiagnosticAt("b/main.go", 0, 0),
)
env.WriteWorkspaceFile("go.work", `go 1.16
use (
.
b
)
`)
env.AfterChange(NoOutstandingDiagnostics())
// Removing the go.work file should put us back where we started.
env.RemoveWorkspaceFile("go.work")
// TODO(golang/go#57558, golang/go#57508): file watching is asynchronous,
// and we must wait for the view to be reconstructed before touching
// b/main.go, so that the new view "knows" about b/main.go. This is simply
// a bug, but awaiting the change here avoids it.
env.Await(env.DoneWithChangeWatchedFiles())
// TODO(rfindley): fix this bug: reopening b/main.go is necessary here
// because we no longer "see" the file in any view.
env.CloseBuffer("b/main.go")
env.OpenFile("b/main.go")
env.AfterChange(
EmptyDiagnostics("main.go"),
DiagnosticAt("b/main.go", 0, 0),
)
})
}
// Tests the fix for golang/go#52500.
func TestChangeTestVariant_Issue52500(t *testing.T) {
const src = `
-- go.mod --
module mod.test
go 1.12
-- main_test.go --
package main_test
type Server struct{}
const mainConst = otherConst
-- other_test.go --
package main_test
const otherConst = 0
func (Server) Foo() {}
`
Run(t, src, func(t *testing.T, env *Env) {
env.OpenFile("other_test.go")
env.RegexpReplace("other_test.go", "main_test", "main")
// For this test to function, it is necessary to wait on both of the
// expectations below: the bug is that when switching the package name in
// other_test.go from main->main_test, metadata for main_test is not marked
// as invalid. So we need to wait for the metadata of main_test.go to be
// updated before moving other_test.go back to the main_test package.
env.Await(
env.DiagnosticAtRegexp("other_test.go", "Server"),
env.DiagnosticAtRegexp("main_test.go", "otherConst"),
)
env.RegexpReplace("other_test.go", "main", "main_test")
env.Await(
EmptyDiagnostics("other_test.go"),
EmptyDiagnostics("main_test.go"),
)
// This will cause a test failure if other_test.go is not in any package.
_, _ = env.GoToDefinition("other_test.go", env.RegexpSearch("other_test.go", "Server"))
})
}
// Test for golang/go#48929.
func TestClearNonWorkspaceDiagnostics(t *testing.T) {
testenv.NeedsGo1Point(t, 18) // uses go.work
const ws = `
-- go.work --
go 1.18
use (
./b
)
-- a/go.mod --
module a
go 1.17
-- a/main.go --
package main
func main() {
var V string
}
-- b/go.mod --
module b
go 1.17
-- b/main.go --
package b
import (
_ "fmt"
)
`
Run(t, ws, func(t *testing.T, env *Env) {
env.OpenFile("b/main.go")
env.Await(
OnceMet(
env.DoneWithOpen(),
NoDiagnostics("a/main.go"),
),
)
env.OpenFile("a/main.go")
env.Await(
OnceMet(
env.DoneWithOpen(),
env.DiagnosticAtRegexpWithMessage("a/main.go", "V", "not used"),
),
)
env.CloseBuffer("a/main.go")
// Make an arbitrary edit because gopls explicitly diagnoses a/main.go
// whenever it is "changed".
//
// TODO(rfindley): it should not be necessary to make another edit here.
// Gopls should be smart enough to avoid diagnosing a.
env.RegexpReplace("b/main.go", "package b", "package b // a package")
env.Await(
OnceMet(
env.DoneWithChange(),
EmptyDiagnostics("a/main.go"),
),
)
})
}
// Test that we don't get a version warning when the Go version in PATH is
// supported.
func TestOldGoNotification_SupportedVersion(t *testing.T) {
v := goVersion(t)
if v < lsp.OldestSupportedGoVersion() {
t.Skipf("go version 1.%d is unsupported", v)
}
Run(t, "", func(t *testing.T, env *Env) {
env.Await(
OnceMet(
InitialWorkspaceLoad,
NoShownMessage("upgrade"),
),
)
})
}
// Test that we do get a version warning when the Go version in PATH is
// unsupported, though this test may never execute if we stop running CI at
// legacy Go versions (see also TestOldGoNotification_Fake)
func TestOldGoNotification_UnsupportedVersion(t *testing.T) {
v := goVersion(t)
if v >= lsp.OldestSupportedGoVersion() {
t.Skipf("go version 1.%d is supported", v)
}
Run(t, "", func(t *testing.T, env *Env) {
env.Await(
// Note: cannot use OnceMet(InitialWorkspaceLoad, ...) here, as the
// upgrade message may race with the IWL.
ShownMessage("Please upgrade"),
)
})
}
func TestOldGoNotification_Fake(t *testing.T) {
// Get the Go version from path, and make sure it's unsupported.
//
// In the future we'll stop running CI on legacy Go versions. By mutating the
// oldest supported Go version here, we can at least ensure that the
// ShowMessage pop-up works.
ctx := context.Background()
goversion, err := gocommand.GoVersion(ctx, gocommand.Invocation{}, &gocommand.Runner{})
if err != nil {
t.Fatal(err)
}
defer func(t []lsp.GoVersionSupport) {
lsp.GoVersionTable = t
}(lsp.GoVersionTable)
lsp.GoVersionTable = []lsp.GoVersionSupport{
{GoVersion: goversion, InstallGoplsVersion: "v1.0.0"},
}
Run(t, "", func(t *testing.T, env *Env) {
env.Await(
// Note: cannot use OnceMet(InitialWorkspaceLoad, ...) here, as the
// upgrade message may race with the IWL.
ShownMessage("Please upgrade"),
)
})
}
// goVersion returns the version of the Go command in PATH.
func goVersion(t *testing.T) int {
t.Helper()
ctx := context.Background()
goversion, err := gocommand.GoVersion(ctx, gocommand.Invocation{}, &gocommand.Runner{})
if err != nil {
t.Fatal(err)
}
return goversion
}
|