Debian Codegraph @

go/packages/packages_test.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 // Copyright 2018 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 packages_test
6
7 import (
8 "bytes"
9 "encoding/json"
10 "fmt"
11 "go/ast"
12 constantpkg "go/constant"
13 "go/parser"
14 "go/token"
15 "go/types"
16 "io"
17 "log"
18 "os"
19 "os/exec"
20 "path/filepath"
21 "reflect"
22 "regexp"
23 "runtime"
24 "slices"
25 "sort"
26 "strings"
27 "testing"
28 "testing/fstest"
29
30 "github.com/google/go-cmp/cmp"
31 "golang.org/x/tools/go/packages"
32 "golang.org/x/tools/internal/packagepath"
33 "golang.org/x/tools/internal/packagesinternal"
34 "golang.org/x/tools/internal/packagestest"
35 "golang.org/x/tools/internal/testenv"
36 "golang.org/x/tools/internal/testfiles"
37 "golang.org/x/tools/txtar"
38 )
39
40 func TestMain(m *testing.M) {
41 testenv.ExitIfSmallMachine()
42
43 // This executable also behaves as various flavors of
44 // GOPACKAGESDRIVER command for some tests, based on ENTRYPOINT.
45 entrypoint := os.Getenv("ENTRYPOINT")
46 switch entrypoint {
47 case "":
48 os.Exit(m.Run())
49 case "driver1":
50 driver1()
51 case "driver2":
52 driver2()
53 default:
54 log.Fatalf("unexpected ENTRYPOINT %q", entrypoint)
55 }
56 }
57
58 func skipIfShort(t *testing.T, reason string) {
59 if testing.Short() {
60 t.Skipf("skipping slow test in short mode: %s", reason)
61 }
62 }
63
64 // testAllOrModulesParallel tests f, in parallel, against all packagestest
65 // exporters in long mode, but only against the Modules exporter in short mode.
66 func testAllOrModulesParallel(t *testing.T, f func(*testing.T, packagestest.Exporter)) {
67 t.Parallel()
68 packagestest.TestAll(t, func(t *testing.T, exporter packagestest.Exporter) {
69 t.Helper()
70
71 switch exporter.Name() {
72 case "Modules":
73 case "GOPATH":
74 if testing.Short() {
75 t.Skipf("skipping GOPATH test in short mode")
76 }
77 default:
78 t.Fatalf("unexpected exporter %q", exporter.Name())
79 }
80
81 t.Parallel()
82 f(t, exporter)
83 })
84 }
85
86 // TODO(adonovan): more test cases to write:
87 //
88 // - When the tests fail, make them print a 'cd & load' command
89 // that will allow the maintainer to interact with the failing scenario.
90 // - errors in go-list metadata
91 // - a foo.test package that cannot be built for some reason (e.g.
92 // import error) will result in a JSON blob with no name and a
93 // nonexistent testmain file in GoFiles. Test that we handle this
94 // gracefully.
95 // - test more Flags.
96 //
97 // LoadSyntax & LoadAllSyntax modes:
98 // - Fset may be user-supplied or not.
99 // - Packages.Info is correctly set.
100 // - typechecker configuration is honored
101 // - import cycles are gracefully handled in type checker.
102 // - test typechecking of generated test main and cgo.
103
104 // The zero-value of Config has LoadFiles mode.
105 func TestLoadZeroConfig(t *testing.T) {
106 testenv.NeedsGoPackages(t)
107 t.Parallel()
108
109 initial, err := packages.Load(nil, "hash")
110 if err != nil {
111 t.Fatal(err)
112 }
113 if len(initial) != 1 {
114 t.Fatalf("got %s, want [hash]", initial)
115 }
116 hash := initial[0]
117 // Even though the hash package has imports,
118 // they are not reported.
119 got := fmt.Sprintf("srcs=%v imports=%v", srcs(hash), hash.Imports)
120 want := "srcs=[hash.go] imports=map[]"
121 if got != want {
122 t.Fatalf("got %s, want %s", got, want)
123 }
124 }
125
126 func TestLoadImportsGraph(t *testing.T) { testAllOrModulesParallel(t, testLoadImportsGraph) }
127 func testLoadImportsGraph(t *testing.T, exporter packagestest.Exporter) {
128 exported := packagestest.Export(t, exporter, []packagestest.Module{{
129 Name: "golang.org/fake",
130 Files: map[string]any{
131 "a/a.go": `package a; const A = 1`,
132 "b/b.go": `package b; import ("golang.org/fake/a"; _ "container/list"); var B = a.A`,
133 "c/c.go": `package c; import (_ "golang.org/fake/b"; _ "unsafe")`,
134 "c/c2.go": "// +build ignore\n\n" + `package c; import _ "fmt"`,
135 "subdir/d/d.go": `package d`,
136 "subdir/d/d_test.go": `package d; import _ "math/bits"`,
137 "subdir/d/x_test.go": `package d_test; import _ "golang.org/fake/subdir/d"`, // TODO(adonovan): test bad import here
138 "subdir/e/d.go": `package e`,
139 "e/e.go": `package main; import _ "golang.org/fake/b"`,
140 "e/e2.go": `package main; import _ "golang.org/fake/c"`,
141 "f/f.go": `package f`,
142 }}})
143 defer exported.Cleanup()
144 exported.Config.Mode = packages.LoadImports
145 initial, err := packages.Load(exported.Config, "golang.org/fake/c", "golang.org/fake/subdir/d", "golang.org/fake/e")
146 if err != nil {
147 t.Fatal(err)
148 }
149
150 // Check graph topology.
151 graph, _ := importGraph(initial)
152 wantGraph := `
153 container/list
154 golang.org/fake/a
155 golang.org/fake/b
156 * golang.org/fake/c
157 * golang.org/fake/e
158 * golang.org/fake/subdir/d
159 * golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
160 * golang.org/fake/subdir/d.test
161 * golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
162 math/bits
163 unsafe
164 golang.org/fake/b -> container/list
165 golang.org/fake/b -> golang.org/fake/a
166 golang.org/fake/c -> golang.org/fake/b
167 golang.org/fake/c -> unsafe
168 golang.org/fake/e -> golang.org/fake/b
169 golang.org/fake/e -> golang.org/fake/c
170 golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] -> math/bits
171 golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
172 golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
173 golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
174 `[1:]
175
176 if graph != wantGraph {
177 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
178 }
179
180 exported.Config.Tests = true
181 initial, err = packages.Load(exported.Config, "golang.org/fake/c", "golang.org/fake/subdir/d", "golang.org/fake/e")
182 if err != nil {
183 t.Fatal(err)
184 }
185
186 // Check graph topology.
187 graph, all := importGraph(initial)
188 wantGraph = `
189 container/list
190 golang.org/fake/a
191 golang.org/fake/b
192 * golang.org/fake/c
193 * golang.org/fake/e
194 * golang.org/fake/subdir/d
195 * golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
196 * golang.org/fake/subdir/d.test
197 * golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
198 math/bits
199 unsafe
200 golang.org/fake/b -> container/list
201 golang.org/fake/b -> golang.org/fake/a
202 golang.org/fake/c -> golang.org/fake/b
203 golang.org/fake/c -> unsafe
204 golang.org/fake/e -> golang.org/fake/b
205 golang.org/fake/e -> golang.org/fake/c
206 golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] -> math/bits
207 golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
208 golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
209 golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
210 `[1:]
211
212 if graph != wantGraph {
213 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
214 }
215
216 // Check node information: kind, name, srcs.
217 for _, test := range []struct {
218 id string
219 wantName string
220 wantKind string
221 wantSrcs string // = {Go,Other,Embed}Files
222 wantIgnored string
223 }{
224 {"golang.org/fake/a", "a", "package", "a.go", ""},
225 {"golang.org/fake/b", "b", "package", "b.go", ""},
226 {"golang.org/fake/c", "c", "package", "c.go", "c2.go"}, // c2.go is ignored
227 {"golang.org/fake/e", "main", "command", "e.go e2.go", ""},
228 {"container/list", "list", "package", "list.go", ""},
229 {"golang.org/fake/subdir/d", "d", "package", "d.go", ""},
230 {"golang.org/fake/subdir/d.test", "main", "command", "0.go", ""},
231 {"unsafe", "unsafe", "package", "unsafe.go", ""},
232 } {
233 p, ok := all[test.id]
234 if !ok {
235 t.Errorf("no package %s", test.id)
236 continue
237 }
238 if p.Name != test.wantName {
239 t.Errorf("%s.Name = %q, want %q", test.id, p.Name, test.wantName)
240 }
241
242 // kind
243 var kind string
244 if p.Name == "main" {
245 kind += "command"
246 } else {
247 kind += "package"
248 }
249 if kind != test.wantKind {
250 t.Errorf("%s.Kind = %q, want %q", test.id, kind, test.wantKind)
251 }
252
253 if srcs := strings.Join(srcs(p), " "); srcs != test.wantSrcs {
254 t.Errorf("%s.{Go,Other,Embed}Files = [%s], want [%s]", test.id, srcs, test.wantSrcs)
255 }
256 if ignored := strings.Join(cleanPaths(p.IgnoredFiles), " "); ignored != test.wantIgnored {
257 t.Errorf("%s.IgnoredFiles = [%s], want [%s]", test.id, ignored, test.wantIgnored)
258 }
259 }
260
261 // Test an ad-hoc package, analogous to "go run hello.go".
262 if initial, err := packages.Load(exported.Config, exported.File("golang.org/fake", "c/c.go")); len(initial) == 0 {
263 t.Errorf("failed to obtain metadata for ad-hoc package: %s", err)
264 } else {
265 got := fmt.Sprintf("%s %s", initial[0].ID, srcs(initial[0]))
266 if want := "command-line-arguments [c.go]"; got != want {
267 t.Errorf("oops: got %s, want %s", got, want)
268 }
269 }
270
271 // Wildcards
272 // See StdlibTest for effective test of "std" wildcard.
273 // TODO(adonovan): test "all" returns everything in the current module.
274 {
275 // "..." (subdirectory)
276 initial, err = packages.Load(exported.Config, "golang.org/fake/subdir/...")
277 if err != nil {
278 t.Fatal(err)
279 }
280 graph, _ = importGraph(initial)
281 wantGraph = `
282 * golang.org/fake/subdir/d
283 * golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
284 * golang.org/fake/subdir/d.test
285 * golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
286 * golang.org/fake/subdir/e
287 math/bits
288 golang.org/fake/subdir/d [golang.org/fake/subdir/d.test] -> math/bits
289 golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
290 golang.org/fake/subdir/d.test -> golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test]
291 golang.org/fake/subdir/d_test [golang.org/fake/subdir/d.test] -> golang.org/fake/subdir/d [golang.org/fake/subdir/d.test]
292 `[1:]
293
294 if graph != wantGraph {
295 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
296 }
297 }
298 }
299
300 func TestLoadImportsTestVariants(t *testing.T) {
301 testAllOrModulesParallel(t, testLoadImportsTestVariants)
302 }
303 func testLoadImportsTestVariants(t *testing.T, exporter packagestest.Exporter) {
304 exported := packagestest.Export(t, exporter, []packagestest.Module{{
305 Name: "golang.org/fake",
306 Files: map[string]any{
307 "a/a.go": `package a; import _ "golang.org/fake/b"`,
308 "b/b.go": `package b`,
309 "b/b_test.go": `package b`,
310 "b/bx_test.go": `package b_test; import _ "golang.org/fake/a"`,
311 }}})
312 defer exported.Cleanup()
313 exported.Config.Mode = packages.LoadImports
314 exported.Config.Tests = true
315
316 initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/b")
317 if err != nil {
318 t.Fatal(err)
319 }
320
321 // Check graph topology.
322 graph, _ := importGraph(initial)
323 wantGraph := `
324 * golang.org/fake/a
325 golang.org/fake/a [golang.org/fake/b.test]
326 * golang.org/fake/b
327 * golang.org/fake/b [golang.org/fake/b.test]
328 * golang.org/fake/b.test
329 * golang.org/fake/b_test [golang.org/fake/b.test]
330 golang.org/fake/a -> golang.org/fake/b
331 golang.org/fake/a [golang.org/fake/b.test] -> golang.org/fake/b [golang.org/fake/b.test]
332 golang.org/fake/b.test -> golang.org/fake/b [golang.org/fake/b.test]
333 golang.org/fake/b.test -> golang.org/fake/b_test [golang.org/fake/b.test]
334 golang.org/fake/b_test [golang.org/fake/b.test] -> golang.org/fake/a [golang.org/fake/b.test]
335 `[1:]
336
337 if graph != wantGraph {
338 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
339 }
340 }
341
342 func TestLoadAbsolutePath(t *testing.T) {
343 t.Parallel()
344
345 exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{
346 Name: "golang.org/gopatha",
347 Files: map[string]any{
348 "a/a.go": `package a`,
349 }}, {
350 Name: "golang.org/gopathb",
351 Files: map[string]any{
352 "b/b.go": `package b`,
353 }}})
354 defer exported.Cleanup()
355
356 initial, err := packages.Load(exported.Config, filepath.Dir(exported.File("golang.org/gopatha", "a/a.go")), filepath.Dir(exported.File("golang.org/gopathb", "b/b.go")))
357 if err != nil {
358 t.Fatalf("failed to load imports: %v", err)
359 }
360
361 got := []string{}
362 for _, p := range initial {
363 got = append(got, p.ID)
364 }
365 sort.Strings(got)
366 want := []string{"golang.org/gopatha/a", "golang.org/gopathb/b"}
367 if !reflect.DeepEqual(got, want) {
368 t.Fatalf("initial packages loaded: got [%s], want [%s]", got, want)
369 }
370 }
371
372 func TestLoadArgumentListIsNotTooLong(t *testing.T) {
373 // NOTE: this test adds about 2s to the test suite running time
374
375 t.Parallel()
376
377 // using the real ARG_MAX for some platforms increases the running time of this test by a lot,
378 // 1_000_000 seems like enough to break Windows and macOS if Load doesn't split provided patterns
379 argMax := 1_000_000
380 exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{
381 Name: "golang.org/mod",
382 Files: map[string]any{
383 "main.go": `package main"`,
384 }}})
385 defer exported.Cleanup()
386 numOfPatterns := argMax/16 + 1 // the pattern below is approx. 16 chars
387 patterns := make([]string, numOfPatterns)
388 for i := range numOfPatterns {
389 patterns[i] = fmt.Sprintf("golang.org/mod/p%d", i)
390 } // patterns have more than argMax number of chars combined with whitespaces b/w patterns
391
392 _, err := packages.Load(exported.Config, patterns...)
393 if err != nil {
394 t.Fatalf("failed to load: %v", err)
395 }
396 }
397
398 func TestLoadSamePackageMultipleChunks(t *testing.T) {
399 t.Parallel()
400
401 exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{
402 Name: "golang.org/fake",
403 Files: map[string]any{
404 "a/def.go": `package a; const SharedConstant = 42`,
405 }}})
406 defer exported.Cleanup()
407
408 defFile := exported.File("golang.org/fake", "a/def.go")
409
410 // Force chunking (exceed ~16KB arg limit)
411 var files []string
412 files = append(files, defFile)
413
414 for i := range 200 {
415 fillerPath := filepath.Join(filepath.Dir(defFile), fmt.Sprintf("filler_%03d.go", i))
416 if err := os.WriteFile(fillerPath, []byte("package a\n"), 0644); err != nil {
417 t.Fatal(err)
418 }
419 files = append(files, fillerPath)
420 }
421
422 exported.Config.Mode = packages.NeedFiles
423 pkgs, err := packages.Load(exported.Config, files...)
424 if err != nil {
425 t.Fatal(err)
426 }
427
428 if len(pkgs) == 0 {
429 t.Fatal("package golang.org/fake/a not found")
430 }
431
432 if len(pkgs[0].GoFiles) != len(files) {
433 t.Errorf("expected %d files, got %d", len(files), len(pkgs[0].GoFiles))
434 }
435 }
436
437 // TestLoadDoesNotInvokeGit ensures that the expensive and unnecessary VCS check is skipped;
438 // see go.dev/issue/51999 and go.dev/issue/77419.
439 func TestLoadDoesNotInvokeGit(t *testing.T) {
440 testenv.NeedsGoPackages(t)
441 t.Parallel()
442
443 exported := packagestest.Export(t, packagestest.Modules, []packagestest.Module{{
444 Name: "golang.org/fake",
445 Files: map[string]any{
446 "main.go": `package main; func main() {}`,
447 }}})
448 defer exported.Cleanup()
449
450 // mock a git repository by creating a .git directory
451 modRoot := filepath.Dir(exported.File("golang.org/fake", "main.go"))
452 if err := os.MkdirAll(filepath.Join(modRoot, ".git"), 0755); err != nil {
453 t.Fatalf("creating .git: %v", err)
454 }
455
456 fakeGitDir := buildFakeGit(t, exported.Config.Env)
457
458 pathVar := "PATH"
459 if runtime.GOOS == "plan9" {
460 pathVar = "path"
461 }
462 exported.Config.Env = prependPath(exported.Config.Env, pathVar, fakeGitDir)
463 // NeedTypes triggers usesExportData, which sets -export=true on the go list invocation
464 exported.Config.Mode = packages.NeedTypes
465
466 pkgs, err := packages.Load(exported.Config, "golang.org/fake")
467 if err != nil {
468 t.Fatalf("packages.Load: %v", err)
469 }
470 if len(pkgs) != 1 {
471 t.Fatalf("packages.Load: expected 1 package, got %d: %v", len(pkgs), pkgs)
472 }
473 if len(pkgs[0].Errors) > 0 {
474 // Assume the failure was due to the fake git command being executed.
475 t.Fatalf("packages.Load: unexpected errors (git should not have been called): %v", pkgs[0].Errors)
476 }
477 }
478
479 // buildFakeGit returns a directory containing a "git" executable that exits 1.
480 func buildFakeGit(t *testing.T, env []string) string {
481 t.Helper()
482
483 tmpdir := t.TempDir()
484 gitName := "git"
485 if runtime.GOOS == "windows" {
486 gitName = "git.exe"
487 }
488 src := filepath.Join(tmpdir, "main.go")
489 if err := os.WriteFile(src, []byte(`package main; func main() { panic("git executed") }`), 0644); err != nil {
490 t.Fatal(err)
491 }
492 cmd := exec.Command("go", "build", "-o", gitName, "main.go")
493 cmd.Dir = tmpdir
494 cmd.Env = env
495 if out, err := cmd.CombinedOutput(); err != nil {
496 t.Fatalf("building fake git: %v\n%s", err, out)
497 }
498 return tmpdir
499 }
500
501 func prependPath(env []string, key, dir string) []string {
502 result := make([]string, len(env))
503 copy(result, env)
504 for i, v := range result {
505 if val, ok := strings.CutPrefix(v, key+"="); ok {
506 result[i] = key + "=" + dir + string(os.PathListSeparator) + val
507 return result
508 }
509 }
510 return append(result, key+"="+dir)
511 }
512
513 func TestVendorImports(t *testing.T) {
514 t.Parallel()
515
516 exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{
517 Name: "golang.org/fake",
518 Files: map[string]any{
519 "a/a.go": `package a; import _ "b"; import _ "golang.org/fake/c";`,
520 "a/vendor/b/b.go": `package b; import _ "golang.org/fake/c"`,
521 "c/c.go": `package c; import _ "b"`,
522 "c/vendor/b/b.go": `package b`,
523 }}})
524 defer exported.Cleanup()
525 exported.Config.Mode = packages.LoadImports
526 initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c")
527 if err != nil {
528 t.Fatal(err)
529 }
530
531 graph, all := importGraph(initial)
532 wantGraph := `
533 * golang.org/fake/a
534 golang.org/fake/a/vendor/b
535 * golang.org/fake/c
536 golang.org/fake/c/vendor/b
537 golang.org/fake/a -> golang.org/fake/a/vendor/b
538 golang.org/fake/a -> golang.org/fake/c
539 golang.org/fake/a/vendor/b -> golang.org/fake/c
540 golang.org/fake/c -> golang.org/fake/c/vendor/b
541 `[1:]
542 if graph != wantGraph {
543 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
544 }
545
546 for _, test := range []struct {
547 pattern string
548 wantImports string
549 }{
550 {"golang.org/fake/a", "b:golang.org/fake/a/vendor/b golang.org/fake/c:golang.org/fake/c"},
551 {"golang.org/fake/c", "b:golang.org/fake/c/vendor/b"},
552 {"golang.org/fake/a/vendor/b", "golang.org/fake/c:golang.org/fake/c"},
553 {"golang.org/fake/c/vendor/b", ""},
554 } {
555 // Test the import paths.
556 pkg := all[test.pattern]
557 if imports := strings.Join(imports(pkg), " "); imports != test.wantImports {
558 t.Errorf("package %q: got %s, want %s", test.pattern, imports, test.wantImports)
559 }
560 }
561 }
562
563 func imports(p *packages.Package) []string {
564 if p == nil {
565 return nil
566 }
567 keys := make([]string, 0, len(p.Imports))
568 for k, v := range p.Imports {
569 keys = append(keys, fmt.Sprintf("%s:%s", k, v.ID))
570 }
571 sort.Strings(keys)
572 return keys
573 }
574
575 func TestConfigDir(t *testing.T) { testAllOrModulesParallel(t, testConfigDir) }
576 func testConfigDir(t *testing.T, exporter packagestest.Exporter) {
577 exported := packagestest.Export(t, exporter, []packagestest.Module{{
578 Name: "golang.org/fake",
579 Files: map[string]any{
580 "a/a.go": `package a; const Name = "a" `,
581 "a/b/b.go": `package b; const Name = "a/b"`,
582 "b/b.go": `package b; const Name = "b"`,
583 }}})
584 defer exported.Cleanup()
585 aDir := filepath.Dir(exported.File("golang.org/fake", "a/a.go"))
586 bDir := filepath.Dir(exported.File("golang.org/fake", "b/b.go"))
587 baseDir := filepath.Dir(aDir)
588
589 for _, test := range []struct {
590 dir string
591 pattern string
592 want string // value of Name constant
593 fails bool
594 }{
595 {dir: bDir, pattern: "golang.org/fake/a", want: `"a"`},
596 {dir: bDir, pattern: "golang.org/fake/b", want: `"b"`},
597 {dir: bDir, pattern: "./a", fails: true},
598 {dir: bDir, pattern: "./b", fails: true},
599 {dir: baseDir, pattern: "golang.org/fake/a", want: `"a"`},
600 {dir: baseDir, pattern: "golang.org/fake/b", want: `"b"`},
601 {dir: baseDir, pattern: "./a", want: `"a"`},
602 {dir: baseDir, pattern: "./b", want: `"b"`},
603 {dir: aDir, pattern: "golang.org/fake/a", want: `"a"`},
604 {dir: aDir, pattern: "golang.org/fake/b", want: `"b"`},
605 {dir: aDir, pattern: "./a", fails: true},
606 {dir: aDir, pattern: "./b", want: `"a/b"`},
607 } {
608 exported.Config.Mode = packages.LoadSyntax // Use LoadSyntax to ensure that files can be opened.
609 exported.Config.Dir = test.dir
610 initial, err := packages.Load(exported.Config, test.pattern)
611 var got string
612 fails := false
613 if err != nil {
614 fails = true
615 } else if len(initial) > 0 {
616 if len(initial[0].Errors) > 0 {
617 fails = true
618 } else if c := constant(initial[0], "Name"); c != nil {
619 got = c.Val().String()
620 }
621 }
622 if got != test.want {
623 t.Errorf("dir %q, pattern %q: got %s, want %s",
624 test.dir, test.pattern, got, test.want)
625 }
626 if fails != test.fails {
627 t.Errorf("dir %q, pattern %q: error %v, want %v",
628 test.dir, test.pattern, fails, test.fails)
629 }
630 }
631 }
632
633 func TestConfigFlags(t *testing.T) { testAllOrModulesParallel(t, testConfigFlags) }
634 func testConfigFlags(t *testing.T, exporter packagestest.Exporter) {
635 // Test satisfying +build line tags, with -tags flag.
636 exported := packagestest.Export(t, exporter, []packagestest.Module{{
637 Name: "golang.org/fake",
638 Files: map[string]any{
639 // package a
640 "a/a.go": `package a; import _ "golang.org/fake/a/b"`,
641 "a/b.go": `// +build tag
642
643 package a`,
644 "a/c.go": `// +build tag tag2
645
646 package a`,
647 "a/d.go": `// +build tag,tag2
648
649 package a`,
650 // package a/b
651 "a/b/a.go": `package b`,
652 "a/b/b.go": `// +build tag
653
654 package b`,
655 }}})
656 defer exported.Cleanup()
657
658 for _, test := range []struct {
659 pattern string
660 tags []string
661 wantSrcs string
662 wantImportSrcs string
663 }{
664 {`golang.org/fake/a`, []string{}, "a.go", "a.go"},
665 {`golang.org/fake/a`, []string{`-tags=tag`}, "a.go b.go c.go", "a.go b.go"},
666 {`golang.org/fake/a`, []string{`-tags=tag2`}, "a.go c.go", "a.go"},
667 {`golang.org/fake/a`, []string{`-tags=tag tag2`}, "a.go b.go c.go d.go", "a.go b.go"},
668 } {
669 exported.Config.Mode = packages.LoadImports
670 exported.Config.BuildFlags = test.tags
671
672 initial, err := packages.Load(exported.Config, test.pattern)
673 if err != nil {
674 t.Error(err)
675 continue
676 }
677 if len(initial) != 1 {
678 t.Errorf("test tags %v: pattern %s, expected 1 package, got %d packages.", test.tags, test.pattern, len(initial))
679 continue
680 }
681 pkg := initial[0]
682 if srcs := strings.Join(srcs(pkg), " "); srcs != test.wantSrcs {
683 t.Errorf("test tags %v: srcs of package %s = [%s], want [%s]", test.tags, test.pattern, srcs, test.wantSrcs)
684 }
685 for path, ipkg := range pkg.Imports {
686 if srcs := strings.Join(srcs(ipkg), " "); srcs != test.wantImportSrcs {
687 t.Errorf("build tags %v: srcs of imported package %s = [%s], want [%s]", test.tags, path, srcs, test.wantImportSrcs)
688 }
689 }
690
691 }
692 }
693
694 func TestLoadTypes(t *testing.T) { testAllOrModulesParallel(t, testLoadTypes) }
695 func testLoadTypes(t *testing.T, exporter packagestest.Exporter) {
696 // In LoadTypes and LoadSyntax modes, the compiler will
697 // fail to generate an export data file for c, because it has
698 // a type error. The loader should fall back loading a and c
699 // from source, but use the export data for b.
700
701 exported := packagestest.Export(t, exporter, []packagestest.Module{{
702 Name: "golang.org/fake",
703 Files: map[string]any{
704 "a/a.go": `package a; import "golang.org/fake/b"; import "golang.org/fake/c"; const A = "a" + b.B + c.C`,
705 "b/b.go": `package b; const B = "b"`,
706 "c/c.go": `package c; const C = "c" + 1`,
707 }}})
708 defer exported.Cleanup()
709
710 exported.Config.Mode = packages.LoadTypes
711 initial, err := packages.Load(exported.Config, "golang.org/fake/a")
712 if err != nil {
713 t.Fatal(err)
714 }
715
716 graph, all := importGraph(initial)
717 wantGraph := `
718 * golang.org/fake/a
719 golang.org/fake/b
720 golang.org/fake/c
721 golang.org/fake/a -> golang.org/fake/b
722 golang.org/fake/a -> golang.org/fake/c
723 `[1:]
724 if graph != wantGraph {
725 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
726 }
727
728 for _, id := range []string{
729 "golang.org/fake/a",
730 "golang.org/fake/b",
731 "golang.org/fake/c",
732 } {
733 p := all[id]
734 if p == nil {
735 t.Errorf("missing package: %s", id)
736 continue
737 }
738 if p.Types == nil {
739 t.Errorf("missing types.Package for %s", p)
740 continue
741 } else if !p.Types.Complete() {
742 t.Errorf("incomplete types.Package for %s", p)
743 } else if p.TypesSizes == nil {
744 t.Errorf("TypesSizes is not filled in for %s", p)
745 }
746
747 }
748 }
749
750 // TestLoadTypesBits is equivalent to TestLoadTypes except that it only requests
751 // the types using the NeedTypes bit.
752 func TestLoadTypesBits(t *testing.T) { testAllOrModulesParallel(t, testLoadTypesBits) }
753 func testLoadTypesBits(t *testing.T, exporter packagestest.Exporter) {
754 exported := packagestest.Export(t, exporter, []packagestest.Module{{
755 Name: "golang.org/fake",
756 Files: map[string]any{
757 "a/a.go": `package a; import "golang.org/fake/b"; const A = "a" + b.B`,
758 "b/b.go": `package b; import "golang.org/fake/c"; const B = "b" + c.C`,
759 "c/c.go": `package c; import "golang.org/fake/d"; const C = "c" + d.D`,
760 "d/d.go": `package d; import "golang.org/fake/e"; const D = "d" + e.E`,
761 "e/e.go": `package e; import "golang.org/fake/f"; const E = "e" + f.F`,
762 "f/f.go": `package f; const F = "f"`,
763 }}})
764 defer exported.Cleanup()
765
766 exported.Config.Mode = packages.NeedTypes | packages.NeedImports
767 initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c")
768 if err != nil {
769 t.Fatal(err)
770 }
771
772 graph, all := importGraph(initial)
773 wantGraph := `
774 * golang.org/fake/a
775 golang.org/fake/b
776 * golang.org/fake/c
777 golang.org/fake/d
778 golang.org/fake/e
779 golang.org/fake/f
780 golang.org/fake/a -> golang.org/fake/b
781 golang.org/fake/b -> golang.org/fake/c
782 golang.org/fake/c -> golang.org/fake/d
783 golang.org/fake/d -> golang.org/fake/e
784 golang.org/fake/e -> golang.org/fake/f
785 `[1:]
786 if graph != wantGraph {
787 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
788 }
789
790 for _, test := range []struct {
791 id string
792 }{
793 {"golang.org/fake/a"},
794 {"golang.org/fake/b"},
795 {"golang.org/fake/c"},
796 {"golang.org/fake/d"},
797 {"golang.org/fake/e"},
798 {"golang.org/fake/f"},
799 } {
800 p := all[test.id]
801 if p == nil {
802 t.Errorf("missing package: %s", test.id)
803 continue
804 }
805 if p.Types == nil {
806 t.Errorf("missing types.Package for %s", p)
807 continue
808 }
809 // We don't request the syntax, so we shouldn't get it.
810 if p.Syntax != nil {
811 t.Errorf("Syntax unexpectedly provided for %s", p)
812 }
813 if p.Errors != nil {
814 t.Errorf("errors in package: %s: %s", p, p.Errors)
815 }
816 }
817
818 // Check value of constant.
819 aA := constant(all["golang.org/fake/a"], "A")
820 if aA == nil {
821 t.Fatalf("a.A: got nil")
822 }
823 if got, want := fmt.Sprintf("%v %v", aA, aA.Val()), `const golang.org/fake/a.A untyped string "abcdef"`; got != want {
824 t.Errorf("a.A: got %s, want %s", got, want)
825 }
826 }
827
828 func TestLoadSyntaxOK(t *testing.T) { testAllOrModulesParallel(t, testLoadSyntaxOK) }
829 func testLoadSyntaxOK(t *testing.T, exporter packagestest.Exporter) {
830 exported := packagestest.Export(t, exporter, []packagestest.Module{{
831 Name: "golang.org/fake",
832 Files: map[string]any{
833 "a/a.go": `package a; import "golang.org/fake/b"; const A = "a" + b.B`,
834 "b/b.go": `package b; import "golang.org/fake/c"; const B = "b" + c.C`,
835 "c/c.go": `package c; import "golang.org/fake/d"; const C = "c" + d.D`,
836 "d/d.go": `package d; import "golang.org/fake/e"; const D = "d" + e.E`,
837 "e/e.go": `package e; import "golang.org/fake/f"; const E = "e" + f.F`,
838 "f/f.go": `package f; const F = "f"`,
839 }}})
840 defer exported.Cleanup()
841
842 exported.Config.Mode = packages.LoadSyntax
843 initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c")
844 if err != nil {
845 t.Fatal(err)
846 }
847
848 graph, all := importGraph(initial)
849 wantGraph := `
850 * golang.org/fake/a
851 golang.org/fake/b
852 * golang.org/fake/c
853 golang.org/fake/d
854 golang.org/fake/e
855 golang.org/fake/f
856 golang.org/fake/a -> golang.org/fake/b
857 golang.org/fake/b -> golang.org/fake/c
858 golang.org/fake/c -> golang.org/fake/d
859 golang.org/fake/d -> golang.org/fake/e
860 golang.org/fake/e -> golang.org/fake/f
861 `[1:]
862 if graph != wantGraph {
863 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
864 }
865
866 for _, test := range []struct {
867 id string
868 wantSyntax bool
869 wantComplete bool
870 }{
871 {"golang.org/fake/a", true, true}, // source package
872 {"golang.org/fake/b", true, true}, // source package because depends on initial package
873 {"golang.org/fake/c", true, true}, // source package
874 {"golang.org/fake/d", false, true}, // export data package
875 {"golang.org/fake/e", false, false}, // export data package
876 {"golang.org/fake/f", false, false}, // export data package
877 } {
878 // TODO(matloob): LoadSyntax and LoadAllSyntax are now equivalent, wantSyntax and wantComplete
879 // are true for all packages in the transitive dependency set. Add test cases on the individual
880 // Need* fields to check the equivalents on the new API.
881 p := all[test.id]
882 if p == nil {
883 t.Errorf("missing package: %s", test.id)
884 continue
885 }
886 if p.Types == nil {
887 t.Errorf("missing types.Package for %s", p)
888 continue
889 } else if p.Types.Complete() != test.wantComplete {
890 if test.wantComplete {
891 t.Errorf("incomplete types.Package for %s", p)
892 } else {
893 t.Errorf("unexpected complete types.Package for %s", p)
894 }
895 }
896 if (p.Syntax != nil) != test.wantSyntax {
897 if test.wantSyntax {
898 t.Errorf("missing ast.Files for %s", p)
899 } else {
900 t.Errorf("unexpected ast.Files for for %s", p)
901 }
902 }
903 if p.Errors != nil {
904 t.Errorf("errors in package: %s: %s", p, p.Errors)
905 }
906 }
907
908 // Check value of constant.
909 aA := constant(all["golang.org/fake/a"], "A")
910 if aA == nil {
911 t.Fatalf("a.A: got nil")
912 }
913 if got, want := fmt.Sprintf("%v %v", aA, aA.Val()), `const golang.org/fake/a.A untyped string "abcdef"`; got != want {
914 t.Errorf("a.A: got %s, want %s", got, want)
915 }
916 }
917
918 func TestLoadDiamondTypes(t *testing.T) { testAllOrModulesParallel(t, testLoadDiamondTypes) }
919 func testLoadDiamondTypes(t *testing.T, exporter packagestest.Exporter) {
920 // We make a diamond dependency and check the type d.D is the same through both paths
921 exported := packagestest.Export(t, exporter, []packagestest.Module{{
922 Name: "golang.org/fake",
923 Files: map[string]any{
924 "a/a.go": `package a; import ("golang.org/fake/b"; "golang.org/fake/c"); var _ = b.B == c.C`,
925 "b/b.go": `package b; import "golang.org/fake/d"; var B d.D`,
926 "c/c.go": `package c; import "golang.org/fake/d"; var C d.D`,
927 "d/d.go": `package d; type D int`,
928 }}})
929 defer exported.Cleanup()
930
931 exported.Config.Mode = packages.LoadSyntax
932 initial, err := packages.Load(exported.Config, "golang.org/fake/a")
933 if err != nil {
934 t.Fatal(err)
935 }
936 for pkg := range packages.Postorder(initial) {
937 for _, err := range pkg.Errors {
938 t.Errorf("package %s: %v", pkg.ID, err)
939 }
940 }
941
942 graph, _ := importGraph(initial)
943 wantGraph := `
944 * golang.org/fake/a
945 golang.org/fake/b
946 golang.org/fake/c
947 golang.org/fake/d
948 golang.org/fake/a -> golang.org/fake/b
949 golang.org/fake/a -> golang.org/fake/c
950 golang.org/fake/b -> golang.org/fake/d
951 golang.org/fake/c -> golang.org/fake/d
952 `[1:]
953 if graph != wantGraph {
954 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
955 }
956 }
957
958 func TestLoadSyntaxError(t *testing.T) { testAllOrModulesParallel(t, testLoadSyntaxError) }
959 func testLoadSyntaxError(t *testing.T, exporter packagestest.Exporter) {
960 // A type error in a lower-level package (e) prevents go list
961 // from producing export data for all packages that depend on it
962 // [a-e]. Only f should be loaded from export data, and the rest
963 // should be IllTyped.
964 exported := packagestest.Export(t, exporter, []packagestest.Module{{
965 Name: "golang.org/fake",
966 Files: map[string]any{
967 "a/a.go": `package a; import "golang.org/fake/b"; const A = "a" + b.B`,
968 "b/b.go": `package b; import "golang.org/fake/c"; const B = "b" + c.C`,
969 "c/c.go": `package c; import "golang.org/fake/d"; const C = "c" + d.D`,
970 "d/d.go": `package d; import "golang.org/fake/e"; const D = "d" + e.E`,
971 "e/e.go": `package e; import "golang.org/fake/f"; const E = "e" + f.F + 1`, // type error
972 "f/f.go": `package f; const F = "f"`,
973 }}})
974 defer exported.Cleanup()
975
976 exported.Config.Mode = packages.LoadSyntax
977 initial, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/c")
978 if err != nil {
979 t.Fatal(err)
980 }
981
982 all := make(map[string]*packages.Package)
983 for p := range packages.Postorder(initial) {
984 all[p.ID] = p
985 }
986
987 for _, test := range []struct {
988 id string
989 wantSyntax bool
990 wantIllTyped bool
991 }{
992 {"golang.org/fake/a", true, true},
993 {"golang.org/fake/b", true, true},
994 {"golang.org/fake/c", true, true},
995 {"golang.org/fake/d", true, true},
996 {"golang.org/fake/e", true, true},
997 {"golang.org/fake/f", false, false},
998 } {
999 p := all[test.id]
1000 if p == nil {
1001 t.Errorf("missing package: %s", test.id)
1002 continue
1003 }
1004 if p.Types == nil {
1005 t.Errorf("missing types.Package for %s", p)
1006 continue
1007 } else if !p.Types.Complete() {
1008 t.Errorf("incomplete types.Package for %s", p)
1009 }
1010 if (p.Syntax != nil) != test.wantSyntax {
1011 if test.wantSyntax {
1012 t.Errorf("missing ast.Files for %s", test.id)
1013 } else {
1014 t.Errorf("unexpected ast.Files for for %s", test.id)
1015 }
1016 }
1017 if p.IllTyped != test.wantIllTyped {
1018 t.Errorf("IllTyped was %t for %s", p.IllTyped, test.id)
1019 }
1020 }
1021
1022 // Check value of constant.
1023 aA := constant(all["golang.org/fake/a"], "A")
1024 if aA == nil {
1025 t.Fatalf("a.A: got nil")
1026 }
1027 if got, want := aA.String(), `const golang.org/fake/a.A invalid type`; got != want {
1028 t.Errorf("a.A: got %s, want %s", got, want)
1029 }
1030 }
1031
1032 // This function tests use of the ParseFile hook to modify
1033 // the AST after parsing.
1034 func TestParseFileModifyAST(t *testing.T) { testAllOrModulesParallel(t, testParseFileModifyAST) }
1035 func testParseFileModifyAST(t *testing.T, exporter packagestest.Exporter) {
1036 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1037 Name: "golang.org/fake",
1038 Files: map[string]any{
1039 "a/a.go": `package a; const A = "a" `,
1040 }}})
1041 defer exported.Cleanup()
1042
1043 exported.Config.Mode = packages.LoadAllSyntax
1044 exported.Config.ParseFile = func(fset *token.FileSet, filename string, src []byte) (*ast.File, error) {
1045 const mode = parser.AllErrors | parser.ParseComments
1046 f, err := parser.ParseFile(fset, filename, src, mode)
1047 // modify AST to change `const A = "a"` to `const A = "b"`
1048 spec := f.Decls[0].(*ast.GenDecl).Specs[0].(*ast.ValueSpec)
1049 spec.Values[0].(*ast.BasicLit).Value = `"b"`
1050 return f, err
1051 }
1052 initial, err := packages.Load(exported.Config, "golang.org/fake/a")
1053 if err != nil {
1054 t.Error(err)
1055 }
1056
1057 // Check value of a.A has been set to "b"
1058 a := initial[0]
1059 got := constant(a, "A").Val().String()
1060 if got != `"b"` {
1061 t.Errorf("a.A: got %s, want %s", got, `"b"`)
1062 }
1063 }
1064
1065 func TestAdHocPackagesBadImport(t *testing.T) {
1066 t.Parallel()
1067 testenv.NeedsTool(t, "go")
1068
1069 // This test doesn't use packagestest because we are testing ad-hoc packages,
1070 // which are outside of $GOPATH and outside of a module.
1071 tmp, err := os.MkdirTemp("", "a")
1072 if err != nil {
1073 t.Fatal(err)
1074 }
1075 defer os.RemoveAll(tmp)
1076
1077 filename := filepath.Join(tmp, "a.go")
1078 content := []byte(`package a
1079 import _ "badimport"
1080 const A = 1
1081 `)
1082 if err := os.WriteFile(filename, content, 0775); err != nil {
1083 t.Fatal(err)
1084 }
1085
1086 // Make sure that the user's value of GO111MODULE does not affect test results.
1087 for _, go111module := range []string{"off", "auto", "on"} {
1088 config := &packages.Config{
1089 Env: append(os.Environ(), "GOPACKAGESDRIVER=off", fmt.Sprintf("GO111MODULE=%s", go111module)),
1090 Dir: tmp,
1091 Mode: packages.LoadAllSyntax,
1092 Logf: t.Logf,
1093 }
1094 initial, err := packages.Load(config, fmt.Sprintf("file=%s", filename))
1095 if err != nil {
1096 t.Error(err)
1097 }
1098 if len(initial) == 0 {
1099 t.Fatalf("no packages for %s with GO111MODULE=%s", filename, go111module)
1100 }
1101 // Check value of a.A.
1102 a := initial[0]
1103 // There's an error because there's a bad import.
1104 aA := constant(a, "A")
1105 if aA == nil {
1106 t.Errorf("a.A: got nil")
1107 return
1108 }
1109 got := aA.Val().String()
1110 if want := "1"; got != want {
1111 t.Errorf("a.A: got %s, want %s", got, want)
1112 }
1113 }
1114 }
1115
1116 func TestLoadAllSyntaxImportErrors(t *testing.T) {
1117 testAllOrModulesParallel(t, testLoadAllSyntaxImportErrors)
1118 }
1119 func testLoadAllSyntaxImportErrors(t *testing.T, exporter packagestest.Exporter) {
1120 // TODO(matloob): Remove this once go list -e -compiled is fixed.
1121 // See https://golang.org/issue/26755
1122 t.Skip("go list -compiled -e fails with non-zero exit status for empty packages")
1123
1124 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1125 Name: "golang.org/fake",
1126 Files: map[string]any{
1127 "unicycle/unicycle.go": `package unicycle; import _ "unicycle"`,
1128 "bicycle1/bicycle1.go": `package bicycle1; import _ "bicycle2"`,
1129 "bicycle2/bicycle2.go": `package bicycle2; import _ "bicycle1"`,
1130 "bad/bad.go": `not a package declaration`,
1131 "empty/README.txt": `not a go file`,
1132 "root/root.go": `package root
1133 import (
1134 _ "bicycle1"
1135 _ "unicycle"
1136 _ "nonesuch"
1137 _ "empty"
1138 _ "bad"
1139 )`,
1140 }}})
1141 defer exported.Cleanup()
1142
1143 exported.Config.Mode = packages.LoadAllSyntax
1144 initial, err := packages.Load(exported.Config, "root")
1145 if err != nil {
1146 t.Fatal(err)
1147 }
1148
1149 // Cycle-forming edges are removed from the graph:
1150 // bicycle2 -> bicycle1
1151 // unicycle -> unicycle
1152 graph, all := importGraph(initial)
1153 wantGraph := `
1154 bicycle1
1155 bicycle2
1156 * root
1157 unicycle
1158 bicycle1 -> bicycle2
1159 root -> bicycle1
1160 root -> unicycle
1161 `[1:]
1162 if graph != wantGraph {
1163 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
1164 }
1165 for _, test := range []struct {
1166 id string
1167 wantErrs []string
1168 }{
1169 {"bicycle1", nil},
1170 {"bicycle2", []string{
1171 "could not import bicycle1 (import cycle: [root bicycle1 bicycle2])",
1172 }},
1173 {"unicycle", []string{
1174 "could not import unicycle (import cycle: [root unicycle])",
1175 }},
1176 {"root", []string{
1177 `could not import bad (missing package: "bad")`,
1178 `could not import empty (missing package: "empty")`,
1179 `could not import nonesuch (missing package: "nonesuch")`,
1180 }},
1181 } {
1182 p := all[test.id]
1183 if p == nil {
1184 t.Errorf("missing package: %s", test.id)
1185 continue
1186 }
1187 if p.Types == nil {
1188 t.Errorf("missing types.Package for %s", test.id)
1189 }
1190 if p.Syntax == nil {
1191 t.Errorf("missing ast.Files for %s", test.id)
1192 }
1193 if !p.IllTyped {
1194 t.Errorf("IllTyped was false for %s", test.id)
1195 }
1196 if errs := errorMessages(p.Errors); !reflect.DeepEqual(errs, test.wantErrs) {
1197 t.Errorf("in package %s, got errors %s, want %s", p, errs, test.wantErrs)
1198 }
1199 }
1200 }
1201
1202 func TestAbsoluteFilenames(t *testing.T) { testAllOrModulesParallel(t, testAbsoluteFilenames) }
1203 func testAbsoluteFilenames(t *testing.T, exporter packagestest.Exporter) {
1204 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1205 Name: "golang.org/fake",
1206 Files: map[string]any{
1207 "a/a.go": `package a; const A = 1`,
1208 "b/b.go": `package b; import ("golang.org/fake/a"; _ "errors"); var B = a.A`,
1209 "b/vendor/a/a.go": `package a; const A = 1`,
1210 "c/c.go": `package c; import (_ "golang.org/fake/b"; _ "unsafe")`,
1211 "c/c2.go": "// +build ignore\n\n" + `package c; import _ "fmt"`,
1212 "subdir/d/d.go": `package d`,
1213 "subdir/e/d.go": `package e`,
1214 "e/e.go": `package main; import _ "golang.org/fake/b"`,
1215 "e/e2.go": `package main; import _ "golang.org/fake/c"`,
1216 "f/f.go": `package f`,
1217 "f/f.s": ``,
1218 "g/g.go": `package g; import _ "embed";` + "\n//go:embed g2.txt\n" + `var s string`,
1219 "g/g2.txt": "hello",
1220 "h/h.go": `package g; import _ "embed";` + "\n//go:embed a*.txt\n" + `var s string`,
1221 "h/aa.txt": "hello",
1222 }}})
1223 defer exported.Cleanup()
1224 exported.Config.Dir = filepath.Dir(filepath.Dir(exported.File("golang.org/fake", "a/a.go")))
1225
1226 checkFile := func(filename string) {
1227 if !filepath.IsAbs(filename) {
1228 t.Errorf("filename is not absolute: %s", filename)
1229 }
1230 if _, err := os.Stat(filename); err != nil {
1231 t.Errorf("stat error, %s: %v", filename, err)
1232 }
1233 }
1234
1235 for _, test := range []struct {
1236 pattern string
1237 want string
1238 }{
1239 // Import paths
1240 {"golang.org/fake/a", "a.go"},
1241 {"golang.org/fake/b/vendor/a", "a.go"},
1242 {"golang.org/fake/b", "b.go"},
1243 {"golang.org/fake/c", "c.go"},
1244 {"golang.org/fake/subdir/d", "d.go"},
1245 {"golang.org/fake/subdir/e", "d.go"},
1246 {"golang.org/fake/e", "e.go e2.go"},
1247 {"golang.org/fake/f", "f.go f.s"},
1248 {"golang.org/fake/g", "g.go g2.txt"},
1249 {"golang.org/fake/h", "h.go aa.txt"},
1250 // Relative paths
1251 {"./a", "a.go"},
1252 {"./b/vendor/a", "a.go"},
1253 {"./b", "b.go"},
1254 {"./c", "c.go"},
1255 {"./subdir/d", "d.go"},
1256 {"./subdir/e", "d.go"},
1257 {"./e", "e.go e2.go"},
1258 {"./f", "f.go f.s"},
1259 {"./g", "g.go g2.txt"},
1260 {"./h", "h.go aa.txt"},
1261 } {
1262 exported.Config.Mode = packages.LoadFiles | packages.NeedEmbedFiles
1263 pkgs, err := packages.Load(exported.Config, test.pattern)
1264 if err != nil {
1265 t.Errorf("pattern %s: %v", test.pattern, err)
1266 continue
1267 }
1268
1269 if got := strings.Join(srcs(pkgs[0]), " "); got != test.want {
1270 t.Errorf("in package %s, got %s, want %s", test.pattern, got, test.want)
1271 }
1272
1273 // Test that files in all packages exist and are absolute paths.
1274 _, all := importGraph(pkgs)
1275 for _, pkg := range all {
1276 for _, filename := range pkg.GoFiles {
1277 checkFile(filename)
1278 }
1279 for _, filename := range pkg.OtherFiles {
1280 checkFile(filename)
1281 }
1282 for _, filename := range pkg.EmbedFiles {
1283 checkFile(filename)
1284 }
1285 for _, filename := range pkg.IgnoredFiles {
1286 checkFile(filename)
1287 }
1288 }
1289 }
1290 }
1291
1292 func TestContains(t *testing.T) { testAllOrModulesParallel(t, testContains) }
1293 func testContains(t *testing.T, exporter packagestest.Exporter) {
1294 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1295 Name: "golang.org/fake",
1296 Files: map[string]any{
1297 "a/a.go": `package a; import "golang.org/fake/b"`,
1298 "b/b.go": `package b; import "golang.org/fake/c"`,
1299 "c/c.go": `package c`,
1300 }}})
1301 defer exported.Cleanup()
1302 bFile := exported.File("golang.org/fake", "b/b.go")
1303 exported.Config.Mode = packages.LoadImports
1304 initial, err := packages.Load(exported.Config, "file="+bFile)
1305 if err != nil {
1306 t.Fatal(err)
1307 }
1308
1309 graph, _ := importGraph(initial)
1310 wantGraph := `
1311 * golang.org/fake/b
1312 golang.org/fake/c
1313 golang.org/fake/b -> golang.org/fake/c
1314 `[1:]
1315 if graph != wantGraph {
1316 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
1317 }
1318 }
1319
1320 // This test ensures that the effective GOARCH variable in the
1321 // application determines the Sizes function used by the type checker.
1322 // This behavior is a stop-gap until we make the build system's query
1323 // tool report the correct sizes function for the actual configuration.
1324 func TestSizes(t *testing.T) { testAllOrModulesParallel(t, testSizes) }
1325 func testSizes(t *testing.T, exporter packagestest.Exporter) {
1326 // Only run this test on operating systems that have both an amd64 and 386 port.
1327 switch runtime.GOOS {
1328 case "linux", "windows", "freebsd", "openbsd", "netbsd", "android":
1329 default:
1330 t.Skipf("skipping test on %s", runtime.GOOS)
1331 }
1332
1333 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1334 Name: "golang.org/fake",
1335 Files: map[string]any{
1336 "a/a.go": `package a; import "unsafe"; const WordSize = 8*unsafe.Sizeof(int(0))`,
1337 }}})
1338 defer exported.Cleanup()
1339
1340 exported.Config.Mode = packages.LoadSyntax
1341 savedEnv := exported.Config.Env
1342 for arch, wantWordSize := range map[string]int64{"386": 32, "amd64": 64} {
1343 exported.Config.Env = append(savedEnv, "GOARCH="+arch)
1344 initial, err := packages.Load(exported.Config, "golang.org/fake/a")
1345 if err != nil {
1346 t.Fatal(err)
1347 }
1348 if packages.PrintErrors(initial) > 0 {
1349 t.Fatal("there were errors")
1350 }
1351 gotWordSize, _ := constantpkg.Int64Val(constant(initial[0], "WordSize").Val())
1352 if gotWordSize != wantWordSize {
1353 t.Errorf("for GOARCH=%s, got word size %d, want %d", arch, gotWordSize, wantWordSize)
1354 }
1355 }
1356 }
1357
1358 // This is a regression test for a bug related to
1359 // github.com/golang/vscode-go/issues/3021: if types are needed (any
1360 // of NeedTypes{,Info,Sizes} and the types.Sizes cannot be obtained
1361 // (e.g. due to a bad GOARCH) then the Load operation must fail. It
1362 // must not return a nil TypesSizes, or use the default (wrong) size.
1363 // (The root cause of that issue turned out to be due to skew in the
1364 // Bazel GOPACKAGESDRIVER; see CL 537876.)
1365 //
1366 // We use a file=... query because it suppresses the bad-GOARCH check
1367 // that the go command would otherwise perform eagerly.
1368 // (Gopls relies on this as a fallback.)
1369 func TestNeedTypeSizesWithBadGOARCH(t *testing.T) {
1370 testAllOrModulesParallel(t, func(t *testing.T, exporter packagestest.Exporter) {
1371 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1372 Name: "testdata",
1373 Files: map[string]any{"a/a.go": `package a`}}})
1374 defer exported.Cleanup()
1375
1376 exported.Config.Mode = packages.NeedTypesSizes // or {,Info,Sizes}
1377 exported.Config.Env = append(exported.Config.Env, "GOARCH=286")
1378 _, err := packages.Load(exported.Config, "file=./a/a.go")
1379 got := fmt.Sprint(err)
1380 want := "can't determine type sizes"
1381 if !strings.Contains(got, want) {
1382 t.Errorf("Load error %q does not contain substring %q", got, want)
1383 }
1384 })
1385 }
1386
1387 // TestContainsFallbackSticks ensures that when there are both contains and non-contains queries
1388 // the decision whether to fallback to the pre-1.11 go list sticks across both sets of calls to
1389 // go list.
1390 func TestContainsFallbackSticks(t *testing.T) {
1391 testAllOrModulesParallel(t, testContainsFallbackSticks)
1392 }
1393 func testContainsFallbackSticks(t *testing.T, exporter packagestest.Exporter) {
1394 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1395 Name: "golang.org/fake",
1396 Files: map[string]any{
1397 "a/a.go": `package a; import "golang.org/fake/b"`,
1398 "b/b.go": `package b; import "golang.org/fake/c"`,
1399 "c/c.go": `package c`,
1400 }}})
1401 defer exported.Cleanup()
1402
1403 exported.Config.Mode = packages.LoadImports
1404 bFile := exported.File("golang.org/fake", "b/b.go")
1405 initial, err := packages.Load(exported.Config, "golang.org/fake/a", "file="+bFile)
1406 if err != nil {
1407 t.Fatal(err)
1408 }
1409
1410 graph, _ := importGraph(initial)
1411 wantGraph := `
1412 * golang.org/fake/a
1413 * golang.org/fake/b
1414 golang.org/fake/c
1415 golang.org/fake/a -> golang.org/fake/b
1416 golang.org/fake/b -> golang.org/fake/c
1417 `[1:]
1418 if graph != wantGraph {
1419 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
1420 }
1421 }
1422
1423 // Test that Load with no patterns is equivalent to loading "." via the golist
1424 // driver.
1425 func TestNoPatterns(t *testing.T) { testAllOrModulesParallel(t, testNoPatterns) }
1426 func testNoPatterns(t *testing.T, exporter packagestest.Exporter) {
1427 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1428 Name: "golang.org/fake",
1429 Files: map[string]any{
1430 "a/a.go": `package a;`,
1431 "a/b/b.go": `package b;`,
1432 }}})
1433 defer exported.Cleanup()
1434
1435 aDir := filepath.Dir(exported.File("golang.org/fake", "a/a.go"))
1436 exported.Config.Dir = aDir
1437
1438 initial, err := packages.Load(exported.Config)
1439 if err != nil {
1440 t.Fatal(err)
1441 }
1442 if len(initial) != 1 || initial[0].Name != "a" {
1443 t.Fatalf(`Load() = %v, wanted just the package in the current directory`, initial)
1444 }
1445 }
1446
1447 func TestJSON(t *testing.T) { testAllOrModulesParallel(t, testJSON) }
1448 func testJSON(t *testing.T, exporter packagestest.Exporter) {
1449 // TODO: add in some errors
1450 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1451 Name: "golang.org/fake",
1452 Files: map[string]any{
1453 "a/a.go": `package a; const A = 1`,
1454 "b/b.go": `package b; import "golang.org/fake/a"; var B = a.A`,
1455 "c/c.go": `package c; import "golang.org/fake/b" ; var C = b.B`,
1456 "d/d.go": `package d; import "golang.org/fake/b" ; var D = b.B`,
1457 }}})
1458 defer exported.Cleanup()
1459
1460 exported.Config.Mode = packages.LoadImports
1461 initial, err := packages.Load(exported.Config, "golang.org/fake/c", "golang.org/fake/d")
1462 if err != nil {
1463 t.Fatal(err)
1464 }
1465
1466 // Visit and print all packages.
1467 buf := &bytes.Buffer{}
1468 enc := json.NewEncoder(buf)
1469 enc.SetIndent("", "\t")
1470 for pkg := range packages.Postorder(initial) {
1471 // trim the source lists for stable results
1472 pkg.GoFiles = cleanPaths(pkg.GoFiles)
1473 pkg.CompiledGoFiles = cleanPaths(pkg.CompiledGoFiles)
1474 pkg.OtherFiles = cleanPaths(pkg.OtherFiles)
1475 pkg.IgnoredFiles = cleanPaths(pkg.IgnoredFiles)
1476 if err := enc.Encode(pkg); err != nil {
1477 t.Fatal(err)
1478 }
1479 }
1480
1481 wantJSON := `
1482 {
1483 "ID": "golang.org/fake/a",
1484 "Name": "a",
1485 "PkgPath": "golang.org/fake/a",
1486 "GoFiles": [
1487 "a.go"
1488 ],
1489 "CompiledGoFiles": [
1490 "a.go"
1491 ]
1492 }
1493 {
1494 "ID": "golang.org/fake/b",
1495 "Name": "b",
1496 "PkgPath": "golang.org/fake/b",
1497 "GoFiles": [
1498 "b.go"
1499 ],
1500 "CompiledGoFiles": [
1501 "b.go"
1502 ],
1503 "Imports": {
1504 "golang.org/fake/a": "golang.org/fake/a"
1505 }
1506 }
1507 {
1508 "ID": "golang.org/fake/c",
1509 "Name": "c",
1510 "PkgPath": "golang.org/fake/c",
1511 "GoFiles": [
1512 "c.go"
1513 ],
1514 "CompiledGoFiles": [
1515 "c.go"
1516 ],
1517 "Imports": {
1518 "golang.org/fake/b": "golang.org/fake/b"
1519 }
1520 }
1521 {
1522 "ID": "golang.org/fake/d",
1523 "Name": "d",
1524 "PkgPath": "golang.org/fake/d",
1525 "GoFiles": [
1526 "d.go"
1527 ],
1528 "CompiledGoFiles": [
1529 "d.go"
1530 ],
1531 "Imports": {
1532 "golang.org/fake/b": "golang.org/fake/b"
1533 }
1534 }
1535 `[1:]
1536
1537 if buf.String() != wantJSON {
1538 t.Errorf("wrong JSON: got <<%s>>, want <<%s>>", buf.String(), wantJSON)
1539 }
1540 // now decode it again
1541 var decoded []*packages.Package
1542 dec := json.NewDecoder(buf)
1543 for dec.More() {
1544 p := new(packages.Package)
1545 if err := dec.Decode(p); err != nil {
1546 t.Fatal(err)
1547 }
1548 decoded = append(decoded, p)
1549 }
1550 if len(decoded) != 4 {
1551 t.Fatalf("got %d packages, want 4", len(decoded))
1552 }
1553 for i, want := range []*packages.Package{{
1554 ID: "golang.org/fake/a",
1555 Name: "a",
1556 }, {
1557 ID: "golang.org/fake/b",
1558 Name: "b",
1559 Imports: map[string]*packages.Package{
1560 "golang.org/fake/a": {ID: "golang.org/fake/a"},
1561 },
1562 }, {
1563 ID: "golang.org/fake/c",
1564 Name: "c",
1565 Imports: map[string]*packages.Package{
1566 "golang.org/fake/b": {ID: "golang.org/fake/b"},
1567 },
1568 }, {
1569 ID: "golang.org/fake/d",
1570 Name: "d",
1571 Imports: map[string]*packages.Package{
1572 "golang.org/fake/b": {ID: "golang.org/fake/b"},
1573 },
1574 }} {
1575 got := decoded[i]
1576 if got.ID != want.ID {
1577 t.Errorf("Package %d has ID %q want %q", i, got.ID, want.ID)
1578 }
1579 if got.Name != want.Name {
1580 t.Errorf("Package %q has Name %q want %q", got.ID, got.Name, want.Name)
1581 }
1582 if len(got.Imports) != len(want.Imports) {
1583 t.Errorf("Package %q has %d imports want %d", got.ID, len(got.Imports), len(want.Imports))
1584 continue
1585 }
1586 for path, ipkg := range got.Imports {
1587 if want.Imports[path] == nil {
1588 t.Errorf("Package %q has unexpected import %q", got.ID, path)
1589 continue
1590 }
1591 if want.Imports[path].ID != ipkg.ID {
1592 t.Errorf("Package %q import %q is %q want %q", got.ID, path, ipkg.ID, want.Imports[path].ID)
1593 }
1594 }
1595 }
1596 }
1597
1598 func TestRejectInvalidQueries(t *testing.T) {
1599 t.Parallel()
1600
1601 queries := []string{"key=", "key=value"}
1602 cfg := &packages.Config{
1603 Mode: packages.LoadImports,
1604 Env: append(os.Environ(), "GO111MODULE=off", "GOPACKAGESDRIVER=off"),
1605 }
1606 for _, q := range queries {
1607 if _, err := packages.Load(cfg, q); err == nil {
1608 t.Errorf("packages.Load(%q) succeeded. Expected \"invalid query type\" error", q)
1609 } else if !strings.Contains(err.Error(), "invalid query type") {
1610 t.Errorf("packages.Load(%q): got error %v, want \"invalid query type\" error", q, err)
1611 }
1612 }
1613 }
1614
1615 func TestPatternPassthrough(t *testing.T) { testAllOrModulesParallel(t, testPatternPassthrough) }
1616 func testPatternPassthrough(t *testing.T, exporter packagestest.Exporter) {
1617 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1618 Name: "golang.org/fake",
1619 Files: map[string]any{
1620 "a/a.go": `package a;`,
1621 }}})
1622 defer exported.Cleanup()
1623
1624 initial, err := packages.Load(exported.Config, "pattern=a")
1625 if err != nil {
1626 t.Fatal(err)
1627 }
1628
1629 graph, _ := importGraph(initial)
1630 wantGraph := `
1631 * a
1632 `[1:]
1633 if graph != wantGraph {
1634 t.Errorf("wrong import graph: got <<%s>>, want <<%s>>", graph, wantGraph)
1635 }
1636
1637 }
1638
1639 // TestDriver tests various configurations of default driver
1640 // (go list) and alternative drivers specified explicitly via
1641 // GOPACKAGESDRIVER or implicitly via $(which gopackagesdriver).
1642 func TestDriver(t *testing.T) {
1643 // packagestest.TestAll instead of testAllOrModulesParallel because this test
1644 // can't be parallelized (it modifies the environment).
1645 packagestest.TestAll(t, testDriver)
1646 }
1647
1648 func testDriver(t *testing.T, exporter packagestest.Exporter) {
1649 testenv.NeedsTool(t, "go")
1650
1651 // Copy the current test executable to a temp dir.
1652 // We'll use it as a GOPACKAGESDRIVER.
1653 exe, err := os.Executable()
1654 if err != nil {
1655 t.Fatal(err)
1656 }
1657 gopackagesdriver := filepath.Join(t.TempDir(), "gopackagesdriver"+cond(runtime.GOOS == "windows", ".exe", ""))
1658 if err := copyfile(gopackagesdriver, exe); err != nil {
1659 t.Fatal(err)
1660 }
1661
1662 sanitize := func(s string) string {
1663 return strings.ReplaceAll(s, filepath.Dir(gopackagesdriver), "PATH")
1664 }
1665
1666 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1667 Name: "golang.org/fake",
1668 Files: map[string]any{
1669 "golist/golist.go": "package golist",
1670 }}})
1671 defer exported.Cleanup()
1672
1673 for _, test := range []struct {
1674 desc string
1675 onpath bool // whether gopackagesdriver's directory is on the PATH
1676 gopackagesdriver string // value of GOPACKAGESDRIVER seen by packages.Load ("" and unset are equivalent)
1677 entrypoint string // value of ENTRYPOINT var to be seen by driver executable
1678 want string // expected list of package IDs, or "error: regexp" matching message
1679 }{
1680 // -- tests of driver selection --
1681 {
1682 // GOPACKAGESDRIVER unset, no driver on path: executes go list.
1683 desc: "default",
1684 want: "[golist]",
1685 },
1686 {
1687 // GOPACKAGESDRIVER=off executes go list, not driver on the PATH.
1688 desc: "driver-explicitly-off",
1689 onpath: true,
1690 gopackagesdriver: "off",
1691 entrypoint: "nope",
1692 want: "[golist]",
1693 },
1694 {
1695 // GOPACKAGESDRIVER=exe runs the specified executable.
1696 desc: "driver-set-via-environment",
1697 onpath: false,
1698 gopackagesdriver: gopackagesdriver,
1699 entrypoint: "driver1",
1700 want: "[gopackagesdriver]",
1701 },
1702 {
1703 // GOPACKAGESDRIVER set to nonexistent does not look up 'gopackagesdriver' on the PATH
1704 desc: "driver-not-found-on-path",
1705 onpath: true,
1706 gopackagesdriver: gopackagesdriver + "nonesuch",
1707 entrypoint: "driver1",
1708 want: "error: no such file|file does not exist",
1709 },
1710 // -- tests of driver response payload --
1711 {
1712 // GOPACKAGESDRIVER denotes a driver that returns duplicate IDs
1713 desc: "driver-returns-duplicate-IDs",
1714 gopackagesdriver: gopackagesdriver,
1715 entrypoint: "driver2",
1716 want: `error: go/packages driver response contained duplicate packages for ID "a"`,
1717 },
1718 } {
1719 t.Run(test.desc, func(t *testing.T) {
1720 // Defend against recursive exec due to forgotten entrypoint.
1721 if test.gopackagesdriver != "" && test.entrypoint == "" {
1722 t.Fatalf("missing entrypoint")
1723 }
1724
1725 if test.onpath {
1726 pathVar := cond(runtime.GOOS == "plan9", "path", "PATH")
1727 t.Setenv(pathVar, filepath.Dir(gopackagesdriver)+string(os.PathListSeparator)+os.Getenv(pathVar))
1728 }
1729
1730 // Clone and update the config.
1731 config := *exported.Config
1732 config.Env = slices.Clone(exported.Config.Env)
1733 config.Env = append(config.Env,
1734 "GOPACKAGESDRIVER="+test.gopackagesdriver,
1735 "ENTRYPOINT="+test.entrypoint)
1736
1737 pattern, wantErr := strings.CutPrefix(test.want, "error: ")
1738
1739 // We request golist, but that's
1740 // not necessarily what we get back.
1741 pkgs, err := packages.Load(&config, "golist")
1742 if err != nil {
1743 errStr := sanitize(err.Error())
1744 if wantErr {
1745 if m, err := regexp.MatchString(pattern, errStr); err != nil {
1746 t.Fatalf("bad 'want' pattern: %v", err)
1747 } else if m {
1748 return // success
1749 }
1750 t.Fatalf("Load failed with wrong error: %q, want match for %q", errStr, pattern)
1751 }
1752 t.Fatalf("Load failed: %v", errStr)
1753 }
1754 if wantErr {
1755 t.Errorf("Load succeeded unexpectedly, want error matching %q", pattern)
1756 }
1757
1758 gotIds := make([]string, len(pkgs))
1759 for i, pkg := range pkgs {
1760 gotIds[i] = pkg.ID
1761 }
1762 got := sanitize(fmt.Sprint(pkgs))
1763 if got != test.want {
1764 t.Errorf("got %s, want %s", got, test.want)
1765 }
1766 })
1767 }
1768 }
1769
1770 // driver1 returns a single package.
1771 func driver1() {
1772 fmt.Println(`{"Roots": ["gopackagesdriver"], "Packages": [{"ID": "gopackagesdriver", "Name": "gopackagesdriver"}]}`)
1773 }
1774
1775 // driver2 returns two package with the same ID.
1776 func driver2() {
1777 fmt.Println(`{"Roots": ["a", "b", "c"], "Packages": [
1778 {"ID": "a", "Name": "a"},
1779 {"ID": "b", "Name": "b"},
1780 {"ID": "c", "Name": "c"},
1781 {"ID": "a", "Name": "a"}
1782 ]}`)
1783 }
1784
1785 // copyfile copies a file from src to dst.
1786 func copyfile(dst, src string) error {
1787 srcf, err := os.Open(src)
1788 if err != nil {
1789 return err
1790 }
1791 defer srcf.Close()
1792 fi, err := srcf.Stat()
1793 if err != nil {
1794 return err
1795 }
1796 dstf, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, fi.Mode())
1797 if err != nil {
1798 return err
1799 }
1800 if _, err := io.Copy(dstf, srcf); err != nil {
1801 dstf.Close() // ignore error
1802 return err
1803 }
1804 return dstf.Close()
1805 }
1806
1807 // This test that a simple x test package layout loads correctly.
1808 // There was a bug in go list where it returned multiple copies of the same
1809 // package (specifically in this case of golang.org/fake/a), and this triggered
1810 // a bug in go/packages where it would leave an empty entry in the root package
1811 // list. This would then cause a nil pointer crash.
1812 // This bug was triggered by the simple package layout below, and thus this
1813 // test will make sure the bug remains fixed.
1814 func TestBasicXTest(t *testing.T) { testAllOrModulesParallel(t, testBasicXTest) }
1815 func testBasicXTest(t *testing.T, exporter packagestest.Exporter) {
1816 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1817 Name: "golang.org/fake",
1818 Files: map[string]any{
1819 "a/a.go": `package a;`,
1820 "a/a_test.go": `package a_test;`,
1821 }}})
1822 defer exported.Cleanup()
1823
1824 exported.Config.Mode = packages.LoadFiles
1825 exported.Config.Tests = true
1826 _, err := packages.Load(exported.Config, "golang.org/fake/a")
1827 if err != nil {
1828 t.Fatal(err)
1829 }
1830 }
1831
1832 func TestErrorMissingFile(t *testing.T) { testAllOrModulesParallel(t, testErrorMissingFile) }
1833 func testErrorMissingFile(t *testing.T, exporter packagestest.Exporter) {
1834 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1835 Name: "golang.org/fake",
1836 Files: map[string]any{
1837 "a/a_test.go": `package a;`,
1838 }}})
1839 defer exported.Cleanup()
1840
1841 exported.Config.Mode = packages.LoadSyntax
1842 exported.Config.Tests = false
1843 pkgs, err := packages.Load(exported.Config, "missing.go")
1844 if err != nil {
1845 t.Fatal(err)
1846 }
1847 if len(pkgs) == 0 && runtime.GOOS == "windows" {
1848 t.Skip("Issue #31344: the ad-hoc command-line-arguments package isn't created on windows")
1849 }
1850 if len(pkgs) != 1 || (pkgs[0].PkgPath != "command-line-arguments" && pkgs[0].PkgPath != "missing.go") {
1851 t.Fatalf("packages.Load: want [command-line-arguments] or [missing.go], got %v", pkgs)
1852 }
1853 if len(pkgs[0].Errors) == 0 {
1854 t.Errorf("result of Load: want package with errors, got none: %+v", pkgs[0])
1855 }
1856 }
1857
1858 func TestReturnErrorWhenUsingNonGoFiles(t *testing.T) {
1859 testAllOrModulesParallel(t, testReturnErrorWhenUsingNonGoFiles)
1860 }
1861 func testReturnErrorWhenUsingNonGoFiles(t *testing.T, exporter packagestest.Exporter) {
1862 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1863 Name: "golang.org/gopatha",
1864 Files: map[string]any{
1865 "a/a.go": `package a`,
1866 }}, {
1867 Name: "golang.org/gopathb",
1868 Files: map[string]any{
1869 "b/b.c": `package b`,
1870 }}})
1871 defer exported.Cleanup()
1872 config := packages.Config{Env: append(os.Environ(), "GOPACKAGESDRIVER=off")}
1873 pkgs, err := packages.Load(&config, "b/b.c")
1874 if err != nil {
1875 return
1876 }
1877 // Go <1.14 calls the package command-line-arguments while Go 1.14+ uses the file names.
1878 if len(pkgs) != 1 || (pkgs[0].PkgPath != "command-line-arguments" && pkgs[0].PkgPath != "b/b.c") {
1879 t.Fatalf("packages.Load: want [command-line-arguments] or [b/b.c], got %v", pkgs)
1880 }
1881 if len(pkgs[0].Errors) != 1 {
1882 t.Fatalf("result of Load: want package with one error, got: %+v", pkgs[0])
1883 }
1884 }
1885
1886 func TestReturnErrorWhenUsingGoFilesInMultipleDirectories(t *testing.T) {
1887 testAllOrModulesParallel(t, testReturnErrorWhenUsingGoFilesInMultipleDirectories)
1888 }
1889 func testReturnErrorWhenUsingGoFilesInMultipleDirectories(t *testing.T, exporter packagestest.Exporter) {
1890 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1891 Name: "golang.org/gopatha",
1892 Files: map[string]any{
1893 "a/a.go": `package a`,
1894 "b/b.go": `package b`,
1895 }}})
1896 defer exported.Cleanup()
1897 want := "named files must all be in one directory"
1898 pkgs, err := packages.Load(exported.Config, exported.File("golang.org/gopatha", "a/a.go"), exported.File("golang.org/gopatha", "b/b.go"))
1899 if err != nil {
1900 // Check if the error returned is the one we expected.
1901 if !strings.Contains(err.Error(), want) {
1902 t.Fatalf("want error message: %s, got: %s", want, err.Error())
1903 }
1904 return
1905 }
1906 if len(pkgs) != 1 || pkgs[0].PkgPath != "command-line-arguments" {
1907 t.Fatalf("packages.Load: want [command-line-arguments], got %v", pkgs)
1908 }
1909 if len(pkgs[0].Errors) != 1 {
1910 t.Fatalf("result of Load: want package with one error, got: %+v", pkgs[0])
1911 }
1912 got := pkgs[0].Errors[0].Error()
1913 if !strings.Contains(got, want) {
1914 t.Fatalf("want error message: %s, got: %s", want, got)
1915 }
1916 }
1917
1918 func TestReturnErrorForUnexpectedDirectoryLayout(t *testing.T) {
1919 testAllOrModulesParallel(t, testReturnErrorForUnexpectedDirectoryLayout)
1920 }
1921 func testReturnErrorForUnexpectedDirectoryLayout(t *testing.T, exporter packagestest.Exporter) {
1922 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1923 Name: "golang.org/gopatha",
1924 Files: map[string]any{
1925 "a/testdata/a.go": `package a; import _ "b"`,
1926 "a/vendor/b/b.go": `package b; import _ "fmt"`,
1927 }}})
1928 defer exported.Cleanup()
1929 want := "unexpected directory layout"
1930 // triggering this error requires a relative package path
1931 exported.Config.Dir = filepath.Dir(exported.File("golang.org/gopatha", "a/testdata/a.go"))
1932 pkgs, err := packages.Load(exported.Config, ".")
1933
1934 // This error doesn't seem to occur in module mode; so only
1935 // complain if we get zero packages while also getting no error.
1936 if err == nil {
1937 if len(pkgs) == 0 {
1938 // TODO(dh): we'll need to expand on the error check if/when Go stops emitting this error
1939 t.Fatalf("want error, got nil")
1940 }
1941 return
1942 }
1943 // Check if the error returned is the one we expected.
1944 if !strings.Contains(err.Error(), want) {
1945 t.Fatalf("want error message: %s, got: %s", want, err.Error())
1946 }
1947 }
1948
1949 func TestMissingDependency(t *testing.T) { testAllOrModulesParallel(t, testMissingDependency) }
1950 func testMissingDependency(t *testing.T, exporter packagestest.Exporter) {
1951 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1952 Name: "golang.org/fake",
1953 Files: map[string]any{
1954 "a/a.go": `package a; import _ "this/package/doesnt/exist"`,
1955 }}})
1956 defer exported.Cleanup()
1957
1958 exported.Config.Mode = packages.LoadAllSyntax
1959 pkgs, err := packages.Load(exported.Config, "golang.org/fake/a")
1960 if err != nil {
1961 t.Fatal(err)
1962 }
1963 if len(pkgs) != 1 && pkgs[0].PkgPath != "golang.org/fake/a" {
1964 t.Fatalf("packages.Load: want [golang.org/fake/a], got %v", pkgs)
1965 }
1966 if len(pkgs[0].Errors) == 0 {
1967 t.Errorf("result of Load: want package with errors, got none: %+v", pkgs[0])
1968 }
1969 }
1970
1971 func TestAdHocContains(t *testing.T) { testAllOrModulesParallel(t, testAdHocContains) }
1972 func testAdHocContains(t *testing.T, exporter packagestest.Exporter) {
1973 exported := packagestest.Export(t, exporter, []packagestest.Module{{
1974 Name: "golang.org/fake",
1975 Files: map[string]any{
1976 "a/a.go": `package a;`,
1977 }}})
1978 defer exported.Cleanup()
1979
1980 tmpfile, err := os.CreateTemp("", "adhoc*.go")
1981 filename := tmpfile.Name()
1982 if err != nil {
1983 t.Fatal(err)
1984 }
1985 fmt.Fprint(tmpfile, `package main; import "fmt"; func main() { fmt.Println("time for coffee") }`)
1986 if err := tmpfile.Close(); err != nil {
1987 t.Fatal(err)
1988 }
1989
1990 defer func() {
1991 if err := os.Remove(filename); err != nil {
1992 t.Fatal(err)
1993 }
1994 }()
1995
1996 exported.Config.Mode = packages.NeedImports | packages.NeedFiles
1997 pkgs, err := packages.Load(exported.Config, "file="+filename)
1998 if err != nil {
1999 t.Fatal(err)
2000 }
2001 if len(pkgs) != 1 && pkgs[0].PkgPath != "command-line-arguments" {
2002 t.Fatalf("packages.Load: want [command-line-arguments], got %v", pkgs)
2003 }
2004 pkg := pkgs[0]
2005 if _, ok := pkg.Imports["fmt"]; !ok || len(pkg.Imports) != 1 {
2006 t.Fatalf("Imports of loaded package: want [fmt], got %v", pkg.Imports)
2007 }
2008 if len(pkg.GoFiles) != 1 || pkg.GoFiles[0] != filename {
2009 t.Fatalf("GoFiles of loaded package: want [%s], got %v", filename, pkg.GoFiles)
2010 }
2011 }
2012
2013 func TestCgoNoCcompiler(t *testing.T) { testAllOrModulesParallel(t, testCgoNoCcompiler) }
2014 func testCgoNoCcompiler(t *testing.T, exporter packagestest.Exporter) {
2015 testenv.NeedsTool(t, "cgo")
2016 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2017 Name: "golang.org/fake",
2018 Files: map[string]any{
2019 "a/a.go": `package a
2020 import "net/http"
2021 const A = http.MethodGet
2022 `,
2023 }}})
2024 defer exported.Cleanup()
2025
2026 // Explicitly enable cgo but configure a nonexistent C compiler.
2027 exported.Config.Env = append(exported.Config.Env, "CGO_ENABLED=1", "CC=doesnotexist")
2028 exported.Config.Mode = packages.LoadAllSyntax
2029 initial, err := packages.Load(exported.Config, "golang.org/fake/a")
2030
2031 if err != nil {
2032 t.Fatal(err)
2033 }
2034
2035 // Check value of a.A.
2036 a := initial[0]
2037 aA := constant(a, "A")
2038 if aA == nil {
2039 t.Fatalf("a.A: got nil")
2040 }
2041 got := aA.Val().String()
2042 if got != "\"GET\"" {
2043 t.Errorf("a.A: got %s, want %s", got, "\"GET\"")
2044 }
2045 }
2046
2047 func TestCgoMissingFile(t *testing.T) { testAllOrModulesParallel(t, testCgoMissingFile) }
2048 func testCgoMissingFile(t *testing.T, exporter packagestest.Exporter) {
2049 testenv.NeedsTool(t, "cgo")
2050 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2051 Name: "golang.org/fake",
2052 Files: map[string]any{
2053 "a/a.go": `package a
2054
2055 // #include "foo.h"
2056 import "C"
2057
2058 const A = 4
2059 `,
2060 }}})
2061 defer exported.Cleanup()
2062
2063 // Explicitly enable cgo.
2064 exported.Config.Env = append(exported.Config.Env, "CGO_ENABLED=1")
2065 exported.Config.Mode = packages.LoadAllSyntax
2066 initial, err := packages.Load(exported.Config, "golang.org/fake/a")
2067
2068 if err != nil {
2069 t.Fatal(err)
2070 }
2071
2072 // Check value of a.A.
2073 a := initial[0]
2074 aA := constant(a, "A")
2075 if aA == nil {
2076 t.Fatalf("a.A: got nil")
2077 }
2078 got := aA.Val().String()
2079 if got != "4" {
2080 t.Errorf("a.A: got %s, want %s", got, "4")
2081 }
2082 }
2083
2084 func TestLoadImportsC(t *testing.T) {
2085 // This test checks that when a package depends on the
2086 // test variant of "syscall", "unsafe", or "runtime/cgo", that dependency
2087 // is not removed when those packages are added when it imports "C".
2088 //
2089 // For this test to work, the external test of syscall must have a dependency
2090 // on net, and net must import "syscall" and "C".
2091 if runtime.GOOS == "windows" {
2092 t.Skipf("skipping on windows; packages on windows do not satisfy conditions for test.")
2093 }
2094 if runtime.GOOS == "plan9" {
2095 // See https://golang.org/issue/27100.
2096 t.Skip(`skipping on plan9; for some reason "net [syscall.test]" is not loaded`)
2097 }
2098 t.Parallel()
2099 testenv.NeedsGoPackages(t)
2100
2101 cfg := &packages.Config{
2102 Context: t.Context(),
2103 Mode: packages.LoadImports,
2104 Tests: true,
2105 }
2106 initial, err := packages.Load(cfg, "syscall", "net")
2107 if err != nil {
2108 t.Fatalf("failed to load imports: %v", err)
2109 }
2110
2111 _, all := importGraph(initial)
2112
2113 for _, test := range []struct {
2114 pattern string
2115 wantImport string // an import to check for
2116 }{
2117 {"net", "syscall:syscall"},
2118 {"net [syscall.test]", "syscall:syscall [syscall.test]"},
2119 {"syscall_test [syscall.test]", "net:net [syscall.test]"},
2120 } {
2121 // Test the import paths.
2122 pkg := all[test.pattern]
2123 if pkg == nil {
2124 t.Errorf("package %q not loaded", test.pattern)
2125 continue
2126 }
2127 if imports := strings.Join(imports(pkg), " "); !strings.Contains(imports, test.wantImport) {
2128 t.Errorf("package %q: got \n%s, \nwant to have %s", test.pattern, imports, test.wantImport)
2129 }
2130 }
2131 }
2132
2133 func TestCgoNoSyntax(t *testing.T) {
2134 testAllOrModulesParallel(t, testCgoNoSyntax)
2135 }
2136 func testCgoNoSyntax(t *testing.T, exporter packagestest.Exporter) {
2137 testenv.NeedsTool(t, "cgo")
2138
2139 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2140 Name: "golang.org/fake",
2141 Files: map[string]any{
2142 "c/c.go": `package c; import "C"`,
2143 },
2144 }})
2145
2146 // Explicitly enable cgo.
2147 exported.Config.Env = append(exported.Config.Env, "CGO_ENABLED=1")
2148
2149 modes := []packages.LoadMode{
2150 packages.NeedTypes,
2151 packages.NeedName | packages.NeedTypes,
2152 packages.NeedName | packages.NeedTypes | packages.NeedImports,
2153 packages.NeedName | packages.NeedTypes | packages.NeedImports | packages.NeedDeps,
2154 packages.NeedName | packages.NeedImports,
2155 }
2156 for _, mode := range modes {
2157 t.Run(fmt.Sprint(mode), func(t *testing.T) {
2158 exported.Config.Mode = mode
2159 pkgs, err := packages.Load(exported.Config, "golang.org/fake/c")
2160 if err != nil {
2161 t.Fatal(err)
2162 }
2163 if len(pkgs) != 1 {
2164 t.Fatalf("Expected 1 package, got %v", pkgs)
2165 }
2166 pkg := pkgs[0]
2167 if len(pkg.Errors) != 0 {
2168 t.Fatalf("Expected no errors in package, got %v", pkg.Errors)
2169 }
2170 })
2171 }
2172 }
2173
2174 func TestCgoBadPkgConfig(t *testing.T) {
2175 testAllOrModulesParallel(t, testCgoBadPkgConfig)
2176 }
2177 func testCgoBadPkgConfig(t *testing.T, exporter packagestest.Exporter) {
2178 skipIfShort(t, "builds and links a fake pkgconfig binary")
2179 testenv.NeedsTool(t, "cgo")
2180
2181 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2182 Name: "golang.org/fake",
2183 Files: map[string]any{
2184 "c/c.go": `package c
2185
2186 // #cgo pkg-config: --cflags -- foo
2187 import "C"`,
2188 },
2189 }})
2190
2191 dir := buildFakePkgconfig(t, exported.Config.Env)
2192 defer os.RemoveAll(dir)
2193 env := exported.Config.Env
2194 for i, v := range env {
2195 if strings.HasPrefix(v, "PATH=") {
2196 env[i] = "PATH=" + dir + string(os.PathListSeparator) + v[len("PATH="):]
2197 }
2198 }
2199
2200 exported.Config.Env = append(exported.Config.Env, "CGO_ENABLED=1")
2201
2202 exported.Config.Mode = packages.NeedName | packages.NeedCompiledGoFiles
2203 pkgs, err := packages.Load(exported.Config, "golang.org/fake/c")
2204 if err != nil {
2205 t.Fatal(err)
2206 }
2207 if len(pkgs) != 1 {
2208 t.Fatalf("Expected 1 package, got %v", pkgs)
2209 }
2210 if pkgs[0].Name != "c" {
2211 t.Fatalf("Expected package to have name \"c\", got %q", pkgs[0].Name)
2212 }
2213 }
2214
2215 func buildFakePkgconfig(t *testing.T, env []string) string {
2216 tmpdir, err := os.MkdirTemp("", "fakepkgconfig")
2217 if err != nil {
2218 t.Fatal(err)
2219 }
2220 err = os.WriteFile(filepath.Join(tmpdir, "pkg-config.go"), []byte(`
2221 package main
2222
2223 import "fmt"
2224 import "os"
2225
2226 func main() {
2227 fmt.Fprintln(os.Stderr, "bad")
2228 os.Exit(2)
2229 }
2230 `), 0644)
2231 if err != nil {
2232 os.RemoveAll(tmpdir)
2233 t.Fatal(err)
2234 }
2235 cmd := exec.Command("go", "build", "-o", "pkg-config", "pkg-config.go")
2236 cmd.Dir = tmpdir
2237 cmd.Env = env
2238
2239 if b, err := cmd.CombinedOutput(); err != nil {
2240 os.RemoveAll(tmpdir)
2241 fmt.Println(os.Environ())
2242 t.Log(string(b))
2243 t.Fatal(err)
2244 }
2245 return tmpdir
2246 }
2247
2248 func TestIssue32814(t *testing.T) { testAllOrModulesParallel(t, testIssue32814) }
2249 func testIssue32814(t *testing.T, exporter packagestest.Exporter) {
2250 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2251 Name: "golang.org/fake",
2252 Files: map[string]any{}}})
2253 defer exported.Cleanup()
2254
2255 exported.Config.Mode = packages.NeedName | packages.NeedTypes | packages.NeedSyntax | packages.NeedTypesInfo | packages.NeedTypesSizes
2256 pkgs, err := packages.Load(exported.Config, "fmt")
2257
2258 if err != nil {
2259 t.Fatal(err)
2260 }
2261
2262 if len(pkgs) != 1 && pkgs[0].PkgPath != "fmt" {
2263 t.Fatalf("packages.Load: want [fmt], got %v", pkgs)
2264 }
2265 pkg := pkgs[0]
2266 if len(pkg.Errors) != 0 {
2267 t.Fatalf("Errors for fmt pkg: got %v, want none", pkg.Errors)
2268 }
2269 if !pkg.Types.Complete() {
2270 t.Fatalf("Types.Complete() for fmt pkg: got %v, want true", pkgs[0].Types.Complete())
2271
2272 }
2273 }
2274
2275 func TestLoadTypesInfoWithoutNeedDeps(t *testing.T) {
2276 testAllOrModulesParallel(t, testLoadTypesInfoWithoutNeedDeps)
2277 }
2278 func testLoadTypesInfoWithoutNeedDeps(t *testing.T, exporter packagestest.Exporter) {
2279 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2280 Name: "golang.org/fake",
2281 Files: map[string]any{
2282 "a/a.go": `package a; import _ "golang.org/fake/b"`,
2283 "b/b.go": `package b`,
2284 }}})
2285 defer exported.Cleanup()
2286
2287 exported.Config.Mode = packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports
2288 pkgs, err := packages.Load(exported.Config, "golang.org/fake/a")
2289 if err != nil {
2290 t.Fatal(err)
2291 }
2292 pkg := pkgs[0]
2293 if pkg.IllTyped {
2294 t.Fatal("Loaded package is ill typed")
2295 }
2296 const expectedImport = "golang.org/fake/b"
2297 if _, ok := pkg.Imports[expectedImport]; !ok || len(pkg.Imports) != 1 {
2298 t.Fatalf("Imports of loaded package: want [%s], got %v", expectedImport, pkg.Imports)
2299 }
2300 }
2301
2302 func TestLoadWithNeedDeps(t *testing.T) {
2303 testAllOrModulesParallel(t, testLoadWithNeedDeps)
2304 }
2305 func testLoadWithNeedDeps(t *testing.T, exporter packagestest.Exporter) {
2306 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2307 Name: "golang.org/fake",
2308 Files: map[string]any{
2309 "a/a.go": `package a; import _ "golang.org/fake/b"`,
2310 "b/b.go": `package b; import _ "golang.org/fake/c"`,
2311 "c/c.go": `package c`,
2312 }}})
2313 defer exported.Cleanup()
2314
2315 exported.Config.Mode = packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports | packages.NeedDeps
2316 pkgs, err := packages.Load(exported.Config, "golang.org/fake/a")
2317 if err != nil {
2318 t.Fatal(err)
2319 }
2320 if len(pkgs) != 1 {
2321 t.Fatalf("Expected 1 package, got %d", len(pkgs))
2322 }
2323
2324 pkgA := pkgs[0]
2325 if pkgA.IllTyped {
2326 t.Fatal("Loaded package is ill typed")
2327 }
2328
2329 pkgB := pkgA.Imports["golang.org/fake/b"]
2330 if pkgB == nil || len(pkgA.Imports) != 1 {
2331 t.Fatalf("Imports of loaded package 'a' are invalid: %v", pkgA.Imports)
2332 }
2333 if pkgB.Types == nil || !pkgB.Types.Complete() || pkgB.TypesInfo == nil {
2334 t.Fatalf("Types of package 'b' are nil or incomplete: %v, %v", pkgB.Types, pkgB.TypesInfo)
2335 }
2336
2337 pkgC := pkgB.Imports["golang.org/fake/c"]
2338 if pkgC == nil || len(pkgB.Imports) != 1 {
2339 t.Fatalf("Imports of loaded package 'c' are invalid: %v", pkgB.Imports)
2340 }
2341 if pkgC.Types == nil || !pkgC.Types.Complete() || pkgC.TypesInfo == nil {
2342 t.Fatalf("Types of package 'b' are nil or incomplete: %v, %v", pkgC.Types, pkgC.TypesInfo)
2343 }
2344 }
2345
2346 func TestImpliedLoadMode(t *testing.T) {
2347 testAllOrModulesParallel(t, testImpliedLoadMode)
2348 }
2349 func testImpliedLoadMode(t *testing.T, exporter packagestest.Exporter) {
2350 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2351 Name: "golang.org/fake",
2352 Files: map[string]any{
2353 "a/a.go": `package a; import _ "golang.org/fake/b"`,
2354 "b/b.go": `package b`,
2355 }}})
2356 defer exported.Cleanup()
2357
2358 exported.Config.Mode = packages.NeedTypes | packages.NeedTypesInfo
2359 pkgs, err := packages.Load(exported.Config, "golang.org/fake/a")
2360 if err != nil {
2361 t.Fatal(err)
2362 }
2363 if len(pkgs) != 1 {
2364 t.Fatalf("Expected 1 package, got %d", len(pkgs))
2365 }
2366
2367 pkg := pkgs[0]
2368 if pkg.IllTyped {
2369 t.Fatalf("Loaded package is ill typed: %v", pkg.Errors)
2370 }
2371
2372 // Check that packages.NeedTypesInfo worked well.
2373 if !pkg.Types.Complete() {
2374 t.Fatalf("Loaded package types are incomplete")
2375 }
2376
2377 // Check that implied packages.NeedImports by packages.NeedTypesInfo
2378 // didn't add Imports.
2379 if len(pkg.Imports) != 0 {
2380 t.Fatalf("Package imports weren't requested but were returned: %v", pkg.Imports)
2381 }
2382 }
2383
2384 func TestIssue35331(t *testing.T) {
2385 testAllOrModulesParallel(t, testIssue35331)
2386 }
2387 func testIssue35331(t *testing.T, exporter packagestest.Exporter) {
2388 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2389 Name: "golang.org/fake",
2390 }})
2391 defer exported.Cleanup()
2392
2393 exported.Config.Mode = packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles |
2394 packages.NeedImports | packages.NeedDeps | packages.NeedSyntax
2395 exported.Config.Tests = false
2396 pkgs, err := packages.Load(exported.Config, "strconv")
2397 if err != nil {
2398 t.Fatal(err)
2399 }
2400 if len(pkgs) != 1 {
2401 t.Fatalf("Expected 1 package, got %v", pkgs)
2402 }
2403 for pkg := range packages.Postorder(pkgs) {
2404 if len(pkg.Errors) > 0 {
2405 t.Errorf("Expected no errors in package %q, got %v", pkg.ID, pkg.Errors)
2406 }
2407 if len(pkg.Syntax) == 0 && pkg.ID != "unsafe" {
2408 t.Errorf("Expected syntax on package %q, got none.", pkg.ID)
2409 }
2410 }
2411 }
2412
2413 func TestMultiplePackageVersionsIssue36188(t *testing.T) {
2414 testAllOrModulesParallel(t, testMultiplePackageVersionsIssue36188)
2415 }
2416
2417 func testMultiplePackageVersionsIssue36188(t *testing.T, exporter packagestest.Exporter) {
2418 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2419 Name: "golang.org/fake",
2420 Files: map[string]any{
2421 "a/a.go": `package a; import _ "golang.org/fake/b"`,
2422 "b/b.go": `package main`,
2423 }}})
2424 pkgs, err := packages.Load(exported.Config, "golang.org/fake/a", "golang.org/fake/b")
2425 if err != nil {
2426 t.Fatal(err)
2427 }
2428 sort.Slice(pkgs, func(i, j int) bool { return pkgs[i].ID < pkgs[j].ID })
2429 if len(pkgs) != 2 {
2430 t.Fatalf("expected two packages, got %v", pkgs)
2431 }
2432 if pkgs[0].ID != "golang.org/fake/a" && pkgs[1].ID != "golang.org/fake/b" {
2433 t.Fatalf(`expected (sorted) IDs "golang.org/fake/a" and "golang.org/fake/b", got %q and %q`,
2434 pkgs[0].ID, pkgs[1].ID)
2435 }
2436 if pkgs[0].Errors == nil {
2437 t.Errorf(`expected error on package "golang.org/fake/a", got none`)
2438 }
2439 if pkgs[1].Errors != nil {
2440 t.Errorf(`expected no errors on package "golang.org/fake/b", got %v`, pkgs[1].Errors)
2441 }
2442 defer exported.Cleanup()
2443 }
2444
2445 func TestLoadModeStrings(t *testing.T) {
2446 testcases := []struct {
2447 mode packages.LoadMode
2448 expected string
2449 }{
2450 {
2451 packages.LoadMode(0),
2452 "LoadMode(0)",
2453 },
2454 {
2455 packages.NeedName,
2456 "NeedName",
2457 },
2458 {
2459 packages.NeedFiles,
2460 "NeedFiles",
2461 },
2462 {
2463 packages.NeedCompiledGoFiles,
2464 "NeedCompiledGoFiles",
2465 },
2466 {
2467 packages.NeedImports,
2468 "NeedImports",
2469 },
2470 {
2471 packages.NeedDeps,
2472 "NeedDeps",
2473 },
2474 {
2475 packages.NeedExportFile,
2476 "NeedExportFile",
2477 },
2478 {
2479 packages.NeedTypes,
2480 "NeedTypes",
2481 },
2482 {
2483 packages.NeedSyntax,
2484 "NeedSyntax",
2485 },
2486 {
2487 packages.NeedTypesInfo,
2488 "NeedTypesInfo",
2489 },
2490 {
2491 packages.NeedTypesSizes,
2492 "NeedTypesSizes",
2493 },
2494 {
2495 packages.NeedName | packages.NeedExportFile,
2496 "(NeedName|NeedExportFile)",
2497 },
2498 {
2499 packages.NeedForTest | packages.NeedTarget | packages.NeedEmbedFiles | packages.NeedEmbedPatterns,
2500 "(NeedForTest|NeedEmbedFiles|NeedEmbedPatterns|NeedTarget)",
2501 },
2502 {
2503 packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | packages.NeedDeps | packages.NeedExportFile | packages.NeedTypes | packages.NeedSyntax | packages.NeedTypesInfo | packages.NeedTypesSizes,
2504 "(NeedName|NeedFiles|NeedCompiledGoFiles|NeedImports|NeedDeps|NeedExportFile|NeedTypes|NeedSyntax|NeedTypesInfo|NeedTypesSizes)",
2505 },
2506 {
2507 packages.NeedName | packages.NeedModule,
2508 "(NeedName|NeedModule)",
2509 },
2510 {
2511 packages.NeedName | 0x100000, // off the end (future use)
2512 "(NeedName|0x100000)",
2513 },
2514 {
2515 packages.NeedName | 0x400, // needInternalDepsErrors
2516 "(NeedName|0x400)",
2517 },
2518 {
2519 0x1000,
2520 "LoadMode(0x1000)",
2521 },
2522 }
2523
2524 for tcInd, tc := range testcases {
2525 t.Run(fmt.Sprintf("test-%d", tcInd), func(t *testing.T) {
2526 actual := tc.mode.String()
2527 if tc.expected != actual {
2528 t.Errorf("want %#v, got %#v", tc.expected, actual)
2529 }
2530 })
2531 }
2532 }
2533
2534 func TestCycleImportStack(t *testing.T) {
2535 testAllOrModulesParallel(t, testCycleImportStack)
2536 }
2537 func testCycleImportStack(t *testing.T, exporter packagestest.Exporter) {
2538 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2539 Name: "golang.org/fake",
2540 Files: map[string]any{
2541 "a/a.go": `package a; import _ "golang.org/fake/b"`,
2542 "b/b.go": `package b; import _ "golang.org/fake/a"`,
2543 }}})
2544 defer exported.Cleanup()
2545
2546 exported.Config.Mode = packages.NeedName | packages.NeedImports
2547 pkgs, err := packages.Load(exported.Config, "golang.org/fake/a")
2548 if err != nil {
2549 t.Fatal(err)
2550 }
2551 if len(pkgs) != 1 {
2552 t.Fatalf("Expected 1 package, got %v", pkgs)
2553 }
2554 pkg := pkgs[0]
2555 if len(pkg.Errors) != 1 {
2556 t.Fatalf("Expected one error in package, got %v", pkg.Errors)
2557 }
2558 expected := "import cycle not allowed: import stack: [golang.org/fake/a golang.org/fake/b golang.org/fake/a]"
2559 if pkg.Errors[0].Msg != expected {
2560 t.Fatalf("Expected error %q, got %q", expected, pkg.Errors[0].Msg)
2561 }
2562 }
2563
2564 func TestForTestField(t *testing.T) {
2565 testAllOrModulesParallel(t, testForTestField)
2566 }
2567 func testForTestField(t *testing.T, exporter packagestest.Exporter) {
2568 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2569 Name: "golang.org/fake",
2570 Files: map[string]any{
2571 "a/a.go": `package a; func hello() {};`,
2572 "a/a_test.go": `package a; import "testing"; func TestA1(t *testing.T) {};`,
2573 "a/x_test.go": `package a_test; import "testing"; func TestA2(t *testing.T) {};`,
2574 }}})
2575 defer exported.Cleanup()
2576
2577 // Add overlays to make sure they don't affect anything.
2578 exported.Config.Overlay = map[string][]byte{
2579 "a/a_test.go": []byte(`package a; import "testing"; func TestA1(t *testing.T) { hello(); };`),
2580 "a/x_test.go": []byte(`package a_test; import "testing"; func TestA2(t *testing.T) { hello(); };`),
2581 }
2582 exported.Config.Tests = true
2583 exported.Config.Mode = packages.NeedName | packages.NeedImports
2584 forTest := "golang.org/fake/a"
2585 pkgs, err := packages.Load(exported.Config, forTest)
2586 if err != nil {
2587 t.Fatal(err)
2588 }
2589 if len(pkgs) != 4 {
2590 t.Errorf("expected 4 packages, got %v", len(pkgs))
2591 }
2592 for _, pkg := range pkgs {
2593 var hasTestFile bool
2594 for _, f := range pkg.CompiledGoFiles {
2595 if strings.Contains(f, "a_test.go") || strings.Contains(f, "x_test.go") {
2596 hasTestFile = true
2597 break
2598 }
2599 }
2600 if !hasTestFile {
2601 continue
2602 }
2603 if got := pkg.ForTest; got != forTest {
2604 t.Errorf("expected %q, got %q", forTest, got)
2605 }
2606 }
2607 }
2608
2609 func TestIssue37629(t *testing.T) {
2610 testAllOrModulesParallel(t, testIssue37629)
2611 }
2612 func testIssue37629(t *testing.T, exporter packagestest.Exporter) {
2613 // Tests #37629. When automatic vendoring is triggered, and we try to determine
2614 // the module root dir for a new overlay package, we previously would do a go list -m all,
2615 // which is incompatible with automatic vendoring.
2616
2617 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2618 Name: "golang.org/fake",
2619 Files: map[string]any{
2620 "c/c2.go": `package c`,
2621 "a/a.go": `package a; import "b.com/b"; const A = b.B`,
2622 "vendor/b.com/b/b.go": `package b; const B = 4`,
2623 "vendor/modules.txt": `# b.com/b v1.0.0
2624 ## explicit
2625 b.com/b`,
2626 }}, {
2627 Name: "b.com/[email protected]",
2628 Files: map[string]any{
2629 "arbitrary.txt": "",
2630 }},
2631 })
2632 rootDir := filepath.Dir(filepath.Dir(exported.File("golang.org/fake", "a/a.go")))
2633 exported.Config.Overlay = map[string][]byte{
2634 filepath.Join(rootDir, "c/c.go"): []byte(`package c; import "golang.org/fake/a"; const C = a.A`),
2635 }
2636 exported.Config.Env = append(exported.Config.Env, "GOFLAGS=-mod=vendor")
2637 exported.Config.Mode = packages.LoadAllSyntax
2638
2639 defer exported.Cleanup()
2640
2641 initial, err := packages.Load(exported.Config, "golang.org/fake/c")
2642 if err != nil {
2643 t.Fatal(err)
2644 }
2645
2646 // Check value of a.A.
2647 a := initial[0]
2648 aA := constant(a, "C")
2649 if aA == nil {
2650 t.Fatalf("a.A: got nil")
2651 }
2652 got := aA.Val().String()
2653 if got != "4" {
2654 t.Errorf("a.A: got %s, want %s", got, "4")
2655 }
2656 }
2657
2658 func TestIssue37098(t *testing.T) { testAllOrModulesParallel(t, testIssue37098) }
2659 func testIssue37098(t *testing.T, exporter packagestest.Exporter) {
2660 // packages.Load should only return Go sources in
2661 // (*Package).CompiledGoFiles. This tests #37098, where using SWIG to
2662 // causes C++ sources to be inadvertently included in
2663 // (*Package).CompiledGoFiles.
2664
2665 if _, err := exec.LookPath("swig"); err != nil {
2666 t.Skip("skipping test: swig not available")
2667 }
2668 if _, err := exec.LookPath("g++"); err != nil {
2669 t.Skip("skipping test: g++ not available")
2670 }
2671
2672 // Create a fake package with an empty Go source, and a SWIG interface
2673 // file.
2674 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2675 Name: "golang.org/fake",
2676 Files: map[string]any{
2677 // The "package" statement must be included for SWIG sources to
2678 // be generated.
2679 "a/a.go": "package a",
2680 "a/a.swigcxx": "",
2681 }}})
2682 defer exported.Cleanup()
2683
2684 initial, err := packages.Load(exported.Config, "golang.org/fake/a")
2685 if err != nil {
2686 t.Fatalf("failed to load the package: %v", err)
2687 }
2688 // Try and parse each of the files
2689 for _, pkg := range initial {
2690 for _, file := range pkg.CompiledGoFiles {
2691
2692 // Validate that each file can be parsed as a Go source.
2693 fset := token.NewFileSet()
2694 _, err := parser.ParseFile(fset, file, nil, parser.ImportsOnly)
2695 if err != nil {
2696 t.Errorf("Failed to parse file '%s' as a Go source: %v", file, err)
2697
2698 contents, err := os.ReadFile(file)
2699 if err != nil {
2700 t.Fatalf("Failed to read the un-parsable file '%s': %v", file, err)
2701 }
2702
2703 // Print out some of the un-parsable file to aid in debugging.
2704 n := len(contents)
2705
2706 // Don't print the whole file if it is too large.
2707 const maxBytes = 1000
2708 if n > maxBytes {
2709 n = maxBytes
2710 }
2711
2712 t.Logf("First %d bytes of un-parsable file: %s", n, contents[:n])
2713 }
2714 }
2715 }
2716 }
2717
2718 // TestIssue56632 checks that CompiledGoFiles does not contain non-go files regardless of
2719 // whether the NeedFiles mode bit is set.
2720 func TestIssue56632(t *testing.T) {
2721 t.Parallel()
2722 testenv.NeedsGoBuild(t)
2723 testenv.NeedsTool(t, "cgo")
2724
2725 exported := packagestest.Export(t, packagestest.GOPATH, []packagestest.Module{{
2726 Name: "golang.org/issue56632",
2727 Files: map[string]any{
2728 "a/a.go": `package a`,
2729 "a/a_cgo.go": `package a
2730
2731 import "C"`,
2732 "a/a.s": ``,
2733 "a/a.c": ``,
2734 }}})
2735 defer exported.Cleanup()
2736
2737 modes := []packages.LoadMode{packages.NeedCompiledGoFiles, packages.NeedCompiledGoFiles | packages.NeedFiles, packages.NeedImports | packages.NeedCompiledGoFiles, packages.NeedImports | packages.NeedFiles | packages.NeedCompiledGoFiles}
2738 for _, mode := range modes {
2739 exported.Config.Mode = mode
2740
2741 initial, err := packages.Load(exported.Config, "golang.org/issue56632/a")
2742 if err != nil {
2743 t.Fatalf("failed to load package: %v", err)
2744 }
2745
2746 if len(initial) != 1 {
2747 t.Errorf("expected 3 packages, got %d", len(initial))
2748 }
2749
2750 p := initial[0]
2751
2752 if len(p.Errors) != 0 {
2753 t.Errorf("expected no errors, got %v", p.Errors)
2754 }
2755
2756 for _, f := range p.CompiledGoFiles {
2757 if strings.HasSuffix(f, ".s") || strings.HasSuffix(f, ".c") {
2758 t.Errorf("expected no non-Go CompiledGoFiles, got file %q in CompiledGoFiles", f)
2759 }
2760 }
2761 }
2762 }
2763
2764 // TestInvalidFilesInXTest checks the fix for golang/go#37971 in Go 1.15.
2765 func TestInvalidFilesInXTest(t *testing.T) { testAllOrModulesParallel(t, testInvalidFilesInXTest) }
2766 func testInvalidFilesInXTest(t *testing.T, exporter packagestest.Exporter) {
2767 exported := packagestest.Export(t, exporter, []packagestest.Module{
2768 {
2769 Name: "golang.org/fake",
2770 Files: map[string]any{
2771 "d/d.go": `package d; import "net/http"; const d = http.MethodGet; func Get() string { return d; }`,
2772 "d/d2.go": ``, // invalid file
2773 "d/d_test.go": `package d_test; import "testing"; import "golang.org/fake/d"; func TestD(t *testing.T) { d.Get(); }`,
2774 },
2775 },
2776 })
2777 defer exported.Cleanup()
2778
2779 exported.Config.Mode = packages.NeedName | packages.NeedFiles
2780 exported.Config.Tests = true
2781
2782 initial, err := packages.Load(exported.Config, "golang.org/fake/d")
2783 if err != nil {
2784 t.Fatal(err)
2785 }
2786 if len(initial) != 3 {
2787 t.Errorf("expected 3 packages, got %d", len(initial))
2788 }
2789 }
2790
2791 func TestTypecheckCgo(t *testing.T) { testAllOrModulesParallel(t, testTypecheckCgo) }
2792 func testTypecheckCgo(t *testing.T, exporter packagestest.Exporter) {
2793 testenv.NeedsTool(t, "cgo")
2794
2795 const cgo = `package cgo
2796 import "C"
2797
2798 func Example() {
2799 C.CString("hi")
2800 }
2801 `
2802 exported := packagestest.Export(t, exporter, []packagestest.Module{
2803 {
2804 Name: "golang.org/fake",
2805 Files: map[string]any{
2806 "cgo/cgo.go": cgo,
2807 },
2808 },
2809 })
2810 defer exported.Cleanup()
2811
2812 exported.Config.Mode = packages.NeedFiles | packages.NeedCompiledGoFiles |
2813 packages.NeedSyntax | packages.NeedDeps | packages.NeedTypes |
2814 packages.LoadMode(packagesinternal.TypecheckCgo)
2815
2816 initial, err := packages.Load(exported.Config, "golang.org/fake/cgo")
2817 if err != nil {
2818 t.Fatal(err)
2819 }
2820 pkg := initial[0]
2821 if len(pkg.Errors) != 0 {
2822 t.Fatalf("package has errors: %v", pkg.Errors)
2823 }
2824
2825 expos := pkg.Types.Scope().Lookup("Example").Pos()
2826 fname := pkg.Fset.File(expos).Name()
2827 if !strings.HasSuffix(fname, "cgo.go") {
2828 t.Errorf("position for cgo package was loaded from %v, wanted cgo.go", fname)
2829 }
2830 }
2831
2832 // TestIssue48226 ensures that when NeedSyntax is provided we do not nullify the
2833 // Fset, which is needed to resolve the syntax tree element positions to files.
2834 func TestIssue48226(t *testing.T) { testAllOrModulesParallel(t, testIssue48226) }
2835 func testIssue48226(t *testing.T, exporter packagestest.Exporter) {
2836 exported := packagestest.Export(t, exporter, []packagestest.Module{
2837 {
2838 Name: "golang.org/fake/syntax",
2839 Files: map[string]any{
2840 "syntax.go": `package test`,
2841 },
2842 },
2843 })
2844 defer exported.Cleanup()
2845
2846 exported.Config.Mode = packages.NeedFiles | packages.NeedSyntax
2847
2848 initial, err := packages.Load(exported.Config, "golang.org/fake/syntax")
2849 if err != nil {
2850 t.Fatal(err)
2851 }
2852 if len(initial) != 1 {
2853 t.Fatalf("expected 1 package, got %d", len(initial))
2854 }
2855 pkg := initial[0]
2856
2857 if len(pkg.Errors) != 0 {
2858 t.Fatalf("package has errors: %v", pkg.Errors)
2859 }
2860
2861 fname := pkg.Fset.File(pkg.Syntax[0].FileStart).Name()
2862 if filepath.Base(fname) != "syntax.go" {
2863 t.Errorf("expected the package declaration position "+
2864 "to resolve to \"syntax.go\", got %q instead", fname)
2865 }
2866 }
2867
2868 func TestModule(t *testing.T) {
2869 testAllOrModulesParallel(t, testModule)
2870 }
2871 func testModule(t *testing.T, exporter packagestest.Exporter) {
2872 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2873 Name: "golang.org/fake",
2874 Files: map[string]any{"a/a.go": `package a`}}})
2875 exported.Config.Mode = packages.NeedModule
2876 rootDir := filepath.Dir(filepath.Dir(exported.File("golang.org/fake", "a/a.go")))
2877
2878 initial, err := packages.Load(exported.Config, "golang.org/fake/a")
2879 if err != nil {
2880 t.Fatal(err)
2881 }
2882
2883 if len(initial) != 1 {
2884 t.Fatal("want exactly one package, got ", initial)
2885 }
2886 a := initial[0]
2887 switch exported.Exporter.Name() {
2888 case "GOPATH":
2889 if a.Module != nil {
2890 t.Fatal("package.Module: want nil, got ", a.Module)
2891 }
2892 case "Modules":
2893 // Make sure Modules field is set, and spot check a few of its fields.
2894 if a.Module == nil {
2895 t.Fatal("package.Module: want non-nil, got nil")
2896 }
2897 if a.Module.Path != "golang.org/fake" {
2898 t.Fatalf("package.Module.Path: want \"golang.org/fake\", got %q", a.Module.Path)
2899 }
2900 if a.Module.GoMod != filepath.Join(rootDir, "go.mod") {
2901 t.Fatalf("package.Module.GoMod: want %q, got %q", filepath.Join(rootDir, "go.mod"), a.Module.GoMod)
2902 }
2903 default:
2904 t.Fatalf("Expected exporter to be GOPATH or Modules, got %v", exported.Exporter.Name())
2905 }
2906 }
2907
2908 func TestExternal_NotHandled(t *testing.T) {
2909 testAllOrModulesParallel(t, testExternal_NotHandled)
2910 }
2911 func testExternal_NotHandled(t *testing.T, exporter packagestest.Exporter) {
2912 skipIfShort(t, "builds and links fake driver binaries")
2913 testenv.NeedsGoBuild(t)
2914
2915 tempdir, err := os.MkdirTemp("", "testexternal")
2916 if err != nil {
2917 t.Fatal(err)
2918 }
2919 defer os.RemoveAll(tempdir)
2920
2921 exported := packagestest.Export(t, exporter, []packagestest.Module{{
2922 Name: "golang.org/fake",
2923 Files: map[string]any{
2924 "a/a.go": `package a`,
2925 "empty_driver/main.go": `package main
2926
2927 import (
2928 "fmt"
2929 "io"
2930 "os"
2931 )
2932
2933 func main() {
2934 io.ReadAll(os.Stdin)
2935 fmt.Println("{}")
2936 }
2937 `,
2938 "nothandled_driver/main.go": `package main
2939
2940 import (
2941 "fmt"
2942 "io"
2943 "os"
2944 )
2945
2946 func main() {
2947 io.ReadAll(os.Stdin)
2948 fmt.Println("{\"NotHandled\": true}")
2949 }
2950 `,
2951 }}})
2952 baseEnv := exported.Config.Env
2953
2954 // As a control, create a fake driver that always returns an empty response.
2955 emptyDriverPath := filepath.Join(tempdir, "empty_driver.exe") // Add .exe because Windows expects it.
2956 cmd := exec.Command("go", "build", "-o", emptyDriverPath, "golang.org/fake/empty_driver")
2957 cmd.Env = baseEnv
2958 cmd.Dir = exported.Config.Dir
2959 if b, err := cmd.CombinedOutput(); err != nil {
2960 t.Log(string(b))
2961 t.Fatal(err)
2962 }
2963
2964 exported.Config.Env = append(slices.Clone(baseEnv), "GOPACKAGESDRIVER="+emptyDriverPath)
2965 initial, err := packages.Load(exported.Config, "golang.org/fake/a")
2966 if err != nil {
2967 t.Fatal(err)
2968 }
2969
2970 if len(initial) != 0 {
2971 t.Errorf("package.Load with empty driver: want [], got %v", initial)
2972 }
2973
2974 // Create a fake driver that always returns a NotHandled response.
2975 notHandledDriverPath := filepath.Join(tempdir, "nothandled_driver.exe")
2976 cmd = exec.Command("go", "build", "-o", notHandledDriverPath, "golang.org/fake/nothandled_driver")
2977 cmd.Env = baseEnv
2978 cmd.Dir = exported.Config.Dir
2979 if b, err := cmd.CombinedOutput(); err != nil {
2980 t.Log(string(b))
2981 t.Fatal(err)
2982 }
2983
2984 exported.Config.Env = append(slices.Clone(baseEnv), "GOPACKAGESDRIVER="+notHandledDriverPath)
2985 initial, err = packages.Load(exported.Config, "golang.org/fake/a")
2986 if err != nil {
2987 t.Fatal(err)
2988 }
2989
2990 if len(initial) != 1 || initial[0].PkgPath != "golang.org/fake/a" {
2991 t.Errorf("package.Load: want [golang.org/fake/a], got %v", initial)
2992 }
2993 }
2994
2995 func TestInvalidPackageName(t *testing.T) {
2996 testAllOrModulesParallel(t, testInvalidPackageName)
2997 }
2998
2999 func testInvalidPackageName(t *testing.T, exporter packagestest.Exporter) {
3000 exported := packagestest.Export(t, exporter, []packagestest.Module{{
3001 Name: "golang.org/fake",
3002 Files: map[string]any{
3003 "main.go": `package default
3004
3005 func main() {
3006 }
3007 `,
3008 },
3009 }})
3010 defer exported.Cleanup()
3011
3012 initial, err := packages.Load(exported.Config, "golang.org/fake")
3013 if err != nil {
3014 t.Fatal(err)
3015 }
3016 pkg := initial[0]
3017 if len(pkg.CompiledGoFiles) != 1 {
3018 t.Fatalf("expected 1 Go file in package %s, got %v", pkg.ID, len(pkg.CompiledGoFiles))
3019 }
3020 }
3021
3022 // TestConfigEnvDoesNotInheritProcessEnv tests that when Config.Env is non-nil
3023 // and doesn't contain os.Environ(), packages.Load doesn't inherit the process
3024 // environment.
3025 func TestConfigEnvDoesNotInheritProcessEnv(t *testing.T) {
3026 testenv.NeedsGoPackages(t)
3027
3028 dir := writeTree(t, `
3029 -- go.mod --
3030 module example.com
3031
3032 go 1.18
3033
3034 -- p/p.go --
3035 package p
3036
3037 -- p/tagged.go --
3038 //go:build fromparent
3039 // +build fromparent
3040
3041 package p
3042 `)
3043
3044 t.Setenv("GOFLAGS", "-tags=fromparent")
3045
3046 pkgs, err := packages.Load(&packages.Config{
3047 Dir: dir,
3048 Mode: packages.NeedFiles,
3049 Env: []string{
3050 "PATH=" + os.Getenv("PATH"),
3051 "GOCACHE=" + t.TempDir(),
3052 "GOPACKAGESDRIVER=off",
3053 "GOWORK=off",
3054 },
3055 }, "./p")
3056 if err != nil {
3057 t.Fatal(err)
3058 }
3059 if len(pkgs) != 1 {
3060 t.Fatalf("Load returned %d packages, want 1", len(pkgs))
3061 }
3062 if got, want := strings.Join(srcs(pkgs[0]), " "), "p.go"; got != want {
3063 t.Fatalf("GoFiles = %s, want %s", got, want)
3064 }
3065 }
3066
3067 func TestPackageLoadSingleFile(t *testing.T) {
3068 testenv.NeedsTool(t, "go")
3069
3070 tmp, err := os.MkdirTemp("", "a")
3071 if err != nil {
3072 t.Fatal(err)
3073 }
3074 defer os.RemoveAll(tmp)
3075
3076 filename := filepath.Join(tmp, "a.go")
3077
3078 if err := os.WriteFile(filename, []byte(`package main; func main() { println("hello world") }`), 0775); err != nil {
3079 t.Fatal(err)
3080 }
3081
3082 pkgs, err := packages.Load(&packages.Config{Mode: packages.LoadSyntax, Dir: tmp}, "file="+filename)
3083 if err != nil {
3084 t.Fatalf("could not load package: %v", err)
3085 }
3086 if len(pkgs) != 1 {
3087 t.Fatalf("expected one package to be loaded, got %d", len(pkgs))
3088 }
3089 if len(pkgs[0].CompiledGoFiles) != 1 || pkgs[0].CompiledGoFiles[0] != filename {
3090 t.Fatalf("expected one compiled go file (%q), got %v", filename, pkgs[0].CompiledGoFiles)
3091 }
3092 }
3093
3094 func errorMessages(errors []packages.Error) []string {
3095 var msgs []string
3096 for _, err := range errors {
3097 msgs = append(msgs, err.Msg)
3098 }
3099 return msgs
3100 }
3101
3102 func srcs(p *packages.Package) []string {
3103 var files []string
3104 files = append(files, p.GoFiles...)
3105 files = append(files, p.OtherFiles...)
3106 files = append(files, p.EmbedFiles...)
3107 return cleanPaths(files)
3108 }
3109
3110 // cleanPaths attempts to reduce path names to stable forms
3111 func cleanPaths(paths []string) []string {
3112 result := make([]string, len(paths))
3113 for i, src := range paths {
3114 // If the source file doesn't have an extension like .go or .s,
3115 // it comes from GOCACHE. The names there aren't predictable.
3116 name := filepath.Base(src)
3117 if !strings.Contains(name, ".") {
3118 result[i] = fmt.Sprintf("%d.go", i) // make cache names predictable
3119 } else {
3120 result[i] = name
3121 }
3122 }
3123 return result
3124 }
3125
3126 // importGraph returns the import graph as a user-friendly string,
3127 // and a map containing all packages keyed by ID.
3128 func importGraph(initial []*packages.Package) (string, map[string]*packages.Package) {
3129 out := new(bytes.Buffer)
3130
3131 initialSet := make(map[*packages.Package]bool)
3132 for _, p := range initial {
3133 initialSet[p] = true
3134 }
3135
3136 // We can't use Visit or Postorder because we need to prune
3137 // the traversal of specific edges, not just nodes.
3138 var nodes, edges []string
3139 res := make(map[string]*packages.Package)
3140 seen := make(map[*packages.Package]bool)
3141 var visit func(p *packages.Package)
3142 visit = func(p *packages.Package) {
3143 if !seen[p] {
3144 seen[p] = true
3145 if res[p.ID] != nil {
3146 panic("duplicate ID: " + p.ID)
3147 }
3148 res[p.ID] = p
•3149
3150 star := ' ' // mark initial packages with a star
3151 if initialSet[p] {
3152 star = '*'
3153 }
3154 nodes = append(nodes, fmt.Sprintf("%c %s", star, p.ID))
3155
3156 // To avoid a lot of noise,
3157 // we prune uninteresting dependencies of testmain packages,
3158 // which we identify by this import:
3159 isTestMain := p.Imports["testing/internal/testdeps"] != nil
3160
3161 for _, imp := range p.Imports {
3162 if isTestMain {
3163 switch imp.ID {
3164 case "os", "reflect", "testing", "testing/internal/testdeps":
3165 continue
3166 }
3167 }
3168 // math/bits took on a dependency on unsafe in 1.12, which breaks some
3169 // tests. As a short term hack, prune that edge.
3170 // ditto for ("errors", "internal/reflectlite") in 1.13.
3171 // TODO(matloob): think of a cleaner solution, or remove math/bits from the test.
3172 if p.ID == "math/bits" && imp.ID == "unsafe" {
3173 continue
3174 }
3175 edges = append(edges, fmt.Sprintf("%s -> %s", p, imp))
3176 visit(imp)
3177 }
3178 }
3179 }
3180 for _, p := range initial {
3181 visit(p)
3182 }
3183
3184 // Sort, ignoring leading optional star prefix.
3185 sort.Slice(nodes, func(i, j int) bool { return nodes[i][2:] < nodes[j][2:] })
3186 for _, node := range nodes {
3187 fmt.Fprintf(out, "%s\n", node)
3188 }
3189
3190 sort.Strings(edges)
3191 for _, edge := range edges {
3192 fmt.Fprintf(out, " %s\n", edge)
3193 }
3194
3195 return out.String(), res
3196 }
3197
3198 func constant(p *packages.Package, name string) *types.Const {
3199 if p == nil || p.Types == nil {
3200 return nil
3201 }
3202 c := p.Types.Scope().Lookup(name)
3203 if c == nil {
3204 return nil
3205 }
3206 return c.(*types.Const)
3207 }
3208
3209 func TestExportFile(t *testing.T) {
3210 // This used to trigger the log.Fatal in loadFromExportData.
3211 // See go.dev/issue/45584.
3212 cfg := new(packages.Config)
3213 cfg.Mode = packages.NeedTypes
3214 packages.Load(cfg, "fmt")
3215 }
3216
3217 // TestLoadEitherSucceedsOrFails is an attempt to reproduce a sporadic
3218 // failure observed on the Android emu builders in which Load would
3219 // return an empty list of packages but no error. We don't expect
3220 // packages.Load to succeed on that platform, and testenv.NeedsGoBuild
3221 // would ordinarily suppress the attempt if called early. But
3222 // regardless of whether the 'go' command is functional, Load should
3223 // never return an empty set of packages but no error.
3224 func TestLoadEitherSucceedsOrFails(t *testing.T) {
3225 const src = `package p`
3226 dir := t.TempDir()
3227 cfg := &packages.Config{
3228 Dir: dir,
3229 Mode: packages.LoadSyntax,
3230 Overlay: map[string][]byte{
3231 filepath.Join(dir, "p.go"): []byte(src),
3232 },
3233 }
3234 initial, err := packages.Load(cfg, "./p.go")
3235 if err != nil {
3236 // If Load failed because it needed 'go' and the
3237 // platform doesn't have it, silently skip the test.
3238 testenv.NeedsGoBuild(t)
3239
3240 // Otherwise, it's a real failure.
3241 t.Fatal(err)
3242 }
3243
3244 // If Load returned without error,
3245 // it had better give us error-free packages.
3246 if packages.PrintErrors(initial) > 0 {
3247 t.Errorf("packages contain errors")
3248 }
3249
3250 // If Load returned without error,
3251 // it had better give us the correct number packages.
3252 if len(initial) != 1 {
3253 t.Errorf("Load returned %d packages (want 1) and no error", len(initial))
3254 }
3255 }
3256
3257 // TestLoadOverlayGoMod ensures that overlays containing go.mod files
3258 // are effective for all 'go list' calls made by go/packages (#67644).
3259 func TestLoadOverlayGoMod(t *testing.T) {
3260 t.Skip("needs Go mod")
3261 testenv.NeedsGoBuild(t)
3262
3263 cwd, _ := os.Getwd()
3264
3265 // This test ensures that the overlaid go.mod file is seen by
3266 // all runs of 'go list', in particular the early run that
3267 // enumerates the modules: if the go.mod file were absent,
3268 // it would ascend to the parent directory (x/tools) and
3269 // then (falsely) report inconsistent vendoring.
3270 //
3271 // (Ideally the testdata would be constructed from nothing
3272 // rather than rely on the go/packages source tree, but it is
3273 // turned out to a bigger project than bargained for.)
3274 cfg := &packages.Config{
3275 Mode: packages.LoadSyntax,
3276 Overlay: map[string][]byte{
3277 filepath.Join(cwd, "go.mod"): []byte("module example.com\ngo 1.0"),
3278 },
3279 Env: append(os.Environ(), "GOFLAGS=-mod=vendor", "GOWORK=off"),
3280 }
3281
3282 pkgs, err := packages.Load(cfg, "./testdata")
3283 if err != nil {
3284 t.Fatal(err) // (would previously fail here with "inconsistent vendoring")
3285 }
3286 got := fmt.Sprint(pkgs)
3287 want := `[./testdata]`
3288 if got != want {
3289 t.Errorf("Load: got %s, want %v", got, want)
3290 }
3291 }
3292
3293 func overlayFS(overlay map[string][]byte) fstest.MapFS {
3294 fs := make(fstest.MapFS)
3295 for name, data := range overlay {
3296 fs[name] = &fstest.MapFile{Data: data}
3297 }
3298 return fs
3299 }
3300
3301 // TestIssue69606a tests when tools in $GOROOT/pkg/tool/$GOOS_$GOARCH are missing,
3302 // Load should return an error.
3303 func TestIssue69606a(t *testing.T) {
3304 testenv.NeedsTool(t, "go")
3305 overlay := overlayFS(map[string][]byte{
3306 "io/io.go": []byte("package io"),
3307 "unsafe/unsafe.go": []byte("package unsafe"),
3308 })
3309 goroot := testfiles.CopyToTmp(t, overlay)
3310
3311 t.Logf("custom GOROOT: %s", goroot)
3312
3313 // load the std packages under a custom GOROOT
3314 _, err := packages.Load(&packages.Config{
3315 Mode: packages.NeedName |
3316 packages.NeedFiles |
3317 packages.NeedImports |
3318 packages.NeedTypes,
3319 Env: append(
3320 os.Environ(),
3321 "GO111MODULES=on",
3322 "GOPATH=",
3323 "GOWORK=off",
3324 "GOPROXY=off",
3325 fmt.Sprintf("GOROOT=%s", goroot)),
3326 }, "std")
3327
3328 if err == nil {
3329 t.Fatal("Expected to get an error because missing tool 'compile' but got a nil error")
3330 }
3331 }
3332
3333 // TestIssue69606b tests when loading std from a fake goroot without a unsafe package,
3334 // Load should return an error.
3335 func TestIssue69606b(t *testing.T) {
3336 testenv.NeedsTool(t, "go")
3337 overlay := overlayFS(map[string][]byte{
3338 "io/io.go": []byte("package io"),
3339 })
3340 goroot := testfiles.CopyToTmp(t, overlay)
3341
3342 t.Logf("custom GOROOT: %s", goroot)
3343
3344 // load the std packages under a custom GOROOT
3345 _, err := packages.Load(&packages.Config{
3346 Mode: packages.NeedName |
3347 packages.NeedFiles |
3348 packages.NeedImports |
3349 packages.NeedTypes,
3350 Env: append(
3351 os.Environ(),
3352 "GO111MODULES=on",
3353 "GOPATH=",
3354 "GOWORK=off",
3355 "GOPROXY=off",
3356 fmt.Sprintf("GOROOT=%s", goroot)),
3357 }, "std")
3358
3359 if err == nil {
3360 t.Fatal("Expected to get an error because missing unsafe package but got a nil error")
3361 }
3362 }
3363
3364 // TestIssue70394 tests materializing an alias type defined in a package (m/a)
3365 // in another package (m/b) where the types for m/b are coming from the compiler,
3366 // e.g. `go list -compiled=true ... m/b`.
3367 func TestIssue70394(t *testing.T) {
3368 testenv.NeedsGo1Point(t, 23)
3369 testenv.NeedsTool(t, "go") // requires go list.
3370 testenv.NeedsGoBuild(t) // requires the compiler for export data.
3371
3372 dir := t.TempDir()
3373 overlay := map[string][]byte{
3374 filepath.Join(dir, "go.mod"): []byte("module m"), // go version of the module does not matter.
3375 filepath.Join(dir, "a/a.go"): []byte(`package a; type A = int32`),
3376 filepath.Join(dir, "b/b.go"): []byte(`package b; import "m/a"; var V a.A`),
3377 }
3378 cfg := &packages.Config{
3379 Dir: dir,
3380 Mode: packages.NeedTypes, // just NeedsTypes allows for loading export data.
3381 Overlay: overlay,
3382 Env: append(os.Environ(), "GOFLAGS=-mod=vendor", "GOWORK=off"),
3383 }
3384 pkgs, err := packages.Load(cfg, "m/b")
3385 if err != nil {
3386 t.Fatal(err)
3387 }
3388 if errs := packages.PrintErrors(pkgs); errs > 0 {
3389 t.Fatalf("Got %d errors while loading packages.", errs)
3390 }
3391 if len(pkgs) != 1 {
3392 t.Fatalf("Loaded %d packages. expected 1", len(pkgs))
3393 }
3394
3395 pkg := pkgs[0]
3396 scope := pkg.Types.Scope()
3397 obj := scope.Lookup("V")
3398 if obj == nil {
3399 t.Fatalf("Failed to find object %q in package %q", "V", pkg)
3400 }
3401 if _, ok := obj.Type().(*types.Alias); !ok {
3402 t.Errorf("Object %q has type %q. expected an alias", obj, obj.Type())
3403 }
3404 }
3405
3406 // TestLoadTypesInfoWithoutSyntaxOrTypes tests when NeedTypesInfo was set and NeedSyntax & NeedTypes were not,
3407 // Load should include the TypesInfo of packages properly
3408 func TestLoadTypesInfoWithoutSyntaxOrTypes(t *testing.T) {
3409 testAllOrModulesParallel(t, testLoadTypesInfoWithoutSyntaxOrTypes)
3410 }
3411
3412 func testLoadTypesInfoWithoutSyntaxOrTypes(t *testing.T, exporter packagestest.Exporter) {
3413 exported := packagestest.Export(t, exporter, []packagestest.Module{{
3414 Name: "golang.org/fake",
3415 Files: map[string]any{
3416 "a/a.go": `package a;
3417
3418 func foo() int {
3419 i := 0
3420 s := "abc"
3421 return i + len(s)
3422 }
3423 `,
3424 }}})
3425 defer exported.Cleanup()
3426 exported.Config.Mode = packages.NeedTypesInfo
3427
3428 pkgs, err := packages.Load(exported.Config, "golang.org/fake/a")
3429 if err != nil {
3430 t.Fatal(err)
3431 }
3432
3433 // check if types info is present
3434 if pkgs[0].TypesInfo == nil {
3435 t.Errorf("expected types info to be present but got nil")
3436 }
3437 }
3438
3439 // TestDirAndForTest tests the new fields added as part of golang/go#38445.
3440 func TestDirAndForTest(t *testing.T) {
3441 testenv.NeedsGoPackages(t)
3442
3443 dir := writeTree(t, `
3444 -- go.mod --
3445 module example.com
3446
3447 go 1.18
3448
3449 -- a/a.go --
3450 package a
3451
3452 func Foo() int { return 1 }
3453
3454 -- a/a_test.go --
3455 package a
3456
3457 func Bar() int { return 2 }
3458
3459 -- a/a_x_test.go --
3460 package a_test
3461
3462 import (
3463 "example.com/a"
3464 "example.com/b"
3465 )
3466
3467 func _() {
3468 if got := a.Foo() + a.Bar() + b.Baz(); got != 6 {
3469 panic("whoops")
3470 }
3471 }
3472
3473 -- b/b.go --
3474 package b
3475
3476 import "example.com/a"
3477
3478 func Baz() int { return 3 }
3479
3480 func Foo() int { return a.Foo() }
3481 `)
3482
3483 pkgs, err := packages.Load(&packages.Config{
3484 Mode: packages.NeedName |
3485 packages.NeedFiles |
3486 packages.NeedForTest |
3487 packages.NeedImports,
3488 Dir: dir,
3489 Tests: true,
3490 }, "./...")
3491 if err != nil {
3492 t.Fatal(err)
3493 }
3494 type result struct{ Dir, ForTest string }
3495 got := make(map[string]result)
3496 for pkg := range packages.Postorder(pkgs) {
3497 if !packagepath.IsStdPackage(pkg.PkgPath) {
3498 rel, err := filepath.Rel(dir, pkg.Dir)
3499 if err != nil {
3500 t.Errorf("Rel(%q, %q) failed: %v", dir, pkg.Dir, err)
3501 continue
3502 }
3503 got[pkg.ID] = result{
3504 Dir: rel,
3505 ForTest: pkg.ForTest,
3506 }
3507 }
3508 }
3509 want := map[string]result{
3510 "example.com/a": {"a", ""},
3511 "example.com/a.test": {"a", ""},
3512 "example.com/a [example.com/a.test]": {"a", "example.com/a"}, // test variant
3513 "example.com/a_test [example.com/a.test]": {"a", "example.com/a"}, // x_test
3514 "example.com/b [example.com/a.test]": {"b", "example.com/a"}, // intermediate test variant
3515 "example.com/b": {"b", ""},
3516 }
3517 if diff := cmp.Diff(want, got); diff != "" {
3518 t.Errorf("Load returned mismatching ForTest fields (ID->result -want +got):\n%s", diff)
3519 }
3520 t.Logf("Packages: %+v", pkgs)
3521 }
3522
3523 // TestTarget tests the new field added as part of golang/go#38445.
3524 // The test uses GOPATH mode because non-main packages don't usually
3525 // have install targets in module mode.
3526 func TestTarget(t *testing.T) {
3527 testenv.NeedsGoPackages(t)
3528
3529 dir := writeTree(t, `
3530 -- gopath/src/a/a.go --
3531 package a
3532
3533 func Foo() {}
3534 -- gopath/src/b/b.go --
3535 package main
3536
3537 import "a"
3538
3539 func main() {
3540 a.Foo()
3541 }
3542 `)
3543 gopath := filepath.Join(dir, "gopath")
3544
3545 pkgs, err := packages.Load(&packages.Config{
3546 Mode: packages.NeedName | packages.NeedTarget,
3547 Env: append(os.Environ(), "GOPATH="+gopath, "GO111MODULE=off"),
3548 }, filepath.Join(gopath, "src", "..."))
3549 if err != nil {
3550 t.Fatal(err)
3551 }
3552 var goexe string
3553 if runtime.GOOS == "windows" {
3554 goexe = ".exe"
3555 }
3556 want := map[string]string{
3557 "a": filepath.Join(gopath, "pkg", runtime.GOOS+"_"+runtime.GOARCH, "a.a"),
3558 "b": filepath.Join(gopath, "bin", "b"+goexe),
3559 }
3560 got := make(map[string]string)
3561 for pkg := range packages.Postorder(pkgs) {
3562 got[pkg.PkgPath] = pkg.Target
3563 }
3564 if diff := cmp.Diff(want, got); diff != "" {
3565 t.Errorf("Load returned mismatching Target fields (pkgpath->target -want +got):\n%s", diff)
3566 }
3567 t.Logf("Packages: %+v", pkgs)
3568 }
3569
3570 // TestCompiledGoFilesIncludesDepsErrors ensures that when CompiledGoFiles
3571 // is missing, errors reported by go/packages include underlying dependency
3572 // errors from go list, rather than only a generic message.
3573 //
3574 // See golang/go#78083.
3575 func TestCompiledGoFilesIncludesDepsErrors(t *testing.T) {
3576 testenv.NeedsGoPackages(t)
3577
3578 dir := writeTree(t, `
3579 -- go.mod --
3580 module example.com
3581 go 1.18
3582
3583 -- a/a.go --
3584 package a
3585
3586 /*
3587 #cgo CFLAGS: -I/nonexistent
3588 #include <missing.h>
3589 */
3590 import "C"
3591
3592 func Foo() {}
3593 `)
3594 pkgs, err := packages.Load(&packages.Config{
3595 Dir: dir,
3596 Mode: packages.LoadAllSyntax,
3597 Env: append(os.Environ(),
3598 "CGO_ENABLED=1",
3599 ),
3600 }, "example.com/a")
3601 if err != nil {
3602 t.Fatal(err)
3603 }
3604 if len(pkgs) == 0 {
3605 t.Fatal("no packages loaded")
3606 }
3607 found := false
3608 // Expected error should include something like:
3609 // fatal error: missing.h: No such file or directory
3610 // We assert only "missing.h" for portability across systems.
3611 for _, err := range pkgs[0].Errors {
3612 if strings.Contains(err.Msg, "missing.h") {
3613 found = true
3614 }
3615 }
3616 if !found {
3617 t.Errorf("expected error message to include underlying dependency errors, got: %+v", pkgs[0].Errors)
3618 }
3619 }
3620
3621 // TestMainPackagePathInModeTypes tests (*types.Package).Path() for
3622 // main packages in mode NeedTypes, a regression test for #70742, a
3623 // bug in cmd/compile's export data that caused them to appear as
3624 // "main". (The PkgPath field was always correct.)
3625 func TestMainPackagePathInModeTypes(t *testing.T) {
3626 testenv.NeedsGoPackages(t)
3627
3628 cfg := &packages.Config{Mode: packages.NeedName | packages.NeedTypes}
3629 pkgs, err := packages.Load(cfg, "cmd/go")
3630 if err != nil {
3631 t.Fatal(err)
3632 }
3633 p := pkgs[0]
3634 if p.PkgPath != "cmd/go" ||
3635 p.Name != "main" ||
3636 p.Types.Path() != "cmd/go" ||
3637 p.Types.Name() != "main" {
3638 t.Errorf("PkgPath=%q Name=%q Types.Path=%q Types.Name=%q; want (cmd/go, main) both times)",
3639 p.PkgPath,
3640 p.Name,
3641 p.Types.Name(),
3642 p.Types.Path())
3643 }
3644 }
3645
3646 func writeTree(t *testing.T, archive string) string {
3647 root := t.TempDir()
3648
3649 for _, f := range txtar.Parse([]byte(archive)).Files {
3650 filename := filepath.Join(root, f.Name)
3651 if err := os.MkdirAll(filepath.Dir(filename), 0777); err != nil {
3652 t.Fatal(err)
3653 }
3654 if err := os.WriteFile(filename, f.Data, 0666); err != nil {
3655 t.Fatal(err)
3656 }
3657 }
3658 return root
3659 }
3660
3661 func TestLoadFileRelativePath(t *testing.T) {
3662 exported := packagestest.Export(t, packagestest.Modules, []packagestest.Module{
3663 {
3664 Name: "fake/pkg",
3665 Files: map[string]any{
3666 "pkg.go": "package pkg; type A int",
3667 },
3668 },
3669 })
3670 t.Cleanup(exported.Cleanup)
3671
3672 exported.Config.Mode = packages.LoadSyntax
3673 pkgs, err := packages.Load(exported.Config, "file=pkg.go")
3674 if err != nil {
3675 t.Fatal(err)
3676 }
3677 if len(pkgs) != 1 {
3678 t.Fatalf("len(pkgs) = %v; want = 1", len(pkgs))
3679 }
3680 if pkgs[0].ID != "fake/pkg" {
3681 t.Fatalf(`pkgs[0].Id = %q; want "fake/pkg"`, pkgs[0].ID)
3682 }
3683 }
3684
3685 func TestLoad_populatesInfoMapsForUnsafePackage(t *testing.T) {
3686 testenv.NeedsGoPackages(t)
3687
3688 pkgs, err := packages.Load(&packages.Config{Mode: packages.LoadAllSyntax}, "unsafe")
3689 if err != nil {
3690 t.Fatal(err)
3691 }
3692 info := pkgs[0].TypesInfo
3693
3694 if info.Defs == nil ||
3695 info.Uses == nil ||
3696 info.Selections == nil ||
3697 info.Types == nil ||
3698 info.FileVersions == nil ||
3699 info.Implicits == nil ||
3700 info.Instances == nil ||
3701 info.Scopes == nil {
3702 t.Errorf("types.Info for package unsafe has one or more nil maps: %#v", *info)
3703 }
3704 }
3705
3706 func cond[T any](cond bool, t, f T) T {
3707 if cond {
3708 return t
3709 } else {
3710 return f
3711 }
3712 }