Debian Codegraph @

go/loader/loader_test.go

raw symbols SCIP
1 // Copyright 2013 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 // No testdata on Android.
6
7 //go:build !android
8
9 package loader_test
10
11 import (
12 "fmt"
13 "go/build"
14 "go/constant"
15 "go/types"
16 "os"
17 "path/filepath"
18 "reflect"
19 "runtime"
20 "sort"
21 "strings"
22 "sync"
23 "testing"
24
25 "golang.org/x/tools/go/buildutil"
26 "golang.org/x/tools/go/loader"
27 "golang.org/x/tools/internal/testenv"
28 )
29
30 func TestMain(m *testing.M) {
31 testenv.ExitIfSmallMachine()
32 os.Exit(m.Run())
33 }
34
35 // TestFromArgs checks that conf.FromArgs populates conf correctly.
36 // It does no I/O.
37 func TestFromArgs(t *testing.T) {
38 type result struct {
39 Err string
40 Rest []string
41 ImportPkgs map[string]bool
42 CreatePkgs []loader.PkgSpec
43 }
44 for _, test := range []struct {
45 args []string
46 tests bool
47 want result
48 }{
49 // Mix of existing and non-existent packages.
50 {
51 args: []string{"nosuchpkg", "errors"},
52 want: result{
53 ImportPkgs: map[string]bool{"errors": false, "nosuchpkg": false},
54 },
55 },
56 // Same, with -test flag.
57 {
58 args: []string{"nosuchpkg", "errors"},
59 tests: true,
60 want: result{
61 ImportPkgs: map[string]bool{"errors": true, "nosuchpkg": true},
62 },
63 },
64 // Surplus arguments.
65 {
66 args: []string{"fmt", "errors", "--", "surplus"},
67 want: result{
68 Rest: []string{"surplus"},
69 ImportPkgs: map[string]bool{"errors": false, "fmt": false},
70 },
71 },
72 // Ad hoc package specified as *.go files.
73 {
74 args: []string{"foo.go", "bar.go"},
75 want: result{CreatePkgs: []loader.PkgSpec{{
76 Filenames: []string{"foo.go", "bar.go"},
77 }}},
78 },
79 // Mixture of *.go and import paths.
80 {
81 args: []string{"foo.go", "fmt"},
82 want: result{
83 Err: "named files must be .go files: fmt",
84 },
85 },
86 } {
87 var conf loader.Config
88 rest, err := conf.FromArgs(test.args, test.tests)
89 got := result{
90 Rest: rest,
91 ImportPkgs: conf.ImportPkgs,
92 CreatePkgs: conf.CreatePkgs,
93 }
94 if err != nil {
95 got.Err = err.Error()
96 }
97 if !reflect.DeepEqual(got, test.want) {
98 t.Errorf("FromArgs(%q) = %+v, want %+v", test.args, got, test.want)
99 }
100 }
101 }
102
103 func TestLoad_NoInitialPackages(t *testing.T) {
104 var conf loader.Config
105
106 const wantErr = "no initial packages were loaded"
107
108 prog, err := conf.Load()
109 if err == nil {
110 t.Errorf("Load succeeded unexpectedly, want %q", wantErr)
111 } else if err.Error() != wantErr {
112 t.Errorf("Load failed with wrong error %q, want %q", err, wantErr)
113 }
114 if prog != nil {
115 t.Errorf("Load unexpectedly returned a Program")
116 }
117 }
118
119 func TestLoad_MissingInitialPackage(t *testing.T) {
120 if runtime.GOOS == "wasip1" {
121 t.Skip("Skipping due to golang/go#64725: fails with EBADF errors")
122 }
123
124 var conf loader.Config
125 conf.Import("nosuchpkg")
126 conf.Import("errors")
127
128 const wantErr = "couldn't load packages due to errors: nosuchpkg"
129
130 prog, err := conf.Load()
131 if err == nil {
132 t.Errorf("Load succeeded unexpectedly, want %q", wantErr)
133 } else if err.Error() != wantErr {
134 t.Errorf("Load failed with wrong error %q, want %q", err, wantErr)
135 }
136 if prog != nil {
137 t.Errorf("Load unexpectedly returned a Program")
138 }
139 }
140
141 func TestLoad_MissingInitialPackage_AllowErrors(t *testing.T) {
142 if runtime.Compiler == "gccgo" {
143 t.Skip("gccgo has no standard library test files")
144 }
145
146 var conf loader.Config
147 conf.AllowErrors = true
148 conf.Import("nosuchpkg")
149 conf.ImportWithTests("errors")
150
151 prog, err := conf.Load()
152 if err != nil {
153 t.Errorf("Load failed unexpectedly: %v", err)
154 }
155 if prog == nil {
156 t.Fatalf("Load returned a nil Program")
157 }
158 if got, want := created(prog), "errors_test"; got != want {
159 t.Errorf("Created = %s, want %s", got, want)
160 }
161 if got, want := imported(prog), "errors"; got != want {
162 t.Errorf("Imported = %s, want %s", got, want)
163 }
164 }
165
166 func TestCreateUnnamedPackage(t *testing.T) {
167 var conf loader.Config
168 conf.CreateFromFilenames("")
169 prog, err := conf.Load()
170 if err != nil {
171 t.Fatalf("Load failed: %v", err)
172 }
173 if got, want := fmt.Sprint(prog.InitialPackages()), "[(unnamed)]"; got != want {
174 t.Errorf("InitialPackages = %s, want %s", got, want)
175 }
176 }
177
178 func TestLoad_MissingFileInCreatedPackage(t *testing.T) {
179 var conf loader.Config
180 conf.CreateFromFilenames("", "missing.go")
181
182 const wantErr = "couldn't load packages due to errors: (unnamed)"
183
184 prog, err := conf.Load()
185 if prog != nil {
186 t.Errorf("Load unexpectedly returned a Program")
187 }
188 if err == nil {
189 t.Fatalf("Load succeeded unexpectedly, want %q", wantErr)
190 }
191 if err.Error() != wantErr {
192 t.Fatalf("Load failed with wrong error %q, want %q", err, wantErr)
193 }
194 }
195
196 func TestLoad_MissingFileInCreatedPackage_AllowErrors(t *testing.T) {
197 conf := loader.Config{AllowErrors: true}
198 conf.CreateFromFilenames("", "missing.go")
199
200 prog, err := conf.Load()
201 if err != nil {
202 t.Errorf("Load failed: %v", err)
203 }
204 if got, want := fmt.Sprint(prog.InitialPackages()), "[(unnamed)]"; got != want {
205 t.Fatalf("InitialPackages = %s, want %s", got, want)
206 }
207 }
208
209 func TestLoad_ParseError(t *testing.T) {
210 var conf loader.Config
211 conf.CreateFromFilenames("badpkg", "testdata/badpkgdecl.go")
212
213 const wantErr = "couldn't load packages due to errors: badpkg"
214
215 prog, err := conf.Load()
216 if prog != nil {
217 t.Errorf("Load unexpectedly returned a Program")
218 }
219 if err == nil {
220 t.Fatalf("Load succeeded unexpectedly, want %q", wantErr)
221 }
222 if err.Error() != wantErr {
223 t.Fatalf("Load failed with wrong error %q, want %q", err, wantErr)
224 }
225 }
226
227 func TestLoad_ParseError_AllowErrors(t *testing.T) {
228 var conf loader.Config
229 conf.AllowErrors = true
230 conf.CreateFromFilenames("badpkg", "testdata/badpkgdecl.go")
231
232 prog, err := conf.Load()
233 if err != nil {
234 t.Errorf("Load failed unexpectedly: %v", err)
235 }
236 if prog == nil {
237 t.Fatalf("Load returned a nil Program")
238 }
239 if got, want := created(prog), "badpkg"; got != want {
240 t.Errorf("Created = %s, want %s", got, want)
241 }
242
243 badpkg := prog.Created[0]
244 if len(badpkg.Files) != 1 {
245 t.Errorf("badpkg has %d files, want 1", len(badpkg.Files))
246 }
247 wantErr := filepath.Join("testdata", "badpkgdecl.go") + ":1:34: expected 'package', found 'EOF'"
248 if !hasError(badpkg.Errors, wantErr) {
249 t.Errorf("badpkg.Errors = %v, want %s", badpkg.Errors, wantErr)
250 }
251 }
252
253 func TestLoad_FromSource_Success(t *testing.T) {
254 var conf loader.Config
255 conf.CreateFromFilenames("P", "testdata/a.go", "testdata/b.go")
256
257 prog, err := conf.Load()
258 if err != nil {
259 t.Errorf("Load failed unexpectedly: %v", err)
260 }
261 if prog == nil {
262 t.Fatalf("Load returned a nil Program")
263 }
264 if got, want := created(prog), "P"; got != want {
265 t.Errorf("Created = %s, want %s", got, want)
266 }
267 }
268
269 func TestLoad_FromImports_Success(t *testing.T) {
270 if runtime.Compiler == "gccgo" {
271 t.Skip("gccgo has no standard library test files")
272 }
273
274 var conf loader.Config
275 conf.ImportWithTests("fmt")
276 conf.ImportWithTests("errors")
277
278 prog, err := conf.Load()
279 if err != nil {
280 t.Errorf("Load failed unexpectedly: %v", err)
281 }
282 if prog == nil {
283 t.Fatalf("Load returned a nil Program")
284 }
285 if got, want := created(prog), "errors_test fmt_test"; got != want {
286 t.Errorf("Created = %q, want %s", got, want)
287 }
288 if got, want := imported(prog), "errors fmt"; got != want {
289 t.Errorf("Imported = %s, want %s", got, want)
290 }
291 // Check set of transitive packages.
292 // There are >30 and the set may grow over time, so only check a few.
293 want := map[string]bool{
294 "strings": true,
295 "time": true,
296 "runtime": true,
297 "testing": true,
298 "unicode": true,
299 }
300 for _, path := range all(prog) {
301 delete(want, path)
302 }
303 if len(want) > 0 {
304 t.Errorf("AllPackages is missing these keys: %q", keys(want))
305 }
306 }
307
308 func TestLoad_MissingIndirectImport(t *testing.T) {
309 pkgs := map[string]string{
310 "a": `package a; import _ "b"`,
311 "b": `package b; import _ "c"`,
312 }
313 conf := loader.Config{Build: fakeContext(pkgs)}
314 conf.Import("a")
315
316 const wantErr = "couldn't load packages due to errors: b"
317
318 prog, err := conf.Load()
319 if err == nil {
320 t.Errorf("Load succeeded unexpectedly, want %q", wantErr)
321 } else if err.Error() != wantErr {
322 t.Errorf("Load failed with wrong error %q, want %q", err, wantErr)
323 }
324 if prog != nil {
325 t.Errorf("Load unexpectedly returned a Program")
326 }
327 }
328
329 func TestLoad_BadDependency_AllowErrors(t *testing.T) {
330 for _, test := range []struct {
331 descr string
332 pkgs map[string]string
333 wantPkgs string
334 }{
335
336 {
337 descr: "missing dependency",
338 pkgs: map[string]string{
339 "a": `package a; import _ "b"`,
340 "b": `package b; import _ "c"`,
341 },
342 wantPkgs: "a b",
343 },
344 {
345 descr: "bad package decl in dependency",
346 pkgs: map[string]string{
347 "a": `package a; import _ "b"`,
348 "b": `package b; import _ "c"`,
349 "c": `package`,
350 },
351 wantPkgs: "a b",
352 },
353 {
354 descr: "parse error in dependency",
355 pkgs: map[string]string{
356 "a": `package a; import _ "b"`,
357 "b": `package b; import _ "c"`,
358 "c": `package c; var x = `,
359 },
360 wantPkgs: "a b c",
361 },
362 } {
363 conf := loader.Config{
364 AllowErrors: true,
365 Build: fakeContext(test.pkgs),
366 }
367 conf.Import("a")
368
369 prog, err := conf.Load()
370 if err != nil {
371 t.Errorf("%s: Load failed unexpectedly: %v", test.descr, err)
372 }
373 if prog == nil {
374 t.Fatalf("%s: Load returned a nil Program", test.descr)
375 }
376
377 if got, want := imported(prog), "a"; got != want {
378 t.Errorf("%s: Imported = %s, want %s", test.descr, got, want)
379 }
380 if got := all(prog); strings.Join(got, " ") != test.wantPkgs {
381 t.Errorf("%s: AllPackages = %s, want %s", test.descr, got, test.wantPkgs)
382 }
383 }
384 }
385
386 func TestCwd(t *testing.T) {
387 ctxt := fakeContext(map[string]string{"one/two/three": `package three`})
388 for _, test := range []struct {
389 cwd, arg, want string
390 }{
391 {cwd: "/go/src/one", arg: "./two/three", want: "one/two/three"},
392 {cwd: "/go/src/one", arg: "../one/two/three", want: "one/two/three"},
393 {cwd: "/go/src/one", arg: "one/two/three", want: "one/two/three"},
394 {cwd: "/go/src/one/two/three", arg: ".", want: "one/two/three"},
395 {cwd: "/go/src/one", arg: "two/three", want: ""},
396 } {
397 conf := loader.Config{
398 Cwd: test.cwd,
399 Build: ctxt,
400 }
401 conf.Import(test.arg)
402
403 var got string
404 prog, err := conf.Load()
405 if prog != nil {
406 got = imported(prog)
407 }
408 if got != test.want {
409 t.Errorf("Load(%s) from %s: Imported = %s, want %s",
410 test.arg, test.cwd, got, test.want)
411 if err != nil {
412 t.Errorf("Load failed: %v", err)
413 }
414 }
415 }
416 }
417
418 func TestLoad_vendor(t *testing.T) {
419 pkgs := map[string]string{
420 "a": `package a; import _ "x"`,
421 "a/vendor": ``, // mkdir a/vendor
422 "a/vendor/x": `package xa`,
423 "b": `package b; import _ "x"`,
424 "b/vendor": ``, // mkdir b/vendor
425 "b/vendor/x": `package xb`,
426 "c": `package c; import _ "x"`,
427 "x": `package xc`,
428 }
429 conf := loader.Config{Build: fakeContext(pkgs)}
430 conf.Import("a")
431 conf.Import("b")
432 conf.Import("c")
433
434 prog, err := conf.Load()
435 if err != nil {
436 t.Fatal(err)
437 }
438
439 // Check that a, b, and c see different versions of x.
440 for _, r := range "abc" {
441 name := string(r)
442 got := prog.Package(name).Pkg.Imports()[0]
443 want := "x" + name
444 if got.Name() != want {
445 t.Errorf("package %s import %q = %s, want %s",
446 name, "x", got.Name(), want)
447 }
448 }
449 }
450
451 func TestVendorCwd(t *testing.T) {
452 // Test the interaction of cwd and vendor directories.
453 ctxt := fakeContext(map[string]string{
454 "net": ``, // mkdir net
455 "net/http": `package http; import _ "hpack"`,
456 "vendor": ``, // mkdir vendor
457 "vendor/hpack": `package vendorhpack`,
458 "hpack": `package hpack`,
459 })
460 for i, test := range []struct {
461 cwd, arg, want string
462 }{
463 {cwd: "/go/src/net", arg: "http"}, // not found
464 {cwd: "/go/src/net", arg: "./http", want: "net/http vendor/hpack"},
465 {cwd: "/go/src/net", arg: "hpack", want: "vendor/hpack"},
466 {cwd: "/go/src/vendor", arg: "hpack", want: "vendor/hpack"},
467 {cwd: "/go/src/vendor", arg: "./hpack", want: "vendor/hpack"},
468 } {
469 conf := loader.Config{
470 Cwd: test.cwd,
471 Build: ctxt,
472 }
473 conf.Import(test.arg)
474
475 var got string
476 prog, err := conf.Load()
477 if prog != nil {
478 got = strings.Join(all(prog), " ")
479 }
480 if got != test.want {
481 t.Errorf("#%d: Load(%s) from %s: got %s, want %s",
482 i, test.arg, test.cwd, got, test.want)
483 if err != nil {
484 t.Errorf("Load failed: %v", err)
485 }
486 }
487 }
488 }
489
490 func TestVendorCwdIssue16580(t *testing.T) {
491 // Regression test for Go issue 16580.
492 // Import decls in "created" packages were vendor-resolved
493 // w.r.t. cwd, not the parent directory of the package's files.
494 ctxt := fakeContext(map[string]string{
495 "a": ``, // mkdir a
496 "a/vendor": ``, // mkdir a/vendor
497 "a/vendor/b": `package b; const X = true`,
498 "b": `package b; const X = false`,
499 })
500 for _, test := range []struct {
501 filename, cwd string
502 want bool // expected value of b.X; depends on filename, not on cwd
503 }{
504 {filename: "c.go", cwd: "/go/src", want: false},
505 {filename: "c.go", cwd: "/go/src/a", want: false},
506 {filename: "c.go", cwd: "/go/src/a/b", want: false},
507 {filename: "c.go", cwd: "/go/src/a/vendor/b", want: false},
508
509 {filename: "/go/src/a/c.go", cwd: "/go/src", want: true},
510 {filename: "/go/src/a/c.go", cwd: "/go/src/a", want: true},
511 {filename: "/go/src/a/c.go", cwd: "/go/src/a/b", want: true},
512 {filename: "/go/src/a/c.go", cwd: "/go/src/a/vendor/b", want: true},
513
514 {filename: "/go/src/c/c.go", cwd: "/go/src", want: false},
515 {filename: "/go/src/c/c.go", cwd: "/go/src/a", want: false},
516 {filename: "/go/src/c/c.go", cwd: "/go/src/a/b", want: false},
517 {filename: "/go/src/c/c.go", cwd: "/go/src/a/vendor/b", want: false},
518 } {
519 conf := loader.Config{
520 Cwd: test.cwd,
521 Build: ctxt,
522 }
523 f, err := conf.ParseFile(test.filename, `package dummy; import "b"; const X = b.X`)
524 if err != nil {
525 t.Fatal(f)
526 }
527 conf.CreateFromFiles("dummy", f)
528
529 prog, err := conf.Load()
530 if err != nil {
531 t.Errorf("%+v: Load failed: %v", test, err)
532 continue
533 }
534
535 x := constant.BoolVal(prog.Created[0].Pkg.Scope().Lookup("X").(*types.Const).Val())
536 if x != test.want {
537 t.Errorf("%+v: b.X = %t", test, x)
538 }
539 }
540
541 // TODO(adonovan): also test imports within XTestGoFiles.
542 }
543
544 // TODO(adonovan): more Load tests:
545 //
546 // failures:
547 // - to parse package decl of *_test.go files
548 // - to parse package decl of external *_test.go files
549 // - to parse whole of *_test.go files
550 // - to parse whole of external *_test.go files
551 // - to open a *.go file during import scanning
552 // - to import from binary
553
554 // features:
555 // - InitialPackages
556 // - PackageCreated hook
557 // - TypeCheckFuncBodies hook
558
559 func TestTransitivelyErrorFreeFlag(t *testing.T) {
560 // Create a minimal custom build.Context
561 // that fakes the following packages:
562 //
563 // a --> b --> c! c has an error
564 // \ d and e are transitively error-free.
565 // e --> d
566 //
567 // Each package [a-e] consists of one file, x.go.
568 pkgs := map[string]string{
569 "a": `package a; import (_ "b"; _ "e")`,
570 "b": `package b; import _ "c"`,
571 "c": `package c; func f() { _ = int(false) }`, // type error within function body
572 "d": `package d;`,
573 "e": `package e; import _ "d"`,
574 }
575 conf := loader.Config{
576 AllowErrors: true,
577 Build: fakeContext(pkgs),
578 }
579 conf.Import("a")
580
581 prog, err := conf.Load()
582 if err != nil {
583 t.Errorf("Load failed: %s", err)
584 }
585 if prog == nil {
586 t.Fatalf("Load returned nil *Program")
587 }
588
589 for pkg, info := range prog.AllPackages {
590 var wantErr, wantTEF bool
591 switch pkg.Path() {
592 case "a", "b":
593 case "c":
594 wantErr = true
595 case "d", "e":
596 wantTEF = true
597 default:
598 t.Errorf("unexpected package: %q", pkg.Path())
599 continue
600 }
601
602 if (info.Errors != nil) != wantErr {
603 if wantErr {
604 t.Errorf("Package %q.Error = nil, want error", pkg.Path())
605 } else {
606 t.Errorf("Package %q has unexpected Errors: %v",
607 pkg.Path(), info.Errors)
608 }
609 }
610
611 if info.TransitivelyErrorFree != wantTEF {
612 t.Errorf("Package %q.TransitivelyErrorFree=%t, want %t",
613 pkg.Path(), info.TransitivelyErrorFree, wantTEF)
614 }
615 }
616 }
617
618 // Test that syntax (scan/parse), type, and loader errors are recorded
619 // (in PackageInfo.Errors) and reported (via Config.TypeChecker.Error).
620 func TestErrorReporting(t *testing.T) {
621 pkgs := map[string]string{
622 "a": `package a; import (_ "b"; _ "c"); var x int = false`,
623 "b": `package b; 'syntax error!`,
624 }
625 conf := loader.Config{
626 AllowErrors: true,
627 Build: fakeContext(pkgs),
628 }
629 var mu sync.Mutex
630 var allErrors []error
631 conf.TypeChecker.Error = func(err error) {
632 mu.Lock()
633 allErrors = append(allErrors, err)
634 mu.Unlock()
635 }
636 conf.Import("a")
637
638 prog, err := conf.Load()
639 if err != nil {
640 t.Errorf("Load failed: %s", err)
641 }
642 if prog == nil {
643 t.Fatalf("Load returned nil *Program")
644 }
645
646 // TODO(adonovan): test keys of ImportMap.
647
648 // Check errors recorded in each PackageInfo.
649 for pkg, info := range prog.AllPackages {
650 switch pkg.Path() {
651 case "a":
652 // The match below is unfortunately vague, because in go1.16 the error
653 // message in go/types changed from "cannot convert ..." to "cannot use
654 // ... as ... in assignment".
655 if !hasError(info.Errors, "cannot") {
656 t.Errorf("a.Errors = %v, want bool assignment (type) error", info.Errors)
657 }
658 if !hasError(info.Errors, "could not import c") {
659 t.Errorf("a.Errors = %v, want import (loader) error", info.Errors)
660 }
661 case "b":
662 if !hasError(info.Errors, "rune literal not terminated") {
663 t.Errorf("b.Errors = %v, want unterminated literal (syntax) error", info.Errors)
664 }
665 }
666 }
667
668 // Check errors reported via error handler.
669 if !hasError(allErrors, "cannot") ||
670 !hasError(allErrors, "rune literal not terminated") ||
671 !hasError(allErrors, "could not import c") {
672 t.Errorf("allErrors = %v, want syntax, type and loader errors", allErrors)
673 }
674 }
675
676 func TestCycles(t *testing.T) {
677 for _, test := range []struct {
678 descr string
679 ctxt *build.Context
680 wantErr string
681 }{
682 {
683 "self-cycle",
684 fakeContext(map[string]string{
685 "main": `package main; import _ "selfcycle"`,
686 "selfcycle": `package selfcycle; import _ "selfcycle"`,
687 }),
688 `import cycle: selfcycle -> selfcycle`,
689 },
690 {
691 "three-package cycle",
692 fakeContext(map[string]string{
693 "main": `package main; import _ "a"`,
694 "a": `package a; import _ "b"`,
695 "b": `package b; import _ "c"`,
696 "c": `package c; import _ "a"`,
697 }),
698 `import cycle: c -> a -> b -> c`,
699 },
700 {
701 "self-cycle in dependency of test file",
702 buildutil.FakeContext(map[string]map[string]string{
703 "main": {
704 "main.go": `package main`,
705 "main_test.go": `package main; import _ "a"`,
706 },
707 "a": {
708 "a.go": `package a; import _ "a"`,
709 },
710 }),
711 `import cycle: a -> a`,
712 },
713 // TODO(adonovan): fix: these fail
714 // {
715 // "two-package cycle in dependency of test file",
716 // buildutil.FakeContext(map[string]map[string]string{
717 // "main": {
718 // "main.go": `package main`,
719 // "main_test.go": `package main; import _ "a"`,
720 // },
721 // "a": {
722 // "a.go": `package a; import _ "main"`,
723 // },
724 // }),
725 // `import cycle: main -> a -> main`,
726 // },
727 // {
728 // "self-cycle in augmented package",
729 // buildutil.FakeContext(map[string]map[string]string{
730 // "main": {
731 // "main.go": `package main`,
732 // "main_test.go": `package main; import _ "main"`,
733 // },
734 // }),
735 // `import cycle: main -> main`,
736 // },
737 } {
738 conf := loader.Config{
739 AllowErrors: true,
740 Build: test.ctxt,
741 }
742 var mu sync.Mutex
743 var allErrors []error
744 conf.TypeChecker.Error = func(err error) {
745 mu.Lock()
746 allErrors = append(allErrors, err)
747 mu.Unlock()
748 }
749 conf.ImportWithTests("main")
750
751 prog, err := conf.Load()
752 if err != nil {
753 t.Errorf("%s: Load failed: %s", test.descr, err)
754 }
755 if prog == nil {
756 t.Fatalf("%s: Load returned nil *Program", test.descr)
757 }
758
759 if !hasError(allErrors, test.wantErr) {
760 t.Errorf("%s: Load() errors = %q, want %q",
761 test.descr, allErrors, test.wantErr)
762 }
763 }
764
765 // TODO(adonovan):
766 // - Test that in a legal test cycle, none of the symbols
767 // defined by augmentation are visible via import.
768 }
769
770 // ---- utilities ----
771
772 // Simplifying wrapper around buildutil.FakeContext for single-file packages.
773 func fakeContext(pkgs map[string]string) *build.Context {
774 pkgs2 := make(map[string]map[string]string)
775 for path, content := range pkgs {
776 pkgs2[path] = map[string]string{"x.go": content}
777 }
778 return buildutil.FakeContext(pkgs2)
779 }
780
781 func hasError(errors []error, substr string) bool {
782 for _, err := range errors {
783 if strings.Contains(err.Error(), substr) {
784 return true
785 }
786 }
787 return false
788 }
789
790 func keys(m map[string]bool) (keys []string) {
791 for key := range m {
792 keys = append(keys, key)
793 }
794 sort.Strings(keys)
795 return
796 }
797
798 // Returns all loaded packages.
799 func all(prog *loader.Program) []string {
800 var pkgs []string
801 for _, info := range prog.AllPackages {
802 pkgs = append(pkgs, info.Pkg.Path())
803 }
804 sort.Strings(pkgs)
805 return pkgs
806 }
807
808 // Returns initially imported packages, as a string.
809 func imported(prog *loader.Program) string {
810 var pkgs []string
811 for _, info := range prog.Imported {
812 pkgs = append(pkgs, info.Pkg.Path())
813 }
814 sort.Strings(pkgs)
815 return strings.Join(pkgs, " ")
816 }
817
818 // Returns initially created packages, as a string.
819 func created(prog *loader.Program) string {
820 var pkgs []string
821 for _, info := range prog.Created {
822 pkgs = append(pkgs, info.Pkg.Path())
823 }
824 return strings.Join(pkgs, " ")
825 }
826
827 // Load package "io" twice in parallel.
828 // When run with -race, this is a regression test for Go issue 20718, in
829 // which the global "unsafe" package was modified concurrently.
830 func TestLoad1(t *testing.T) { loadIO(t) }
831 func TestLoad2(t *testing.T) { loadIO(t) }
832
833 func loadIO(t *testing.T) {
834 t.Parallel()
835 conf := &loader.Config{ImportPkgs: map[string]bool{"io": false}}
836 if _, err := conf.Load(); err != nil {
837 t.Fatal(err)
838 }
839 }
840
841 func TestCgoCwdIssue46877(t *testing.T) {
842 testenv.NeedsTool(t, "go")
843 testenv.NeedsTool(t, "cgo")
844 var conf loader.Config
845 conf.Import("golang.org/x/tools/go/loader/testdata/issue46877")
846 if _, err := conf.Load(); err != nil {
847 t.Errorf("Load failed: %v", err)
848 }
849 }