1 // Copyright 2011 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.
18 func TestMain(m *testing.M) {
19 Default.GOROOT = testenv.GOROOT(nil)
23 func TestMatch(t *testing.T) {
26 match := func(tag string, want map[string]bool) {
28 m := make(map[string]bool)
29 if !ctxt.matchAuto(tag, m) {
30 t.Errorf("%s context should match %s, does not", what, tag)
32 if !reflect.DeepEqual(m, want) {
33 t.Errorf("%s tags = %v, want %v", tag, m, want)
36 nomatch := func(tag string, want map[string]bool) {
38 m := make(map[string]bool)
39 if ctxt.matchAuto(tag, m) {
40 t.Errorf("%s context should NOT match %s, does", what, tag)
42 if !reflect.DeepEqual(m, want) {
43 t.Errorf("%s tags = %v, want %v", tag, m, want)
47 match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true})
48 match(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
49 nomatch(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
52 ctxt.BuildTags = []string{"foo"}
53 match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true})
54 match(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
55 nomatch(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
56 match(runtime.GOOS+","+runtime.GOARCH+",!bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true})
57 nomatch(runtime.GOOS+","+runtime.GOARCH+",bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true})
60 func TestDotSlashImport(t *testing.T) {
61 p, err := ImportDir("testdata/other", 0)
65 if len(p.Imports) != 1 || p.Imports[0] != "./file" {
66 t.Fatalf("testdata/other: Imports=%v, want [./file]", p.Imports)
69 p1, err := Import("./file", "testdata/other", 0)
73 if p1.Name != "file" {
74 t.Fatalf("./file: Name=%q, want %q", p1.Name, "file")
76 dir := filepath.Clean("testdata/other/file") // Clean to use \ on Windows
78 t.Fatalf("./file: Dir=%q, want %q", p1.Name, dir)
82 func TestEmptyImport(t *testing.T) {
83 p, err := Import("", testenv.GOROOT(t), FindOnly)
85 t.Fatal(`Import("") returned nil error.`)
88 t.Fatal(`Import("") returned nil package.`)
90 if p.ImportPath != "" {
91 t.Fatalf("ImportPath=%q, want %q.", p.ImportPath, "")
95 func TestEmptyFolderImport(t *testing.T) {
96 _, err := Import(".", "testdata/empty", 0)
97 if _, ok := err.(*NoGoError); !ok {
98 t.Fatal(`Import("testdata/empty") did not return NoGoError.`)
102 func TestMultiplePackageImport(t *testing.T) {
103 pkg, err := Import(".", "testdata/multi", 0)
105 mpe, ok := err.(*MultiplePackageError)
107 t.Fatal(`Import("testdata/multi") did not return MultiplePackageError.`)
109 want := &MultiplePackageError{
110 Dir: filepath.FromSlash("testdata/multi"),
111 Packages: []string{"main", "test_package"},
112 Files: []string{"file.go", "file_appengine.go"},
114 if !reflect.DeepEqual(mpe, want) {
115 t.Errorf("err = %#v; want %#v", mpe, want)
118 // TODO(#45999): Since the name is ambiguous, pkg.Name should be left empty.
119 if wantName := "main"; pkg.Name != wantName {
120 t.Errorf("pkg.Name = %q; want %q", pkg.Name, wantName)
123 if wantGoFiles := []string{"file.go", "file_appengine.go"}; !reflect.DeepEqual(pkg.GoFiles, wantGoFiles) {
124 t.Errorf("pkg.GoFiles = %q; want %q", pkg.GoFiles, wantGoFiles)
127 if wantInvalidFiles := []string{"file_appengine.go"}; !reflect.DeepEqual(pkg.InvalidGoFiles, wantInvalidFiles) {
128 t.Errorf("pkg.InvalidGoFiles = %q; want %q", pkg.InvalidGoFiles, wantInvalidFiles)
132 func TestLocalDirectory(t *testing.T) {
133 if runtime.GOOS == "ios" {
134 t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH)
137 cwd, err := os.Getwd()
142 p, err := ImportDir(cwd, 0)
146 if p.ImportPath != "go/build" {
147 t.Fatalf("ImportPath=%q, want %q", p.ImportPath, "go/build")
151 var shouldBuildTests = []struct {
161 content: "// +build yes\n\n" +
163 tags: map[string]bool{"yes": true},
168 content: "//go:build yes\n" +
170 tags: map[string]bool{"yes": true},
175 content: "// +build no yes\n\n" +
177 tags: map[string]bool{"yes": true, "no": true},
182 content: "//go:build no || yes\n" +
184 tags: map[string]bool{"yes": true, "no": true},
189 content: "// +build no,yes\n\n" +
191 tags: map[string]bool{"yes": true, "no": true},
196 content: "//go:build no && yes\n" +
198 tags: map[string]bool{"yes": true, "no": true},
203 content: "// +build cgo\n\n" +
204 "// Copyright The Go Authors.\n\n" +
205 "// This package implements parsing of tags like\n" +
208 tags: map[string]bool{"cgo": true},
213 content: "//go:build cgo\n" +
214 "// Copyright The Go Authors.\n\n" +
215 "// This package implements parsing of tags like\n" +
218 tags: map[string]bool{"cgo": true},
222 name: "AfterPackage",
223 content: "// Copyright The Go Authors.\n\n" +
224 "package build\n\n" +
225 "// shouldBuild checks tags given by lines of the form\n" +
228 "func shouldBuild(content []byte)\n",
229 tags: map[string]bool{},
234 content: "// +build yes\n" +
236 tags: map[string]bool{},
241 content: "//go:build yes\n" +
243 tags: map[string]bool{"yes": true},
248 content: "// +build no\n" +
250 tags: map[string]bool{},
255 content: "//go:build no\n" +
257 tags: map[string]bool{"no": true},
262 content: "//go:binary-only-package\n" +
265 tags: map[string]bool{},
271 content: "//go:binary-only-package\n" +
274 tags: map[string]bool{"no": true},
279 name: "ValidGoBuild",
280 content: "// +build yes\n\n" +
283 tags: map[string]bool{"no": true},
287 name: "MissingBuild2",
289 "// +build yes\n\n" +
292 tags: map[string]bool{"no": true},
301 tags: map[string]bool{},
311 tags: map[string]bool{"no": true},
316 content: "/*/*/ /* hi *//* \n" +
321 tags: map[string]bool{"no": true},
326 content: "/**///go:build no\n" +
328 tags: map[string]bool{},
336 tags: map[string]bool{"no": true},
341 func TestShouldBuild(t *testing.T) {
342 for _, tt := range shouldBuildTests {
343 t.Run(tt.name, func(t *testing.T) {
344 ctx := &Context{BuildTags: []string{"yes"}}
345 tags := map[string]bool{}
346 shouldBuild, binaryOnly, err := ctx.shouldBuild([]byte(tt.content), tags)
347 if shouldBuild != tt.shouldBuild || binaryOnly != tt.binaryOnly || !reflect.DeepEqual(tags, tt.tags) || err != tt.err {
348 t.Errorf("mismatch:\n"+
349 "have shouldBuild=%v, binaryOnly=%v, tags=%v, err=%v\n"+
350 "want shouldBuild=%v, binaryOnly=%v, tags=%v, err=%v",
351 shouldBuild, binaryOnly, tags, err,
352 tt.shouldBuild, tt.binaryOnly, tt.tags, tt.err)
358 func TestGoodOSArchFile(t *testing.T) {
359 ctx := &Context{BuildTags: []string{"linux"}, GOOS: "darwin"}
360 m := map[string]bool{}
361 want := map[string]bool{"linux": true}
362 if !ctx.goodOSArchFile("hello_linux.go", m) {
363 t.Errorf("goodOSArchFile(hello_linux.go) = false, want true")
365 if !reflect.DeepEqual(m, want) {
366 t.Errorf("goodOSArchFile(hello_linux.go) tags = %v, want %v", m, want)
370 type readNopCloser struct {
374 func (r readNopCloser) Close() error {
379 ctxtP9 = Context{GOARCH: "arm", GOOS: "plan9"}
380 ctxtAndroid = Context{GOARCH: "arm", GOOS: "android"}
383 var matchFileTests = []struct {
389 {ctxtP9, "foo_arm.go", "", true},
390 {ctxtP9, "foo1_arm.go", "// +build linux\n\npackage main\n", false},
391 {ctxtP9, "foo_darwin.go", "", false},
392 {ctxtP9, "foo.go", "", true},
393 {ctxtP9, "foo1.go", "// +build linux\n\npackage main\n", false},
394 {ctxtP9, "foo.badsuffix", "", false},
395 {ctxtAndroid, "foo_linux.go", "", true},
396 {ctxtAndroid, "foo_android.go", "", true},
397 {ctxtAndroid, "foo_plan9.go", "", false},
398 {ctxtAndroid, "android.go", "", true},
399 {ctxtAndroid, "plan9.go", "", true},
400 {ctxtAndroid, "plan9_test.go", "", true},
401 {ctxtAndroid, "arm.s", "", true},
402 {ctxtAndroid, "amd64.s", "", true},
405 func TestMatchFile(t *testing.T) {
406 for _, tt := range matchFileTests {
408 ctxt.OpenFile = func(path string) (r io.ReadCloser, err error) {
409 if path != "x+"+tt.name {
410 t.Fatalf("OpenFile asked for %q, expected %q", path, "x+"+tt.name)
412 return &readNopCloser{strings.NewReader(tt.data)}, nil
414 ctxt.JoinPath = func(elem ...string) string {
415 return strings.Join(elem, "+")
417 match, err := ctxt.MatchFile("x", tt.name)
418 if match != tt.match || err != nil {
419 t.Fatalf("MatchFile(%q) = %v, %v, want %v, nil", tt.name, match, err, tt.match)
424 func TestImportCmd(t *testing.T) {
425 if runtime.GOOS == "ios" {
426 t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH)
429 p, err := Import("cmd/internal/objfile", "", 0)
433 if !strings.HasSuffix(filepath.ToSlash(p.Dir), "src/cmd/internal/objfile") {
434 t.Fatalf("Import cmd/internal/objfile returned Dir=%q, want %q", filepath.ToSlash(p.Dir), ".../src/cmd/internal/objfile")
439 expandSrcDirPath = filepath.Join(string(filepath.Separator)+"projects", "src", "add")
442 var expandSrcDirTests = []struct {
443 input, expected string
445 {"-L ${SRCDIR}/libs -ladd", "-L /projects/src/add/libs -ladd"},
446 {"${SRCDIR}/add_linux_386.a -pthread -lstdc++", "/projects/src/add/add_linux_386.a -pthread -lstdc++"},
447 {"Nothing to expand here!", "Nothing to expand here!"},
452 {"$FOO ${BAR}", "$FOO ${BAR}"},
453 {"Find me the $SRCDIRECTORY.", "Find me the $SRCDIRECTORY."},
454 {"$SRCDIR is missing braces", "$SRCDIR is missing braces"},
457 func TestExpandSrcDir(t *testing.T) {
458 for _, test := range expandSrcDirTests {
459 output, _ := expandSrcDir(test.input, expandSrcDirPath)
460 if output != test.expected {
461 t.Errorf("%q expands to %q with SRCDIR=%q when %q is expected", test.input, output, expandSrcDirPath, test.expected)
463 t.Logf("%q expands to %q with SRCDIR=%q", test.input, output, expandSrcDirPath)
468 func TestShellSafety(t *testing.T) {
470 input, srcdir, expected string
473 {"-I${SRCDIR}/../include", "/projects/src/issue 11868", "-I/projects/src/issue 11868/../include", true},
474 {"-I${SRCDIR}", "~wtf$@%^", "-I~wtf$@%^", true},
475 {"-X${SRCDIR}/1,${SRCDIR}/2", "/projects/src/issue 11868", "-X/projects/src/issue 11868/1,/projects/src/issue 11868/2", true},
476 {"-I/tmp -I/tmp", "/tmp2", "-I/tmp -I/tmp", true},
477 {"-I/tmp", "/tmp/[0]", "-I/tmp", true},
478 {"-I${SRCDIR}/dir", "/tmp/[0]", "-I/tmp/[0]/dir", false},
479 {"-I${SRCDIR}/dir", "/tmp/go go", "-I/tmp/go go/dir", true},
480 {"-I${SRCDIR}/dir dir", "/tmp/go", "-I/tmp/go/dir dir", true},
482 for _, test := range tests {
483 output, ok := expandSrcDir(test.input, test.srcdir)
484 if ok != test.result {
485 t.Errorf("Expected %t while %q expands to %q with SRCDIR=%q; got %t", test.result, test.input, output, test.srcdir, ok)
487 if output != test.expected {
488 t.Errorf("Expected %q while %q expands with SRCDIR=%q; got %q", test.expected, test.input, test.srcdir, output)
493 // Want to get a "cannot find package" error when directory for package does not exist.
494 // There should be valid partial information in the returned non-nil *Package.
495 func TestImportDirNotExist(t *testing.T) {
496 testenv.MustHaveGoBuild(t) // really must just have source
499 emptyDir := t.TempDir()
501 ctxt.GOPATH = emptyDir
509 {"Import(full, 0)", "go/build/doesnotexist", "", 0},
510 {"Import(local, 0)", "./doesnotexist", filepath.Join(ctxt.GOROOT, "src/go/build"), 0},
511 {"Import(full, FindOnly)", "go/build/doesnotexist", "", FindOnly},
512 {"Import(local, FindOnly)", "./doesnotexist", filepath.Join(ctxt.GOROOT, "src/go/build"), FindOnly},
515 defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE"))
517 for _, GO111MODULE := range []string{"off", "on"} {
518 t.Run("GO111MODULE="+GO111MODULE, func(t *testing.T) {
519 os.Setenv("GO111MODULE", GO111MODULE)
521 for _, test := range tests {
522 p, err := ctxt.Import(test.path, test.srcDir, test.mode)
524 errOk := (err != nil && strings.HasPrefix(err.Error(), "cannot find package"))
525 wantErr := `"cannot find package" error`
526 if test.srcDir == "" {
527 if err != nil && strings.Contains(err.Error(), "is not in GOROOT") {
530 wantErr = `"cannot find package" or "is not in GOROOT" error`
533 t.Errorf("%s got error: %q, want %s", test.label, err, wantErr)
535 // If an error occurs, build.Import is documented to return
536 // a non-nil *Package containing partial information.
538 t.Fatalf(`%s got nil p, want non-nil *Package`, test.label)
540 // Verify partial information in p.
541 if p.ImportPath != "go/build/doesnotexist" {
542 t.Errorf(`%s got p.ImportPath: %q, want "go/build/doesnotexist"`, test.label, p.ImportPath)
549 func TestImportVendor(t *testing.T) {
550 testenv.MustHaveGoBuild(t) // really must just have source
552 t.Setenv("GO111MODULE", "off")
555 wd, err := os.Getwd()
559 ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor")
560 p, err := ctxt.Import("c/d", filepath.Join(ctxt.GOPATH, "src/a/b"), 0)
562 t.Fatalf("cannot find vendored c/d from testdata src/a/b directory: %v", err)
564 want := "a/vendor/c/d"
565 if p.ImportPath != want {
566 t.Fatalf("Import succeeded but found %q, want %q", p.ImportPath, want)
570 func BenchmarkImportVendor(b *testing.B) {
571 testenv.MustHaveGoBuild(b) // really must just have source
573 b.Setenv("GO111MODULE", "off")
576 wd, err := os.Getwd()
580 ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor")
581 dir := filepath.Join(ctxt.GOPATH, "src/a/b")
583 for i := 0; i < b.N; i++ {
584 _, err := ctxt.Import("c/d", dir, 0)
586 b.Fatalf("cannot find vendored c/d from testdata src/a/b directory: %v", err)
591 func TestImportVendorFailure(t *testing.T) {
592 testenv.MustHaveGoBuild(t) // really must just have source
594 t.Setenv("GO111MODULE", "off")
597 wd, err := os.Getwd()
601 ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor")
602 p, err := ctxt.Import("x.com/y/z", filepath.Join(ctxt.GOPATH, "src/a/b"), 0)
604 t.Fatalf("found made-up package x.com/y/z in %s", p.Dir)
608 if !strings.Contains(e, " (vendor tree)") {
609 t.Fatalf("error on failed import does not mention GOROOT/src/vendor directory:\n%s", e)
613 func TestImportVendorParentFailure(t *testing.T) {
614 testenv.MustHaveGoBuild(t) // really must just have source
616 t.Setenv("GO111MODULE", "off")
619 wd, err := os.Getwd()
623 ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor")
624 // This import should fail because the vendor/c directory has no source code.
625 p, err := ctxt.Import("c", filepath.Join(ctxt.GOPATH, "src/a/b"), 0)
627 t.Fatalf("found empty parent in %s", p.Dir)
629 if p != nil && p.Dir != "" {
630 t.Fatalf("decided to use %s", p.Dir)
633 if !strings.Contains(e, " (vendor tree)") {
634 t.Fatalf("error on failed import does not mention GOROOT/src/vendor directory:\n%s", e)
638 // Check that a package is loaded in module mode if GO111MODULE=on, even when
639 // no go.mod file is present. It should fail to resolve packages outside std.
640 // Verifies golang.org/issue/34669.
641 func TestImportPackageOutsideModule(t *testing.T) {
642 testenv.MustHaveGoBuild(t)
644 // Disable module fetching for this test so that 'go list' fails quickly
645 // without trying to find the latest version of a module.
646 t.Setenv("GOPROXY", "off")
648 // Create a GOPATH in a temporary directory. We don't use testdata
649 // because it's in GOROOT, which interferes with the module heuristic.
650 gopath := t.TempDir()
651 if err := os.MkdirAll(filepath.Join(gopath, "src/example.com/p"), 0777); err != nil {
654 if err := os.WriteFile(filepath.Join(gopath, "src/example.com/p/p.go"), []byte("package p"), 0666); err != nil {
658 t.Setenv("GO111MODULE", "on")
659 t.Setenv("GOPATH", gopath)
662 ctxt.Dir = filepath.Join(gopath, "src/example.com/p")
664 want := "go.mod file not found in current directory or any parent directory"
665 if _, err := ctxt.Import("example.com/p", gopath, FindOnly); err == nil {
666 t.Fatal("importing package when no go.mod is present succeeded unexpectedly")
667 } else if errStr := err.Error(); !strings.Contains(errStr, want) {
668 t.Fatalf("error when importing package when no go.mod is present: got %q; want %q", errStr, want)
670 t.Logf(`ctxt.Import("example.com/p", _, FindOnly): %v`, err)
674 func TestImportDirTarget(t *testing.T) {
675 testenv.MustHaveGoBuild(t) // really must just have source
678 p, err := ctxt.ImportDir(filepath.Join(testenv.GOROOT(t), "src/path"), 0)
682 if p.PkgTargetRoot == "" || p.PkgObj == "" {
683 t.Errorf("p.PkgTargetRoot == %q, p.PkgObj == %q, want non-empty", p.PkgTargetRoot, p.PkgObj)
687 // TestIssue23594 prevents go/build from regressing and populating Package.Doc
688 // from comments in test files.
689 func TestIssue23594(t *testing.T) {
690 // Package testdata/doc contains regular and external test files
691 // with comments attached to their package declarations. The names of the files
692 // ensure that we see the comments from the test files first.
693 p, err := ImportDir("testdata/doc", 0)
695 t.Fatalf("could not import testdata: %v", err)
698 if p.Doc != "Correct" {
699 t.Fatalf("incorrectly set .Doc to %q", p.Doc)
703 // TestMissingImportErrorRepetition checks that when an unknown package is
704 // imported, the package path is only shown once in the error.
705 // Verifies golang.org/issue/34752.
706 func TestMissingImportErrorRepetition(t *testing.T) {
707 testenv.MustHaveGoBuild(t) // need 'go list' internally
709 if err := os.WriteFile(filepath.Join(tmp, "go.mod"), []byte("module m"), 0666); err != nil {
712 t.Setenv("GO111MODULE", "on")
713 t.Setenv("GOPROXY", "off")
714 t.Setenv("GONOPROXY", "none")
719 pkgPath := "example.com/hello"
720 _, err := ctxt.Import(pkgPath, tmp, FindOnly)
722 t.Fatal("unexpected success")
725 // Don't count the package path with a URL like https://...?go-get=1.
726 // See golang.org/issue/35986.
727 errStr := strings.ReplaceAll(err.Error(), "://"+pkgPath+"?go-get=1", "://...?go-get=1")
729 // Also don't count instances in suggested "go get" or similar commands
730 // (see https://golang.org/issue/41576). The suggested command typically
731 // follows a semicolon.
732 errStr, _, _ = strings.Cut(errStr, ";")
734 if n := strings.Count(errStr, pkgPath); n != 1 {
735 t.Fatalf("package path %q appears in error %d times; should appear once\nerror: %v", pkgPath, n, err)
739 // TestCgoImportsIgnored checks that imports in cgo files are not included
740 // in the imports list when cgo is disabled.
741 // Verifies golang.org/issue/35946.
742 func TestCgoImportsIgnored(t *testing.T) {
744 ctxt.CgoEnabled = false
745 p, err := ctxt.ImportDir("testdata/cgo_disabled", 0)
749 for _, path := range p.Imports {
750 if path == "should/be/ignored" {
751 t.Errorf("found import %q in ignored cgo file", path)
756 // Issue #52053. Check that if there is a file x_GOOS_GOARCH.go that both
757 // GOOS and GOARCH show up in the Package.AllTags field. We test both the
758 // case where the file matches and where the file does not match.
759 // The latter case used to fail, incorrectly omitting GOOS.
760 func TestAllTags(t *testing.T) {
764 p, err := ctxt.ImportDir("testdata/alltags", 0)
768 want := []string{"arm", "netbsd"}
769 if !reflect.DeepEqual(p.AllTags, want) {
770 t.Errorf("AllTags = %v, want %v", p.AllTags, want)
772 wantFiles := []string{"alltags.go", "x_netbsd_arm.go"}
773 if !reflect.DeepEqual(p.GoFiles, wantFiles) {
774 t.Errorf("GoFiles = %v, want %v", p.GoFiles, wantFiles)
777 ctxt.GOARCH = "amd64"
779 p, err = ctxt.ImportDir("testdata/alltags", 0)
783 if !reflect.DeepEqual(p.AllTags, want) {
784 t.Errorf("AllTags = %v, want %v", p.AllTags, want)
786 wantFiles = []string{"alltags.go"}
787 if !reflect.DeepEqual(p.GoFiles, wantFiles) {
788 t.Errorf("GoFiles = %v, want %v", p.GoFiles, wantFiles)