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.
4
5package build
6
7import (
8	"flag"
9	"internal/testenv"
10	"io"
11	"os"
12	"path/filepath"
13	"reflect"
14	"runtime"
15	"strings"
16	"testing"
17)
18
19func TestMain(m *testing.M) {
20	flag.Parse()
21	if goTool, err := testenv.GoTool(); err == nil {
22		os.Setenv("PATH", filepath.Dir(goTool)+string(os.PathListSeparator)+os.Getenv("PATH"))
23	}
24	os.Exit(m.Run())
25}
26
27func TestMatch(t *testing.T) {
28	ctxt := Default
29	what := "default"
30	match := func(tag string, want map[string]bool) {
31		t.Helper()
32		m := make(map[string]bool)
33		if !ctxt.matchAuto(tag, m) {
34			t.Errorf("%s context should match %s, does not", what, tag)
35		}
36		if !reflect.DeepEqual(m, want) {
37			t.Errorf("%s tags = %v, want %v", tag, m, want)
38		}
39	}
40	nomatch := func(tag string, want map[string]bool) {
41		t.Helper()
42		m := make(map[string]bool)
43		if ctxt.matchAuto(tag, m) {
44			t.Errorf("%s context should NOT match %s, does", what, tag)
45		}
46		if !reflect.DeepEqual(m, want) {
47			t.Errorf("%s tags = %v, want %v", tag, m, want)
48		}
49	}
50
51	match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true})
52	match(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
53	nomatch(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
54
55	what = "modified"
56	ctxt.BuildTags = []string{"foo"}
57	match(runtime.GOOS+","+runtime.GOARCH, map[string]bool{runtime.GOOS: true, runtime.GOARCH: true})
58	match(runtime.GOOS+","+runtime.GOARCH+",foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
59	nomatch(runtime.GOOS+","+runtime.GOARCH+",!foo", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "foo": true})
60	match(runtime.GOOS+","+runtime.GOARCH+",!bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true})
61	nomatch(runtime.GOOS+","+runtime.GOARCH+",bar", map[string]bool{runtime.GOOS: true, runtime.GOARCH: true, "bar": true})
62}
63
64func TestDotSlashImport(t *testing.T) {
65	p, err := ImportDir("testdata/other", 0)
66	if err != nil {
67		t.Fatal(err)
68	}
69	if len(p.Imports) != 1 || p.Imports[0] != "./file" {
70		t.Fatalf("testdata/other: Imports=%v, want [./file]", p.Imports)
71	}
72
73	p1, err := Import("./file", "testdata/other", 0)
74	if err != nil {
75		t.Fatal(err)
76	}
77	if p1.Name != "file" {
78		t.Fatalf("./file: Name=%q, want %q", p1.Name, "file")
79	}
80	dir := filepath.Clean("testdata/other/file") // Clean to use \ on Windows
81	if p1.Dir != dir {
82		t.Fatalf("./file: Dir=%q, want %q", p1.Name, dir)
83	}
84}
85
86func TestEmptyImport(t *testing.T) {
87	p, err := Import("", Default.GOROOT, FindOnly)
88	if err == nil {
89		t.Fatal(`Import("") returned nil error.`)
90	}
91	if p == nil {
92		t.Fatal(`Import("") returned nil package.`)
93	}
94	if p.ImportPath != "" {
95		t.Fatalf("ImportPath=%q, want %q.", p.ImportPath, "")
96	}
97}
98
99func TestEmptyFolderImport(t *testing.T) {
100	_, err := Import(".", "testdata/empty", 0)
101	if _, ok := err.(*NoGoError); !ok {
102		t.Fatal(`Import("testdata/empty") did not return NoGoError.`)
103	}
104}
105
106func TestMultiplePackageImport(t *testing.T) {
107	pkg, err := Import(".", "testdata/multi", 0)
108
109	mpe, ok := err.(*MultiplePackageError)
110	if !ok {
111		t.Fatal(`Import("testdata/multi") did not return MultiplePackageError.`)
112	}
113	want := &MultiplePackageError{
114		Dir:      filepath.FromSlash("testdata/multi"),
115		Packages: []string{"main", "test_package"},
116		Files:    []string{"file.go", "file_appengine.go"},
117	}
118	if !reflect.DeepEqual(mpe, want) {
119		t.Errorf("err = %#v; want %#v", mpe, want)
120	}
121
122	// TODO(#45999): Since the name is ambiguous, pkg.Name should be left empty.
123	if wantName := "main"; pkg.Name != wantName {
124		t.Errorf("pkg.Name = %q; want %q", pkg.Name, wantName)
125	}
126
127	if wantGoFiles := []string{"file.go", "file_appengine.go"}; !reflect.DeepEqual(pkg.GoFiles, wantGoFiles) {
128		t.Errorf("pkg.GoFiles = %q; want %q", pkg.GoFiles, wantGoFiles)
129	}
130
131	if wantInvalidFiles := []string{"file_appengine.go"}; !reflect.DeepEqual(pkg.InvalidGoFiles, wantInvalidFiles) {
132		t.Errorf("pkg.InvalidGoFiles = %q; want %q", pkg.InvalidGoFiles, wantInvalidFiles)
133	}
134}
135
136func TestLocalDirectory(t *testing.T) {
137	t.Skip("does not work with gccgo")
138	if runtime.GOOS == "ios" {
139		t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH)
140	}
141
142	cwd, err := os.Getwd()
143	if err != nil {
144		t.Fatal(err)
145	}
146
147	p, err := ImportDir(cwd, 0)
148	if err != nil {
149		t.Fatal(err)
150	}
151	if p.ImportPath != "go/build" {
152		t.Fatalf("ImportPath=%q, want %q", p.ImportPath, "go/build")
153	}
154}
155
156var shouldBuildTests = []struct {
157	name        string
158	content     string
159	tags        map[string]bool
160	binaryOnly  bool
161	shouldBuild bool
162	err         error
163}{
164	{
165		name: "Yes",
166		content: "// +build yes\n\n" +
167			"package main\n",
168		tags:        map[string]bool{"yes": true},
169		shouldBuild: true,
170	},
171	{
172		name: "Yes2",
173		content: "//go:build yes\n" +
174			"package main\n",
175		tags:        map[string]bool{"yes": true},
176		shouldBuild: true,
177	},
178	{
179		name: "Or",
180		content: "// +build no yes\n\n" +
181			"package main\n",
182		tags:        map[string]bool{"yes": true, "no": true},
183		shouldBuild: true,
184	},
185	{
186		name: "Or2",
187		content: "//go:build no || yes\n" +
188			"package main\n",
189		tags:        map[string]bool{"yes": true, "no": true},
190		shouldBuild: true,
191	},
192	{
193		name: "And",
194		content: "// +build no,yes\n\n" +
195			"package main\n",
196		tags:        map[string]bool{"yes": true, "no": true},
197		shouldBuild: false,
198	},
199	{
200		name: "And2",
201		content: "//go:build no && yes\n" +
202			"package main\n",
203		tags:        map[string]bool{"yes": true, "no": true},
204		shouldBuild: false,
205	},
206	{
207		name: "Cgo",
208		content: "// +build cgo\n\n" +
209			"// Copyright The Go Authors.\n\n" +
210			"// This package implements parsing of tags like\n" +
211			"// +build tag1\n" +
212			"package build",
213		tags:        map[string]bool{"cgo": true},
214		shouldBuild: false,
215	},
216	{
217		name: "Cgo2",
218		content: "//go:build cgo\n" +
219			"// Copyright The Go Authors.\n\n" +
220			"// This package implements parsing of tags like\n" +
221			"// +build tag1\n" +
222			"package build",
223		tags:        map[string]bool{"cgo": true},
224		shouldBuild: false,
225	},
226	{
227		name: "AfterPackage",
228		content: "// Copyright The Go Authors.\n\n" +
229			"package build\n\n" +
230			"// shouldBuild checks tags given by lines of the form\n" +
231			"// +build tag\n" +
232			"//go:build tag\n" +
233			"func shouldBuild(content []byte)\n",
234		tags:        map[string]bool{},
235		shouldBuild: true,
236	},
237	{
238		name: "TooClose",
239		content: "// +build yes\n" +
240			"package main\n",
241		tags:        map[string]bool{},
242		shouldBuild: true,
243	},
244	{
245		name: "TooClose2",
246		content: "//go:build yes\n" +
247			"package main\n",
248		tags:        map[string]bool{"yes": true},
249		shouldBuild: true,
250	},
251	{
252		name: "TooCloseNo",
253		content: "// +build no\n" +
254			"package main\n",
255		tags:        map[string]bool{},
256		shouldBuild: true,
257	},
258	{
259		name: "TooCloseNo2",
260		content: "//go:build no\n" +
261			"package main\n",
262		tags:        map[string]bool{"no": true},
263		shouldBuild: false,
264	},
265	{
266		name: "BinaryOnly",
267		content: "//go:binary-only-package\n" +
268			"// +build yes\n" +
269			"package main\n",
270		tags:        map[string]bool{},
271		binaryOnly:  true,
272		shouldBuild: true,
273	},
274	{
275		name: "BinaryOnly2",
276		content: "//go:binary-only-package\n" +
277			"//go:build no\n" +
278			"package main\n",
279		tags:        map[string]bool{"no": true},
280		binaryOnly:  true,
281		shouldBuild: false,
282	},
283	{
284		name: "ValidGoBuild",
285		content: "// +build yes\n\n" +
286			"//go:build no\n" +
287			"package main\n",
288		tags:        map[string]bool{"no": true},
289		shouldBuild: false,
290	},
291	{
292		name: "MissingBuild2",
293		content: "/* */\n" +
294			"// +build yes\n\n" +
295			"//go:build no\n" +
296			"package main\n",
297		tags:        map[string]bool{"no": true},
298		shouldBuild: false,
299	},
300	{
301		name: "Comment1",
302		content: "/*\n" +
303			"//go:build no\n" +
304			"*/\n\n" +
305			"package main\n",
306		tags:        map[string]bool{},
307		shouldBuild: true,
308	},
309	{
310		name: "Comment2",
311		content: "/*\n" +
312			"text\n" +
313			"*/\n\n" +
314			"//go:build no\n" +
315			"package main\n",
316		tags:        map[string]bool{"no": true},
317		shouldBuild: false,
318	},
319	{
320		name: "Comment3",
321		content: "/*/*/ /* hi *//* \n" +
322			"text\n" +
323			"*/\n\n" +
324			"//go:build no\n" +
325			"package main\n",
326		tags:        map[string]bool{"no": true},
327		shouldBuild: false,
328	},
329	{
330		name: "Comment4",
331		content: "/**///go:build no\n" +
332			"package main\n",
333		tags:        map[string]bool{},
334		shouldBuild: true,
335	},
336	{
337		name: "Comment5",
338		content: "/**/\n" +
339			"//go:build no\n" +
340			"package main\n",
341		tags:        map[string]bool{"no": true},
342		shouldBuild: false,
343	},
344}
345
346func TestShouldBuild(t *testing.T) {
347	for _, tt := range shouldBuildTests {
348		t.Run(tt.name, func(t *testing.T) {
349			ctx := &Context{BuildTags: []string{"yes"}}
350			tags := map[string]bool{}
351			shouldBuild, binaryOnly, err := ctx.shouldBuild([]byte(tt.content), tags)
352			if shouldBuild != tt.shouldBuild || binaryOnly != tt.binaryOnly || !reflect.DeepEqual(tags, tt.tags) || err != tt.err {
353				t.Errorf("mismatch:\n"+
354					"have shouldBuild=%v, binaryOnly=%v, tags=%v, err=%v\n"+
355					"want shouldBuild=%v, binaryOnly=%v, tags=%v, err=%v",
356					shouldBuild, binaryOnly, tags, err,
357					tt.shouldBuild, tt.binaryOnly, tt.tags, tt.err)
358			}
359		})
360	}
361}
362
363func TestGoodOSArchFile(t *testing.T) {
364	ctx := &Context{BuildTags: []string{"linux"}, GOOS: "darwin"}
365	m := map[string]bool{}
366	want := map[string]bool{"linux": true}
367	if !ctx.goodOSArchFile("hello_linux.go", m) {
368		t.Errorf("goodOSArchFile(hello_linux.go) = false, want true")
369	}
370	if !reflect.DeepEqual(m, want) {
371		t.Errorf("goodOSArchFile(hello_linux.go) tags = %v, want %v", m, want)
372	}
373}
374
375type readNopCloser struct {
376	io.Reader
377}
378
379func (r readNopCloser) Close() error {
380	return nil
381}
382
383var (
384	ctxtP9      = Context{GOARCH: "arm", GOOS: "plan9"}
385	ctxtAndroid = Context{GOARCH: "arm", GOOS: "android"}
386)
387
388var matchFileTests = []struct {
389	ctxt  Context
390	name  string
391	data  string
392	match bool
393}{
394	{ctxtP9, "foo_arm.go", "", true},
395	{ctxtP9, "foo1_arm.go", "// +build linux\n\npackage main\n", false},
396	{ctxtP9, "foo_darwin.go", "", false},
397	{ctxtP9, "foo.go", "", true},
398	{ctxtP9, "foo1.go", "// +build linux\n\npackage main\n", false},
399	{ctxtP9, "foo.badsuffix", "", false},
400	{ctxtAndroid, "foo_linux.go", "", true},
401	{ctxtAndroid, "foo_android.go", "", true},
402	{ctxtAndroid, "foo_plan9.go", "", false},
403	{ctxtAndroid, "android.go", "", true},
404	{ctxtAndroid, "plan9.go", "", true},
405	{ctxtAndroid, "plan9_test.go", "", true},
406	{ctxtAndroid, "arm.s", "", true},
407	{ctxtAndroid, "amd64.s", "", true},
408}
409
410func TestMatchFile(t *testing.T) {
411	for _, tt := range matchFileTests {
412		ctxt := tt.ctxt
413		ctxt.OpenFile = func(path string) (r io.ReadCloser, err error) {
414			if path != "x+"+tt.name {
415				t.Fatalf("OpenFile asked for %q, expected %q", path, "x+"+tt.name)
416			}
417			return &readNopCloser{strings.NewReader(tt.data)}, nil
418		}
419		ctxt.JoinPath = func(elem ...string) string {
420			return strings.Join(elem, "+")
421		}
422		match, err := ctxt.MatchFile("x", tt.name)
423		if match != tt.match || err != nil {
424			t.Fatalf("MatchFile(%q) = %v, %v, want %v, nil", tt.name, match, err, tt.match)
425		}
426	}
427}
428
429func TestImportCmd(t *testing.T) {
430	t.Skip("does not work with gccgo")
431	if runtime.GOOS == "ios" {
432		t.Skipf("skipping on %s/%s, no valid GOROOT", runtime.GOOS, runtime.GOARCH)
433	}
434
435	p, err := Import("cmd/internal/objfile", "", 0)
436	if err != nil {
437		t.Fatal(err)
438	}
439	if !strings.HasSuffix(filepath.ToSlash(p.Dir), "src/cmd/internal/objfile") {
440		t.Fatalf("Import cmd/internal/objfile returned Dir=%q, want %q", filepath.ToSlash(p.Dir), ".../src/cmd/internal/objfile")
441	}
442}
443
444var (
445	expandSrcDirPath = filepath.Join(string(filepath.Separator)+"projects", "src", "add")
446)
447
448var expandSrcDirTests = []struct {
449	input, expected string
450}{
451	{"-L ${SRCDIR}/libs -ladd", "-L /projects/src/add/libs -ladd"},
452	{"${SRCDIR}/add_linux_386.a -pthread -lstdc++", "/projects/src/add/add_linux_386.a -pthread -lstdc++"},
453	{"Nothing to expand here!", "Nothing to expand here!"},
454	{"$", "$"},
455	{"$$", "$$"},
456	{"${", "${"},
457	{"$}", "$}"},
458	{"$FOO ${BAR}", "$FOO ${BAR}"},
459	{"Find me the $SRCDIRECTORY.", "Find me the $SRCDIRECTORY."},
460	{"$SRCDIR is missing braces", "$SRCDIR is missing braces"},
461}
462
463func TestExpandSrcDir(t *testing.T) {
464	for _, test := range expandSrcDirTests {
465		output, _ := expandSrcDir(test.input, expandSrcDirPath)
466		if output != test.expected {
467			t.Errorf("%q expands to %q with SRCDIR=%q when %q is expected", test.input, output, expandSrcDirPath, test.expected)
468		} else {
469			t.Logf("%q expands to %q with SRCDIR=%q", test.input, output, expandSrcDirPath)
470		}
471	}
472}
473
474func TestShellSafety(t *testing.T) {
475	tests := []struct {
476		input, srcdir, expected string
477		result                  bool
478	}{
479		{"-I${SRCDIR}/../include", "/projects/src/issue 11868", "-I/projects/src/issue 11868/../include", true},
480		{"-I${SRCDIR}", "~wtf$@%^", "-I~wtf$@%^", true},
481		{"-X${SRCDIR}/1,${SRCDIR}/2", "/projects/src/issue 11868", "-X/projects/src/issue 11868/1,/projects/src/issue 11868/2", true},
482		{"-I/tmp -I/tmp", "/tmp2", "-I/tmp -I/tmp", true},
483		{"-I/tmp", "/tmp/[0]", "-I/tmp", true},
484		{"-I${SRCDIR}/dir", "/tmp/[0]", "-I/tmp/[0]/dir", false},
485		{"-I${SRCDIR}/dir", "/tmp/go go", "-I/tmp/go go/dir", true},
486		{"-I${SRCDIR}/dir dir", "/tmp/go", "-I/tmp/go/dir dir", true},
487	}
488	for _, test := range tests {
489		output, ok := expandSrcDir(test.input, test.srcdir)
490		if ok != test.result {
491			t.Errorf("Expected %t while %q expands to %q with SRCDIR=%q; got %t", test.result, test.input, output, test.srcdir, ok)
492		}
493		if output != test.expected {
494			t.Errorf("Expected %q while %q expands with SRCDIR=%q; got %q", test.expected, test.input, test.srcdir, output)
495		}
496	}
497}
498
499// Want to get a "cannot find package" error when directory for package does not exist.
500// There should be valid partial information in the returned non-nil *Package.
501func TestImportDirNotExist(t *testing.T) {
502	testenv.MustHaveGoBuild(t) // really must just have source
503	ctxt := Default
504
505	emptyDir := t.TempDir()
506
507	ctxt.GOPATH = emptyDir
508	ctxt.Dir = emptyDir
509
510	tests := []struct {
511		label        string
512		path, srcDir string
513		mode         ImportMode
514	}{
515		{"Import(full, 0)", "go/build/doesnotexist", "", 0},
516		{"Import(local, 0)", "./doesnotexist", filepath.Join(ctxt.GOROOT, "src/go/build"), 0},
517		{"Import(full, FindOnly)", "go/build/doesnotexist", "", FindOnly},
518		{"Import(local, FindOnly)", "./doesnotexist", filepath.Join(ctxt.GOROOT, "src/go/build"), FindOnly},
519	}
520
521	defer os.Setenv("GO111MODULE", os.Getenv("GO111MODULE"))
522
523	for _, GO111MODULE := range []string{"off", "on"} {
524		t.Run("GO111MODULE="+GO111MODULE, func(t *testing.T) {
525			os.Setenv("GO111MODULE", GO111MODULE)
526
527			for _, test := range tests {
528				p, err := ctxt.Import(test.path, test.srcDir, test.mode)
529
530				errOk := (err != nil && strings.HasPrefix(err.Error(), "cannot find package"))
531				wantErr := `"cannot find package" error`
532				if test.srcDir == "" {
533					if err != nil && strings.Contains(err.Error(), "is not in GOROOT") {
534						errOk = true
535					}
536					wantErr = `"cannot find package" or "is not in GOROOT" error`
537				}
538				if !errOk {
539					t.Errorf("%s got error: %q, want %s", test.label, err, wantErr)
540				}
541				// If an error occurs, build.Import is documented to return
542				// a non-nil *Package containing partial information.
543				if p == nil {
544					t.Fatalf(`%s got nil p, want non-nil *Package`, test.label)
545				}
546				// Verify partial information in p.
547				if p.ImportPath != "go/build/doesnotexist" {
548					t.Errorf(`%s got p.ImportPath: %q, want "go/build/doesnotexist"`, test.label, p.ImportPath)
549				}
550			}
551		})
552	}
553}
554
555func TestImportVendor(t *testing.T) {
556	testenv.MustHaveGoBuild(t) // really must just have source
557
558	t.Setenv("GO111MODULE", "off")
559
560	ctxt := Default
561	wd, err := os.Getwd()
562	if err != nil {
563		t.Fatal(err)
564	}
565	ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor")
566	p, err := ctxt.Import("c/d", filepath.Join(ctxt.GOPATH, "src/a/b"), 0)
567	if err != nil {
568		t.Fatalf("cannot find vendored c/d from testdata src/a/b directory: %v", err)
569	}
570	want := "a/vendor/c/d"
571	if p.ImportPath != want {
572		t.Fatalf("Import succeeded but found %q, want %q", p.ImportPath, want)
573	}
574}
575
576func TestImportVendorFailure(t *testing.T) {
577	testenv.MustHaveGoBuild(t) // really must just have source
578
579	t.Setenv("GO111MODULE", "off")
580
581	ctxt := Default
582	wd, err := os.Getwd()
583	if err != nil {
584		t.Fatal(err)
585	}
586	ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor")
587	p, err := ctxt.Import("x.com/y/z", filepath.Join(ctxt.GOPATH, "src/a/b"), 0)
588	if err == nil {
589		t.Fatalf("found made-up package x.com/y/z in %s", p.Dir)
590	}
591
592	e := err.Error()
593	if !strings.Contains(e, " (vendor tree)") {
594		t.Fatalf("error on failed import does not mention GOROOT/src/vendor directory:\n%s", e)
595	}
596}
597
598func TestImportVendorParentFailure(t *testing.T) {
599	testenv.MustHaveGoBuild(t) // really must just have source
600
601	t.Setenv("GO111MODULE", "off")
602
603	ctxt := Default
604	wd, err := os.Getwd()
605	if err != nil {
606		t.Fatal(err)
607	}
608	ctxt.GOPATH = filepath.Join(wd, "testdata/withvendor")
609	// This import should fail because the vendor/c directory has no source code.
610	p, err := ctxt.Import("c", filepath.Join(ctxt.GOPATH, "src/a/b"), 0)
611	if err == nil {
612		t.Fatalf("found empty parent in %s", p.Dir)
613	}
614	if p != nil && p.Dir != "" {
615		t.Fatalf("decided to use %s", p.Dir)
616	}
617	e := err.Error()
618	if !strings.Contains(e, " (vendor tree)") {
619		t.Fatalf("error on failed import does not mention GOROOT/src/vendor directory:\n%s", e)
620	}
621}
622
623// Check that a package is loaded in module mode if GO111MODULE=on, even when
624// no go.mod file is present. It should fail to resolve packages outside std.
625// Verifies golang.org/issue/34669.
626func TestImportPackageOutsideModule(t *testing.T) {
627	testenv.MustHaveGoBuild(t)
628
629	// Disable module fetching for this test so that 'go list' fails quickly
630	// without trying to find the latest version of a module.
631	t.Setenv("GOPROXY", "off")
632
633	// Create a GOPATH in a temporary directory. We don't use testdata
634	// because it's in GOROOT, which interferes with the module heuristic.
635	gopath := t.TempDir()
636	if err := os.MkdirAll(filepath.Join(gopath, "src/example.com/p"), 0777); err != nil {
637		t.Fatal(err)
638	}
639	if err := os.WriteFile(filepath.Join(gopath, "src/example.com/p/p.go"), []byte("package p"), 0666); err != nil {
640		t.Fatal(err)
641	}
642
643	t.Setenv("GO111MODULE", "on")
644	t.Setenv("GOPATH", gopath)
645	ctxt := Default
646	ctxt.GOPATH = gopath
647	ctxt.Dir = filepath.Join(gopath, "src/example.com/p")
648
649	want := "go.mod file not found in current directory or any parent directory"
650	if _, err := ctxt.Import("example.com/p", gopath, FindOnly); err == nil {
651		t.Fatal("importing package when no go.mod is present succeeded unexpectedly")
652	} else if errStr := err.Error(); !strings.Contains(errStr, want) {
653		t.Fatalf("error when importing package when no go.mod is present: got %q; want %q", errStr, want)
654	} else {
655		t.Logf(`ctxt.Import("example.com/p", _, FindOnly): %v`, err)
656	}
657}
658
659func TestImportDirTarget(t *testing.T) {
660	testenv.MustHaveGoBuild(t) // really must just have source
661	ctxt := Default
662	ctxt.GOPATH = ""
663	p, err := ctxt.ImportDir(filepath.Join(ctxt.GOROOT, "src/path"), 0)
664	if err != nil {
665		t.Fatal(err)
666	}
667	if p.PkgTargetRoot == "" || p.PkgObj == "" {
668		t.Errorf("p.PkgTargetRoot == %q, p.PkgObj == %q, want non-empty", p.PkgTargetRoot, p.PkgObj)
669	}
670}
671
672// TestIssue23594 prevents go/build from regressing and populating Package.Doc
673// from comments in test files.
674func TestIssue23594(t *testing.T) {
675	// Package testdata/doc contains regular and external test files
676	// with comments attached to their package declarations. The names of the files
677	// ensure that we see the comments from the test files first.
678	p, err := ImportDir("testdata/doc", 0)
679	if err != nil {
680		t.Fatalf("could not import testdata: %v", err)
681	}
682
683	if p.Doc != "Correct" {
684		t.Fatalf("incorrectly set .Doc to %q", p.Doc)
685	}
686}
687
688// TestMissingImportErrorRepetition checks that when an unknown package is
689// imported, the package path is only shown once in the error.
690// Verifies golang.org/issue/34752.
691func TestMissingImportErrorRepetition(t *testing.T) {
692	testenv.MustHaveGoBuild(t) // need 'go list' internally
693	tmp := t.TempDir()
694	if err := os.WriteFile(filepath.Join(tmp, "go.mod"), []byte("module m"), 0666); err != nil {
695		t.Fatal(err)
696	}
697	t.Setenv("GO111MODULE", "on")
698	t.Setenv("GOPROXY", "off")
699	t.Setenv("GONOPROXY", "none")
700
701	ctxt := Default
702	ctxt.Dir = tmp
703
704	pkgPath := "example.com/hello"
705	_, err := ctxt.Import(pkgPath, tmp, FindOnly)
706	if err == nil {
707		t.Fatal("unexpected success")
708	}
709
710	// Don't count the package path with a URL like https://...?go-get=1.
711	// See golang.org/issue/35986.
712	errStr := strings.ReplaceAll(err.Error(), "://"+pkgPath+"?go-get=1", "://...?go-get=1")
713
714	// Also don't count instances in suggested "go get" or similar commands
715	// (see https://golang.org/issue/41576). The suggested command typically
716	// follows a semicolon.
717	errStr = strings.SplitN(errStr, ";", 2)[0]
718
719	if n := strings.Count(errStr, pkgPath); n != 1 {
720		t.Fatalf("package path %q appears in error %d times; should appear once\nerror: %v", pkgPath, n, err)
721	}
722}
723
724// TestCgoImportsIgnored checks that imports in cgo files are not included
725// in the imports list when cgo is disabled.
726// Verifies golang.org/issue/35946.
727func TestCgoImportsIgnored(t *testing.T) {
728	ctxt := Default
729	ctxt.CgoEnabled = false
730	p, err := ctxt.ImportDir("testdata/cgo_disabled", 0)
731	if err != nil {
732		t.Fatal(err)
733	}
734	for _, path := range p.Imports {
735		if path == "should/be/ignored" {
736			t.Errorf("found import %q in ignored cgo file", path)
737		}
738	}
739}
740