1 // Copyright 2015 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.
27 canRun = true // whether we can run go or ./testgo
28 canRace = false // whether we can run the race detector
29 canCgo = false // whether we can use cgo
31 exeSuffix string // ".exe" on Windows
33 skipExternal = false // skip external tests
38 case "android", "nacl":
41 switch runtime.GOARCH {
46 switch runtime.GOARCH {
48 // many linux/arm machines are too slow to run
49 // the full set of external tests.
51 case "mips", "mipsle", "mips64", "mips64le":
54 if testenv.Builder() != "" {
55 // On the builders, skip the cmd/go
56 // tests. They're too slow and already
57 // covered by other ports. There's
58 // nothing os/arch specific in the
64 switch runtime.GOARCH {
66 // many freebsd/arm machines are too slow to run
67 // the full set of external tests.
76 // testGOROOT is the GOROOT to use when running testgo, a cmd/go binary
77 // build from this process's current GOROOT, but run from a different
83 // The TestMain function creates a go command for testing purposes and
84 // deletes it after the tests have been run.
85 func TestMain(m *testing.M) {
87 args := []string{"build", "-tags", "testgo", "-o", "testgo" + exeSuffix}
89 args = append(args, "-race")
91 out, err := exec.Command("go", args...).CombinedOutput()
93 fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out)
97 out, err = exec.Command("go", "env", "GOROOT").CombinedOutput()
99 fmt.Fprintf(os.Stderr, "could not find testing GOROOT: %v\n%s", err, out)
102 testGOROOT = strings.TrimSpace(string(out))
104 out, err = exec.Command("go", "env", "CC").CombinedOutput()
106 fmt.Fprintf(os.Stderr, "could not find testing CC: %v\n%s", err, out)
109 testCC = strings.TrimSpace(string(out))
111 if out, err := exec.Command("./testgo"+exeSuffix, "env", "CGO_ENABLED").Output(); err != nil {
112 fmt.Fprintf(os.Stderr, "running testgo failed: %v\n", err)
115 canCgo, err = strconv.ParseBool(strings.TrimSpace(string(out)))
117 fmt.Fprintf(os.Stderr, "can't parse go env CGO_ENABLED output: %v\n", strings.TrimSpace(string(out)))
121 switch runtime.GOOS {
122 case "linux", "darwin", "freebsd", "windows":
123 // The race detector doesn't work on Alpine Linux:
124 // golang.org/issue/14481
125 canRace = canCgo && runtime.GOARCH == "amd64" && !isAlpineLinux()
129 // Don't let these environment variables confuse the test.
131 os.Unsetenv("GOPATH")
132 os.Unsetenv("GIT_ALLOW_PROTOCOL")
133 if home, ccacheDir := os.Getenv("HOME"), os.Getenv("CCACHE_DIR"); home != "" && ccacheDir == "" {
134 // On some systems the default C compiler is ccache.
135 // Setting HOME to a non-existent directory will break
136 // those systems. Set CCACHE_DIR to cope. Issue 17668.
137 os.Setenv("CCACHE_DIR", filepath.Join(home, ".ccache"))
139 os.Setenv("HOME", "/test-go-home-does-not-exist")
144 os.Remove("testgo" + exeSuffix)
150 func isAlpineLinux() bool {
151 if runtime.GOOS != "linux" {
154 fi, err := os.Lstat("/etc/alpine-release")
155 return err == nil && fi.Mode().IsRegular()
158 // The length of an mtime tick on this system. This is an estimate of
159 // how long we need to sleep to ensure that the mtime of two files is
161 // We used to try to be clever but that didn't always work (see golang.org/issue/12205).
162 var mtimeTick time.Duration = 1 * time.Second
164 // Manage a single run of the testgo binary.
165 type testgoData struct {
173 stdout, stderr bytes.Buffer
176 // testgo sets up for a test that runs testgo.
177 func testgo(t *testing.T) *testgoData {
178 testenv.MustHaveGoBuild(t)
181 t.Skip("skipping external tests on %s/%s", runtime.GOOS, runtime.GOARCH)
184 return &testgoData{t: t}
187 // must gives a fatal error if err is not nil.
188 func (tg *testgoData) must(err error) {
194 // check gives a test non-fatal error if err is not nil.
195 func (tg *testgoData) check(err error) {
201 // parallel runs the test in parallel by calling t.Parallel.
202 func (tg *testgoData) parallel() {
204 tg.t.Fatal("internal testsuite error: call to parallel after run")
207 tg.t.Fatal("internal testsuite error: call to parallel after cd")
209 for _, e := range tg.env {
210 if strings.HasPrefix(e, "GOROOT=") || strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
211 val := e[strings.Index(e, "=")+1:]
212 if strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata") {
213 tg.t.Fatalf("internal testsuite error: call to parallel with testdata in environment (%s)", e)
221 // pwd returns the current directory.
222 func (tg *testgoData) pwd() string {
223 wd, err := os.Getwd()
225 tg.t.Fatalf("could not get working directory: %v", err)
230 // cd changes the current directory to the named directory. Note that
231 // using this means that the test must not be run in parallel with any
233 func (tg *testgoData) cd(dir string) {
235 tg.t.Fatal("internal testsuite error: changing directory when running in parallel")
240 abs, err := filepath.Abs(dir)
241 tg.must(os.Chdir(dir))
243 tg.setenv("PWD", abs)
247 // sleep sleeps for one tick, where a tick is a conservative estimate
248 // of how long it takes for a file modification to get a different
250 func (tg *testgoData) sleep() {
251 time.Sleep(mtimeTick)
254 // setenv sets an environment variable to use when running the test go
256 func (tg *testgoData) setenv(name, val string) {
257 if tg.inParallel && (name == "GOROOT" || name == "GOPATH" || name == "GOBIN") && (strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata")) {
258 tg.t.Fatalf("internal testsuite error: call to setenv with testdata (%s=%s) after parallel", name, val)
261 tg.env = append(tg.env, name+"="+val)
264 // unsetenv removes an environment variable.
265 func (tg *testgoData) unsetenv(name string) {
267 tg.env = append([]string(nil), os.Environ()...)
269 for i, v := range tg.env {
270 if strings.HasPrefix(v, name+"=") {
271 tg.env = append(tg.env[:i], tg.env[i+1:]...)
277 func (tg *testgoData) goTool() string {
279 return "./testgo" + exeSuffix
281 return filepath.Join(tg.wd, "testgo"+exeSuffix)
284 // doRun runs the test go command, recording stdout and stderr and
285 // returning exit status.
286 func (tg *testgoData) doRun(args []string) error {
288 panic("testgoData.doRun called but canRun false")
291 for _, arg := range args {
292 if strings.HasPrefix(arg, "testdata") || strings.HasPrefix(arg, "./testdata") {
293 tg.t.Fatal("internal testsuite error: parallel run using testdata")
299 for _, v := range tg.env {
300 if strings.HasPrefix(v, "GOROOT=") {
307 tg.setenv("GOROOT", testGOROOT)
310 tg.t.Logf("running testgo %v", args)
311 cmd := exec.Command(prog, args...)
314 cmd.Stdout = &tg.stdout
315 cmd.Stderr = &tg.stderr
318 if tg.stdout.Len() > 0 {
319 tg.t.Log("standard output:")
320 tg.t.Log(tg.stdout.String())
322 if tg.stderr.Len() > 0 {
323 tg.t.Log("standard error:")
324 tg.t.Log(tg.stderr.String())
330 // run runs the test go command, and expects it to succeed.
331 func (tg *testgoData) run(args ...string) {
332 if status := tg.doRun(args); status != nil {
333 tg.t.Logf("go %v failed unexpectedly: %v", args, status)
338 // runFail runs the test go command, and expects it to fail.
339 func (tg *testgoData) runFail(args ...string) {
340 if status := tg.doRun(args); status == nil {
341 tg.t.Fatal("testgo succeeded unexpectedly")
343 tg.t.Log("testgo failed as expected:", status)
347 // runGit runs a git command, and expects it to succeed.
348 func (tg *testgoData) runGit(dir string, args ...string) {
349 cmd := exec.Command("git", args...)
352 cmd.Stdout = &tg.stdout
353 cmd.Stderr = &tg.stderr
357 if tg.stdout.Len() > 0 {
358 tg.t.Log("git standard output:")
359 tg.t.Log(tg.stdout.String())
361 if tg.stderr.Len() > 0 {
362 tg.t.Log("git standard error:")
363 tg.t.Log(tg.stderr.String())
366 tg.t.Logf("git %v failed unexpectedly: %v", args, status)
371 // getStdout returns standard output of the testgo run as a string.
372 func (tg *testgoData) getStdout() string {
374 tg.t.Fatal("internal testsuite error: stdout called before run")
376 return tg.stdout.String()
379 // getStderr returns standard error of the testgo run as a string.
380 func (tg *testgoData) getStderr() string {
382 tg.t.Fatal("internal testsuite error: stdout called before run")
384 return tg.stderr.String()
387 // doGrepMatch looks for a regular expression in a buffer, and returns
388 // whether it is found. The regular expression is matched against
389 // each line separately, as with the grep command.
390 func (tg *testgoData) doGrepMatch(match string, b *bytes.Buffer) bool {
392 tg.t.Fatal("internal testsuite error: grep called before run")
394 re := regexp.MustCompile(match)
395 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
403 // doGrep looks for a regular expression in a buffer and fails if it
404 // is not found. The name argument is the name of the output we are
405 // searching, "output" or "error". The msg argument is logged on
407 func (tg *testgoData) doGrep(match string, b *bytes.Buffer, name, msg string) {
408 if !tg.doGrepMatch(match, b) {
410 tg.t.Logf("pattern %v not found in standard %s", match, name)
415 // grepStdout looks for a regular expression in the test run's
416 // standard output and fails, logging msg, if it is not found.
417 func (tg *testgoData) grepStdout(match, msg string) {
418 tg.doGrep(match, &tg.stdout, "output", msg)
421 // grepStderr looks for a regular expression in the test run's
422 // standard error and fails, logging msg, if it is not found.
423 func (tg *testgoData) grepStderr(match, msg string) {
424 tg.doGrep(match, &tg.stderr, "error", msg)
427 // grepBoth looks for a regular expression in the test run's standard
428 // output or stand error and fails, logging msg, if it is not found.
429 func (tg *testgoData) grepBoth(match, msg string) {
430 if !tg.doGrepMatch(match, &tg.stdout) && !tg.doGrepMatch(match, &tg.stderr) {
432 tg.t.Logf("pattern %v not found in standard output or standard error", match)
437 // doGrepNot looks for a regular expression in a buffer and fails if
438 // it is found. The name and msg arguments are as for doGrep.
439 func (tg *testgoData) doGrepNot(match string, b *bytes.Buffer, name, msg string) {
440 if tg.doGrepMatch(match, b) {
442 tg.t.Logf("pattern %v found unexpectedly in standard %s", match, name)
447 // grepStdoutNot looks for a regular expression in the test run's
448 // standard output and fails, logging msg, if it is found.
449 func (tg *testgoData) grepStdoutNot(match, msg string) {
450 tg.doGrepNot(match, &tg.stdout, "output", msg)
453 // grepStderrNot looks for a regular expression in the test run's
454 // standard error and fails, logging msg, if it is found.
455 func (tg *testgoData) grepStderrNot(match, msg string) {
456 tg.doGrepNot(match, &tg.stderr, "error", msg)
459 // grepBothNot looks for a regular expression in the test run's
460 // standard output or stand error and fails, logging msg, if it is
462 func (tg *testgoData) grepBothNot(match, msg string) {
463 if tg.doGrepMatch(match, &tg.stdout) || tg.doGrepMatch(match, &tg.stderr) {
465 tg.t.Fatalf("pattern %v found unexpectedly in standard output or standard error", match)
469 // doGrepCount counts the number of times a regexp is seen in a buffer.
470 func (tg *testgoData) doGrepCount(match string, b *bytes.Buffer) int {
472 tg.t.Fatal("internal testsuite error: doGrepCount called before run")
474 re := regexp.MustCompile(match)
476 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
484 // grepCountBoth returns the number of times a regexp is seen in both
485 // standard output and standard error.
486 func (tg *testgoData) grepCountBoth(match string) int {
487 return tg.doGrepCount(match, &tg.stdout) + tg.doGrepCount(match, &tg.stderr)
490 // creatingTemp records that the test plans to create a temporary file
491 // or directory. If the file or directory exists already, it will be
492 // removed. When the test completes, the file or directory will be
493 // removed if it exists.
494 func (tg *testgoData) creatingTemp(path string) {
495 if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) {
496 tg.t.Fatalf("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path)
498 // If we have changed the working directory, make sure we have
499 // an absolute path, because we are going to change directory
500 // back before we remove the temporary.
501 if tg.wd != "" && !filepath.IsAbs(path) {
502 path = filepath.Join(tg.pwd(), path)
504 tg.must(os.RemoveAll(path))
505 tg.temps = append(tg.temps, path)
508 // makeTempdir makes a temporary directory for a run of testgo. If
509 // the temporary directory was already created, this does nothing.
510 func (tg *testgoData) makeTempdir() {
511 if tg.tempdir == "" {
513 tg.tempdir, err = ioutil.TempDir("", "gotest")
518 // tempFile adds a temporary file for a run of testgo.
519 func (tg *testgoData) tempFile(path, contents string) {
521 tg.must(os.MkdirAll(filepath.Join(tg.tempdir, filepath.Dir(path)), 0755))
522 bytes := []byte(contents)
523 if strings.HasSuffix(path, ".go") {
524 formatted, err := format.Source(bytes)
529 tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644))
532 // tempDir adds a temporary directory for a run of testgo.
533 func (tg *testgoData) tempDir(path string) {
535 if err := os.MkdirAll(filepath.Join(tg.tempdir, path), 0755); err != nil && !os.IsExist(err) {
540 // path returns the absolute pathname to file with the temporary
542 func (tg *testgoData) path(name string) string {
543 if tg.tempdir == "" {
544 tg.t.Fatalf("internal testsuite error: path(%q) with no tempdir", name)
549 return filepath.Join(tg.tempdir, name)
552 // mustExist fails if path does not exist.
553 func (tg *testgoData) mustExist(path string) {
554 if _, err := os.Stat(path); err != nil {
555 if os.IsNotExist(err) {
556 tg.t.Fatalf("%s does not exist but should", path)
558 tg.t.Fatalf("%s stat failed: %v", path, err)
562 // mustNotExist fails if path exists.
563 func (tg *testgoData) mustNotExist(path string) {
564 if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
565 tg.t.Fatalf("%s exists but should not (%v)", path, err)
569 // wantExecutable fails with msg if path is not executable.
570 func (tg *testgoData) wantExecutable(path, msg string) {
571 if st, err := os.Stat(path); err != nil {
572 if !os.IsNotExist(err) {
577 if runtime.GOOS != "windows" && st.Mode()&0111 == 0 {
578 tg.t.Fatalf("binary %s exists but is not executable", path)
583 // wantArchive fails if path is not an archive.
584 func (tg *testgoData) wantArchive(path string) {
585 f, err := os.Open(path)
589 buf := make([]byte, 100)
592 if !bytes.HasPrefix(buf, []byte("!<arch>\n")) {
593 tg.t.Fatalf("file %s exists but is not an archive", path)
597 // isStale reports whether pkg is stale, and why
598 func (tg *testgoData) isStale(pkg string) (bool, string) {
599 tg.run("list", "-f", "{{.Stale}}:{{.StaleReason}}", pkg)
600 v := strings.TrimSpace(tg.getStdout())
601 f := strings.SplitN(v, ":", 2)
610 tg.t.Fatalf("unexpected output checking staleness of package %v: %v", pkg, v)
614 // wantStale fails with msg if pkg is not stale.
615 func (tg *testgoData) wantStale(pkg, reason, msg string) {
616 stale, why := tg.isStale(pkg)
620 if reason == "" && why != "" || !strings.Contains(why, reason) {
621 tg.t.Errorf("wrong reason for Stale=true: %q, want %q", why, reason)
625 // wantNotStale fails with msg if pkg is stale.
626 func (tg *testgoData) wantNotStale(pkg, reason, msg string) {
627 stale, why := tg.isStale(pkg)
631 if reason == "" && why != "" || !strings.Contains(why, reason) {
632 tg.t.Errorf("wrong reason for Stale=false: %q, want %q", why, reason)
636 // cleanup cleans up a test that runs testgo.
637 func (tg *testgoData) cleanup() {
639 if err := os.Chdir(tg.wd); err != nil {
640 // We are unlikely to be able to continue.
641 fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err)
645 for _, path := range tg.temps {
646 tg.check(os.RemoveAll(path))
648 if tg.tempdir != "" {
649 tg.check(os.RemoveAll(tg.tempdir))
653 // failSSH puts an ssh executable in the PATH that always fails.
654 // This is to stub out uses of ssh by go get.
655 func (tg *testgoData) failSSH() {
656 wd, err := os.Getwd()
660 fail := filepath.Join(wd, "testdata/failssh")
661 tg.setenv("PATH", fmt.Sprintf("%v%c%v", fail, filepath.ListSeparator, os.Getenv("PATH")))
664 func TestFileLineInErrorMessages(t *testing.T) {
668 tg.tempFile("err.go", `package main; import "bar"`)
669 path := tg.path("err.go")
670 tg.runFail("run", path)
672 if rel, err := filepath.Rel(tg.pwd(), path); err == nil && len(rel) < len(path) {
675 tg.grepStderr("^"+regexp.QuoteMeta(shortPath)+":", "missing file:line in error message")
678 func TestProgramNameInCrashMessages(t *testing.T) {
682 tg.tempFile("triv.go", `package main; func main() {}`)
683 tg.runFail("build", "-ldflags", "-crash_for_testing", tg.path("triv.go"))
684 tg.grepStderr(`[/\\]tool[/\\].*[/\\]link`, "missing linker name in error message")
687 func TestBrokenTestsWithoutTestFunctionsAllFail(t *testing.T) {
690 // TODO: tg.parallel()
691 tg.runFail("test", "./testdata/src/badtest/...")
692 tg.grepBothNot("^ok", "test passed unexpectedly")
693 tg.grepBoth("FAIL.*badtest/badexec", "test did not run everything")
694 tg.grepBoth("FAIL.*badtest/badsyntax", "test did not run everything")
695 tg.grepBoth("FAIL.*badtest/badvar", "test did not run everything")
698 func TestGoBuildDashAInDevBranch(t *testing.T) {
700 t.Skip("don't rebuild the standard library in short mode")
705 tg.run("install", "math") // should be up to date already but just in case
706 tg.setenv("TESTGO_IS_GO_RELEASE", "0")
707 tg.run("build", "-v", "-a", "math")
708 tg.grepStderr("runtime", "testgo build -a math in dev branch DID NOT build runtime, but should have")
710 // Everything is out of date. Rebuild to leave things in a better state.
711 tg.run("install", "std")
714 func TestGoBuildDashAInReleaseBranch(t *testing.T) {
716 t.Skip("don't rebuild the standard library in short mode")
721 tg.run("install", "math", "net/http") // should be up to date already but just in case
722 tg.setenv("TESTGO_IS_GO_RELEASE", "1")
723 tg.run("install", "-v", "-a", "math")
724 tg.grepStderr("runtime", "testgo build -a math in release branch DID NOT build runtime, but should have")
726 // Now runtime.a is updated (newer mtime), so everything would look stale if not for being a release.
727 tg.run("build", "-v", "net/http")
728 tg.grepStderrNot("strconv", "testgo build -v net/http in release branch with newer runtime.a DID build strconv but should not have")
729 tg.grepStderrNot("golang.org/x/net/http2/hpack", "testgo build -v net/http in release branch with newer runtime.a DID build .../golang.org/x/net/http2/hpack but should not have")
730 tg.grepStderrNot("net/http", "testgo build -v net/http in release branch with newer runtime.a DID build net/http but should not have")
732 // Everything is out of date. Rebuild to leave things in a better state.
733 tg.run("install", "std")
736 func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) {
738 t.Skip("don't rebuild the standard library in short mode")
744 addNL := func(name string) (restore func()) {
745 data, err := ioutil.ReadFile(name)
750 data = append(data, '\n')
751 if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil {
756 if err := ioutil.WriteFile(name, old, 0666); err != nil {
762 tg.setenv("TESTGO_IS_GO_RELEASE", "1")
764 tg.tempFile("d1/src/p1/p1.go", `package p1`)
765 tg.setenv("GOPATH", tg.path("d1"))
766 tg.run("install", "-a", "p1")
767 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly")
770 // Changing mtime and content of runtime/internal/sys/sys.go
771 // should have no effect: we're in a release, which doesn't rebuild
772 // for general mtime or content changes.
773 sys := runtime.GOROOT() + "/src/runtime/internal/sys/sys.go"
774 restore := addNL(sys)
776 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after updating runtime/internal/sys/sys.go")
778 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after restoring runtime/internal/sys/sys.go")
780 // But changing runtime/internal/sys/zversion.go should have an effect:
781 // that's how we tell when we flip from one release to another.
782 zversion := runtime.GOROOT() + "/src/runtime/internal/sys/zversion.go"
783 restore = addNL(zversion)
785 tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing to new release")
787 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after changing back to old release")
789 tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing again to new release")
790 tg.run("install", "p1")
791 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with new release")
793 // Restore to "old" release.
795 tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing to old release after new build")
796 tg.run("install", "p1")
797 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release")
799 // Everything is out of date. Rebuild to leave things in a better state.
800 tg.run("install", "std")
803 func TestGoListStandard(t *testing.T) {
806 // TODO: tg.parallel()
807 tg.cd(runtime.GOROOT() + "/src")
808 tg.run("list", "-f", "{{if not .Standard}}{{.ImportPath}}{{end}}", "./...")
809 stdout := tg.getStdout()
810 for _, line := range strings.Split(stdout, "\n") {
811 if strings.HasPrefix(line, "_/") && strings.HasSuffix(line, "/src") {
812 // $GOROOT/src shows up if there are any .go files there.
819 t.Errorf("package in GOROOT not listed as standard: %v", line)
822 // Similarly, expanding std should include some of our vendored code.
823 tg.run("list", "std", "cmd")
824 tg.grepStdout("golang.org/x/net/http2/hpack", "list std cmd did not mention vendored hpack")
825 tg.grepStdout("golang.org/x/arch/x86/x86asm", "list std cmd did not mention vendored x86asm")
828 func TestGoInstallCleansUpAfterGoBuild(t *testing.T) {
831 // TODO: tg.parallel()
832 tg.tempFile("src/mycmd/main.go", `package main; func main(){}`)
833 tg.setenv("GOPATH", tg.path("."))
834 tg.cd(tg.path("src/mycmd"))
836 doesNotExist := func(file, msg string) {
837 if _, err := os.Stat(file); err == nil {
839 } else if !os.IsNotExist(err) {
840 t.Fatal(msg, "error:", err)
845 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary")
847 doesNotExist("mycmd"+exeSuffix, "testgo install did not remove command binary")
849 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (second time)")
850 // Running install with arguments does not remove the target,
851 // even in the same directory.
852 tg.run("install", "mycmd")
853 tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary when run in mycmd")
855 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (third time)")
856 // And especially not outside the directory.
858 if data, err := ioutil.ReadFile("src/mycmd/mycmd" + exeSuffix); err != nil {
859 t.Fatal("could not read file:", err)
861 if err := ioutil.WriteFile("mycmd"+exeSuffix, data, 0555); err != nil {
862 t.Fatal("could not write file:", err)
865 tg.run("install", "mycmd")
866 tg.wantExecutable("src/mycmd/mycmd"+exeSuffix, "testgo install mycmd removed command binary from its source dir when run outside mycmd")
867 tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary from current dir when run outside mycmd")
870 func TestGoInstallRebuildsStalePackagesInOtherGOPATH(t *testing.T) {
874 tg.tempFile("d1/src/p1/p1.go", `package p1
876 func F() { p2.F() }`)
877 tg.tempFile("d2/src/p2/p2.go", `package p2
879 sep := string(filepath.ListSeparator)
880 tg.setenv("GOPATH", tg.path("d1")+sep+tg.path("d2"))
881 tg.run("install", "p1")
882 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly")
883 tg.wantNotStale("p2", "", "./testgo list claims p2 is stale, incorrectly")
885 if f, err := os.OpenFile(tg.path("d2/src/p2/p2.go"), os.O_WRONLY|os.O_APPEND, 0); err != nil {
887 } else if _, err = f.WriteString(`func G() {}`); err != nil {
892 tg.wantStale("p2", "newer source file", "./testgo list claims p2 is NOT stale, incorrectly")
893 tg.wantStale("p1", "stale dependency", "./testgo list claims p1 is NOT stale, incorrectly")
895 tg.run("install", "p1")
896 tg.wantNotStale("p2", "", "./testgo list claims p2 is stale after reinstall, incorrectly")
897 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after reinstall, incorrectly")
900 func TestGoInstallDetectsRemovedFiles(t *testing.T) {
904 tg.tempFile("src/mypkg/x.go", `package mypkg`)
905 tg.tempFile("src/mypkg/y.go", `package mypkg`)
906 tg.tempFile("src/mypkg/z.go", `// +build missingtag
909 tg.setenv("GOPATH", tg.path("."))
910 tg.run("install", "mypkg")
911 tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale, incorrectly")
912 // z.go was not part of the build; removing it is okay.
913 tg.must(os.Remove(tg.path("src/mypkg/z.go")))
914 tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale after removing z.go; should not be stale")
915 // y.go was part of the package; removing it should be detected.
916 tg.must(os.Remove(tg.path("src/mypkg/y.go")))
917 tg.wantStale("mypkg", "build ID mismatch", "./testgo list mypkg claims mypkg is NOT stale after removing y.go; should be stale")
920 func TestWildcardMatchesSyntaxErrorDirs(t *testing.T) {
923 // TODO: tg.parallel()
924 tg.tempFile("src/mypkg/x.go", `package mypkg`)
925 tg.tempFile("src/mypkg/y.go", `pkg mypackage`)
926 tg.setenv("GOPATH", tg.path("."))
927 tg.cd(tg.path("src/mypkg"))
928 tg.runFail("list", "./...")
929 tg.runFail("build", "./...")
930 tg.runFail("install", "./...")
933 func TestGoListWithTags(t *testing.T) {
936 tg.tempFile("src/mypkg/x.go", "// +build thetag\n\npackage mypkg\n")
937 tg.setenv("GOPATH", tg.path("."))
938 tg.cd(tg.path("./src"))
939 tg.run("list", "-tags=thetag", "./my...")
940 tg.grepStdout("mypkg", "did not find mypkg")
943 func TestGoInstallErrorOnCrossCompileToBin(t *testing.T) {
945 t.Skip("don't install into GOROOT in short mode")
950 tg.tempFile("src/mycmd/x.go", `package main
952 tg.setenv("GOPATH", tg.path("."))
953 tg.cd(tg.path("src/mycmd"))
955 tg.run("build", "mycmd")
958 if runtime.GOARCH == "386" {
961 tg.setenv("GOOS", "linux")
962 tg.setenv("GOARCH", goarch)
963 tg.run("install", "mycmd")
964 tg.setenv("GOBIN", tg.path("."))
965 tg.runFail("install", "mycmd")
966 tg.run("install", "cmd/pack")
969 func TestGoInstallDetectsRemovedFilesInPackageMain(t *testing.T) {
973 tg.tempFile("src/mycmd/x.go", `package main
975 tg.tempFile("src/mycmd/y.go", `package main`)
976 tg.tempFile("src/mycmd/z.go", `// +build missingtag
979 tg.setenv("GOPATH", tg.path("."))
980 tg.run("install", "mycmd")
981 tg.wantNotStale("mycmd", "", "./testgo list mypkg claims mycmd is stale, incorrectly")
982 // z.go was not part of the build; removing it is okay.
983 tg.must(os.Remove(tg.path("src/mycmd/z.go")))
984 tg.wantNotStale("mycmd", "", "./testgo list mycmd claims mycmd is stale after removing z.go; should not be stale")
985 // y.go was part of the package; removing it should be detected.
986 tg.must(os.Remove(tg.path("src/mycmd/y.go")))
987 tg.wantStale("mycmd", "build ID mismatch", "./testgo list mycmd claims mycmd is NOT stale after removing y.go; should be stale")
990 func testLocalRun(tg *testgoData, exepath, local, match string) {
991 out, err := exec.Command(exepath).Output()
993 tg.t.Fatalf("error running %v: %v", exepath, err)
995 if !regexp.MustCompile(match).Match(out) {
996 tg.t.Log(string(out))
997 tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local)
1001 func testLocalEasy(tg *testgoData, local string) {
1002 exepath := "./easy" + exeSuffix
1003 tg.creatingTemp(exepath)
1004 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go"))
1005 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1008 func testLocalEasySub(tg *testgoData, local string) {
1009 exepath := "./easysub" + exeSuffix
1010 tg.creatingTemp(exepath)
1011 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go"))
1012 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1015 func testLocalHard(tg *testgoData, local string) {
1016 exepath := "./hard" + exeSuffix
1017 tg.creatingTemp(exepath)
1018 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go"))
1019 testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`)
1022 func testLocalInstall(tg *testgoData, local string) {
1023 tg.runFail("install", filepath.Join("testdata", local, "easy.go"))
1026 func TestLocalImportsEasy(t *testing.T) {
1029 testLocalEasy(tg, "local")
1032 func TestLocalImportsEasySub(t *testing.T) {
1035 testLocalEasySub(tg, "local")
1038 func TestLocalImportsHard(t *testing.T) {
1041 testLocalHard(tg, "local")
1044 func TestLocalImportsGoInstallShouldFail(t *testing.T) {
1047 testLocalInstall(tg, "local")
1050 const badDirName = `#$%:, &()*;<=>?\^{}`
1052 func copyBad(tg *testgoData) {
1053 if runtime.GOOS == "windows" {
1054 tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName)
1057 tg.must(filepath.Walk("testdata/local",
1058 func(path string, info os.FileInfo, err error) error {
1066 data, err = ioutil.ReadFile(path)
1070 newpath := strings.Replace(path, "local", badDirName, 1)
1071 tg.tempFile(newpath, string(data))
1077 func TestBadImportsEasy(t *testing.T) {
1080 // TODO: tg.parallel()
1082 testLocalEasy(tg, badDirName)
1085 func TestBadImportsEasySub(t *testing.T) {
1089 testLocalEasySub(tg, badDirName)
1092 func TestBadImportsHard(t *testing.T) {
1096 testLocalHard(tg, badDirName)
1099 func TestBadImportsGoInstallShouldFail(t *testing.T) {
1103 testLocalInstall(tg, badDirName)
1106 func TestInternalPackagesInGOROOTAreRespected(t *testing.T) {
1109 tg.runFail("build", "-v", "./testdata/testinternal")
1110 tg.grepBoth(`testinternal(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrong error message for testdata/testinternal")
1113 func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) {
1116 tg.runFail("build", "-v", "./testdata/testinternal2")
1117 tg.grepBoth(`testinternal2(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrote error message for testdata/testinternal2")
1120 func TestRunInternal(t *testing.T) {
1123 dir := filepath.Join(tg.pwd(), "testdata")
1124 tg.setenv("GOPATH", dir)
1125 tg.run("run", filepath.Join(dir, "src/run/good.go"))
1126 tg.runFail("run", filepath.Join(dir, "src/run/bad.go"))
1127 tg.grepStderr(`testdata(\/|\\)src(\/|\\)run(\/|\\)bad\.go\:3\:8\: use of internal package not allowed`, "unexpected error for run/bad.go")
1130 func testMove(t *testing.T, vcs, url, base, config string) {
1131 testenv.MustHaveExternalNetwork(t)
1137 tg.setenv("GOPATH", tg.path("."))
1138 tg.run("get", "-d", url)
1139 tg.run("get", "-d", "-u", url)
1142 // SVN doesn't believe in text files so we can't just edit the config.
1143 // Check out a different repo into the wrong place.
1144 tg.must(os.RemoveAll(tg.path("src/code.google.com/p/rsc-svn")))
1145 tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk")
1146 tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn")))
1148 path := tg.path(filepath.Join("src", config))
1149 data, err := ioutil.ReadFile(path)
1151 data = bytes.Replace(data, []byte(base), []byte(base+"XXX"), -1)
1152 tg.must(ioutil.WriteFile(path, data, 0644))
1155 // git will ask for a username and password when we
1156 // run go get -d -f -u. An empty username and
1157 // password will work. Prevent asking by setting
1159 tg.creatingTemp("sink" + exeSuffix)
1160 tg.tempFile("src/sink/sink.go", `package main; func main() {}`)
1161 tg.run("build", "-o", "sink"+exeSuffix, "sink")
1162 tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix))
1164 tg.runFail("get", "-d", "-u", url)
1165 tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason")
1166 tg.runFail("get", "-d", "-f", "-u", url)
1167 tg.grepStderr("validating server certificate|[nN]ot [fF]ound", "go get -d -f -u "+url+" failed for wrong reason")
1170 func TestInternalPackageErrorsAreHandled(t *testing.T) {
1173 tg.run("list", "./testdata/testinternal3")
1176 func TestInternalCache(t *testing.T) {
1179 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4"))
1180 tg.runFail("build", "p")
1181 tg.grepStderr("internal", "did not fail to build p")
1184 func TestMoveGit(t *testing.T) {
1185 testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config")
1188 func TestMoveHG(t *testing.T) {
1189 testMove(t, "hg", "vcs-test.golang.org/go/custom-hg-hello", "custom-hg-hello", "vcs-test.golang.org/go/custom-hg-hello/.hg/hgrc")
1192 // TODO(rsc): Set up a test case on SourceForge (?) for svn.
1193 // func testMoveSVN(t *testing.T) {
1194 // testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-")
1197 func TestImportCommandMatch(t *testing.T) {
1200 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1201 tg.run("build", "./testdata/importcom/works.go")
1204 func TestImportCommentMismatch(t *testing.T) {
1207 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1208 tg.runFail("build", "./testdata/importcom/wrongplace.go")
1209 tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import")
1212 func TestImportCommentSyntaxError(t *testing.T) {
1215 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1216 tg.runFail("build", "./testdata/importcom/bad.go")
1217 tg.grepStderr("cannot parse import comment", "go build did not mention syntax error")
1220 func TestImportCommentConflict(t *testing.T) {
1223 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1224 tg.runFail("build", "./testdata/importcom/conflict.go")
1225 tg.grepStderr("found import comments", "go build did not mention comment conflict")
1228 // cmd/go: custom import path checking should not apply to Go packages without import comment.
1229 func TestIssue10952(t *testing.T) {
1230 testenv.MustHaveExternalNetwork(t)
1231 if _, err := exec.LookPath("git"); err != nil {
1232 t.Skip("skipping because git binary not found")
1239 tg.setenv("GOPATH", tg.path("."))
1240 const importPath = "github.com/zombiezen/go-get-issue-10952"
1241 tg.run("get", "-d", "-u", importPath)
1242 repoDir := tg.path("src/" + importPath)
1243 tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git")
1244 tg.run("get", "-d", "-u", importPath)
1247 func TestIssue16471(t *testing.T) {
1248 testenv.MustHaveExternalNetwork(t)
1249 if _, err := exec.LookPath("git"); err != nil {
1250 t.Skip("skipping because git binary not found")
1257 tg.setenv("GOPATH", tg.path("."))
1258 tg.must(os.MkdirAll(tg.path("src/rsc.io/go-get-issue-10952"), 0755))
1259 tg.runGit(tg.path("src/rsc.io"), "clone", "https://github.com/zombiezen/go-get-issue-10952")
1260 tg.runFail("get", "-u", "rsc.io/go-get-issue-10952")
1261 tg.grepStderr("rsc.io/go-get-issue-10952 is a custom import path for https://github.com/rsc/go-get-issue-10952, but .* is checked out from https://github.com/zombiezen/go-get-issue-10952", "did not detect updated import path")
1264 // Test git clone URL that uses SCP-like syntax and custom import path checking.
1265 func TestIssue11457(t *testing.T) {
1266 testenv.MustHaveExternalNetwork(t)
1267 if _, err := exec.LookPath("git"); err != nil {
1268 t.Skip("skipping because git binary not found")
1275 tg.setenv("GOPATH", tg.path("."))
1276 const importPath = "rsc.io/go-get-issue-11457"
1277 tg.run("get", "-d", "-u", importPath)
1278 repoDir := tg.path("src/" + importPath)
1279 tg.runGit(repoDir, "remote", "set-url", "origin", "git@github.com:rsc/go-get-issue-11457")
1281 // At this time, custom import path checking compares remotes verbatim (rather than
1282 // just the host and path, skipping scheme and user), so we expect go get -u to fail.
1283 // However, the goal of this test is to verify that gitRemoteRepo correctly parsed
1284 // the SCP-like syntax, and we expect it to appear in the error message.
1285 tg.runFail("get", "-d", "-u", importPath)
1286 want := " is checked out from ssh://git@github.com/rsc/go-get-issue-11457"
1287 if !strings.HasSuffix(strings.TrimSpace(tg.getStderr()), want) {
1288 t.Error("expected clone URL to appear in stderr")
1292 func TestGetGitDefaultBranch(t *testing.T) {
1293 testenv.MustHaveExternalNetwork(t)
1294 if _, err := exec.LookPath("git"); err != nil {
1295 t.Skip("skipping because git binary not found")
1302 tg.setenv("GOPATH", tg.path("."))
1304 // This repo has two branches, master and another-branch.
1305 // The another-branch is the default that you get from 'git clone'.
1306 // The go get command variants should not override this.
1307 const importPath = "github.com/rsc/go-get-default-branch"
1309 tg.run("get", "-d", importPath)
1310 repoDir := tg.path("src/" + importPath)
1311 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1312 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1314 tg.run("get", "-d", "-u", importPath)
1315 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1316 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1319 func TestAccidentalGitCheckout(t *testing.T) {
1320 testenv.MustHaveExternalNetwork(t)
1321 if _, err := exec.LookPath("git"); err != nil {
1322 t.Skip("skipping because git binary not found")
1329 tg.setenv("GOPATH", tg.path("."))
1331 tg.runFail("get", "-u", "vcs-test.golang.org/go/test1-svn-git")
1332 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1334 tg.runFail("get", "-u", "vcs-test.golang.org/go/test2-svn-git/test2main")
1335 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1338 func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) {
1341 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1342 tg.runFail("test", "syntaxerror")
1343 tg.grepStderr("FAIL", "go test did not say FAIL")
1346 func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) {
1349 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1350 tg.runFail("list", "...")
1351 tg.grepBoth("badpkg", "go list ... failure does not mention badpkg")
1352 tg.run("list", "m...")
1355 func TestRelativeImportsGoTest(t *testing.T) {
1358 tg.run("test", "./testdata/testimport")
1361 func TestRelativeImportsGoTestDashI(t *testing.T) {
1364 tg.run("test", "-i", "./testdata/testimport")
1367 func TestRelativeImportsInCommandLinePackage(t *testing.T) {
1370 // TODO: tg.parallel()
1371 files, err := filepath.Glob("./testdata/testimport/*.go")
1373 tg.run(append([]string{"test"}, files...)...)
1376 func TestNonCanonicalImportPaths(t *testing.T) {
1380 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1381 tg.runFail("build", "canonical/d")
1382 tg.grepStderr("package canonical/d", "did not report canonical/d")
1383 tg.grepStderr("imports canonical/b", "did not report canonical/b")
1384 tg.grepStderr("imports canonical/a/: non-canonical", "did not report canonical/a/")
1387 func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) {
1390 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1"))
1391 tg.runFail("get", "-u", "foo")
1393 // TODO(iant): We should not have to use strconv.Quote here.
1394 // The code in vcs.go should be changed so that it is not required.
1395 quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo"))
1396 quoted = quoted[1 : len(quoted)-1]
1398 tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo")
1401 func TestInstallFailsWithNoBuildableFiles(t *testing.T) {
1404 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1405 tg.setenv("CGO_ENABLED", "0")
1406 tg.runFail("install", "cgotest")
1407 tg.grepStderr("build constraints exclude all Go files", "go install cgotest did not report 'build constraints exclude all Go files'")
1410 func TestRelativeGOBINFail(t *testing.T) {
1413 tg.tempFile("triv.go", `package main; func main() {}`)
1414 tg.setenv("GOBIN", ".")
1415 tg.runFail("install")
1416 tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path")
1419 // Test that without $GOBIN set, binaries get installed
1420 // into the GOPATH bin directory.
1421 func TestInstallIntoGOPATH(t *testing.T) {
1424 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1425 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1426 tg.run("install", "go-cmd-test")
1427 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1431 func TestBuildOutputToDevNull(t *testing.T) {
1434 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1435 tg.run("build", "-o", os.DevNull, "go-cmd-test")
1438 func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) {
1442 gobin := filepath.Join(tg.pwd(), "testdata", "bin")
1443 tg.creatingTemp(gobin)
1444 tg.setenv("GOBIN", gobin)
1445 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1446 tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now()))
1448 tg.run("test", "main_test")
1449 tg.run("install", "main_test")
1450 tg.wantNotStale("main_test", "", "after go install, main listed as stale")
1451 tg.run("test", "main_test")
1454 // The runtime version string takes one of two forms:
1455 // "go1.X[.Y]" for Go releases, and "devel +hash" at tip.
1456 // Determine whether we are in a released copy by
1457 // inspecting the version.
1458 var isGoRelease = strings.HasPrefix(runtime.Version(), "go1")
1461 func TestPackageNotStaleWithTrailingSlash(t *testing.T) {
1465 // Make sure the packages below are not stale.
1466 tg.run("install", "runtime", "os", "io")
1468 goroot := runtime.GOROOT()
1469 tg.setenv("GOROOT", goroot+"/")
1473 want = "standard package in Go release distribution"
1476 tg.wantNotStale("runtime", want, "with trailing slash in GOROOT, runtime listed as stale")
1477 tg.wantNotStale("os", want, "with trailing slash in GOROOT, os listed as stale")
1478 tg.wantNotStale("io", want, "with trailing slash in GOROOT, io listed as stale")
1481 // With $GOBIN set, binaries get installed to $GOBIN.
1482 func TestInstallIntoGOBIN(t *testing.T) {
1485 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1486 tg.creatingTemp(gobin)
1487 tg.setenv("GOBIN", gobin)
1488 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1489 tg.run("install", "go-cmd-test")
1490 tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test")
1494 func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) {
1497 pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test")
1498 tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix))
1499 tg.setenv("GOBIN", pkg)
1500 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1503 tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory")
1506 // Without $GOBIN set, installing a program outside $GOPATH should fail
1507 // (there is nowhere to install it).
1508 func TestInstallWithoutDestinationFails(t *testing.T) {
1511 tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go")
1512 tg.grepStderr("no install location for .go files listed on command line", "wrong error")
1515 // With $GOBIN set, should install there.
1516 func TestInstallToGOBINCommandLinePackage(t *testing.T) {
1519 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1520 tg.creatingTemp(gobin)
1521 tg.setenv("GOBIN", gobin)
1522 tg.run("install", "testdata/src/go-cmd-test/helloworld.go")
1523 tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld")
1526 func TestGoGetNonPkg(t *testing.T) {
1527 testenv.MustHaveExternalNetwork(t)
1532 tg.setenv("GOPATH", tg.path("."))
1533 tg.setenv("GOBIN", tg.path("gobin"))
1534 tg.runFail("get", "-d", "golang.org/x/tools")
1535 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1536 tg.runFail("get", "-d", "-u", "golang.org/x/tools")
1537 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1538 tg.runFail("get", "-d", "golang.org/x/tools")
1539 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1542 func TestGoGetTestOnlyPkg(t *testing.T) {
1543 testenv.MustHaveExternalNetwork(t)
1547 tg.tempDir("gopath")
1548 tg.setenv("GOPATH", tg.path("gopath"))
1549 tg.run("get", "golang.org/x/tour/content")
1550 tg.run("get", "-t", "golang.org/x/tour/content")
1553 func TestInstalls(t *testing.T) {
1554 if testing.Short() {
1555 t.Skip("don't install into GOROOT in short mode")
1562 tg.setenv("GOPATH", tg.path("."))
1563 goroot := runtime.GOROOT()
1564 tg.setenv("GOROOT", goroot)
1566 // cmd/fix installs into tool
1567 tg.run("env", "GOOS")
1568 goos := strings.TrimSpace(tg.getStdout())
1569 tg.setenv("GOOS", goos)
1570 tg.run("env", "GOARCH")
1571 goarch := strings.TrimSpace(tg.getStdout())
1572 tg.setenv("GOARCH", goarch)
1573 fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix
1574 tg.must(os.RemoveAll(fixbin))
1575 tg.run("install", "cmd/fix")
1576 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool")
1577 tg.must(os.Remove(fixbin))
1578 tg.setenv("GOBIN", tg.path("gobin"))
1579 tg.run("install", "cmd/fix")
1580 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set")
1581 tg.unsetenv("GOBIN")
1583 // gopath program installs into GOBIN
1584 tg.tempFile("src/progname/p.go", `package main; func main() {}`)
1585 tg.setenv("GOBIN", tg.path("gobin"))
1586 tg.run("install", "progname")
1587 tg.unsetenv("GOBIN")
1588 tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname")
1590 // gopath program installs into GOPATH/bin
1591 tg.run("install", "progname")
1592 tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname")
1595 func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) {
1598 tg.setenv("GOPATH", ".")
1599 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1600 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1603 func TestRejectRelativePathsInGOPATH(t *testing.T) {
1606 sep := string(filepath.ListSeparator)
1607 tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".")
1608 tg.runFail("build", "go-cmd-test")
1609 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1612 func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) {
1615 tg.setenv("GOPATH", "testdata")
1616 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1617 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1621 func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
1625 tg.run("test", "errors", "errors", "errors", "errors", "errors")
1626 if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") {
1627 t.Error("go test errors errors errors errors errors tested the same package multiple times")
1631 func TestGoListHasAConsistentOrder(t *testing.T) {
1635 tg.run("list", "std")
1636 first := tg.getStdout()
1637 tg.run("list", "std")
1638 if first != tg.getStdout() {
1639 t.Error("go list std ordering is inconsistent")
1643 func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
1647 tg.run("list", "std")
1648 tg.grepStdoutNot("cmd/", "go list std shows commands")
1651 func TestGoListCmdOnlyShowsCommands(t *testing.T) {
1655 tg.run("list", "cmd")
1656 out := strings.TrimSpace(tg.getStdout())
1657 for _, line := range strings.Split(out, "\n") {
1658 if !strings.Contains(line, "cmd/") {
1659 t.Error("go list cmd shows non-commands")
1665 func TestGoListDedupsPackages(t *testing.T) {
1668 // TODO: tg.parallel()
1669 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1670 tg.run("list", "xtestonly", "./testdata/src/xtestonly/...")
1671 got := strings.TrimSpace(tg.getStdout())
1672 const want = "xtestonly"
1674 t.Errorf("got %q; want %q", got, want)
1678 // Issue 4096. Validate the output of unsuccessful go install foo/quxx.
1679 func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) {
1683 tg.runFail("install", "foo/quxx")
1684 if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 {
1685 t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`)
1689 func TestGOROOTSearchFailureReporting(t *testing.T) {
1693 tg.runFail("install", "foo/quxx")
1694 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 {
1695 t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`)
1699 func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) {
1703 sep := string(filepath.ListSeparator)
1704 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1705 tg.runFail("install", "foo/quxx")
1706 if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 {
1707 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`)
1711 // Test (from $GOPATH) annotation is reported for the first GOPATH entry,
1712 func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) {
1716 sep := string(filepath.ListSeparator)
1717 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1718 tg.runFail("install", "foo/quxx")
1719 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 {
1720 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`)
1724 // but not on the second.
1725 func TestMentionGOPATHNotOnSecondEntry(t *testing.T) {
1729 sep := string(filepath.ListSeparator)
1730 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1731 tg.runFail("install", "foo/quxx")
1732 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 {
1733 t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`)
1737 func homeEnvName() string {
1738 switch runtime.GOOS {
1740 return "USERPROFILE"
1748 func TestDefaultGOPATH(t *testing.T) {
1752 tg.tempDir("home/go")
1753 tg.setenv(homeEnvName(), tg.path("home"))
1755 tg.run("env", "GOPATH")
1756 tg.grepStdout(regexp.QuoteMeta(tg.path("home/go")), "want GOPATH=$HOME/go")
1758 tg.setenv("GOROOT", tg.path("home/go"))
1759 tg.run("env", "GOPATH")
1760 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go")
1762 tg.setenv("GOROOT", tg.path("home/go")+"/")
1763 tg.run("env", "GOPATH")
1764 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go/")
1767 func TestDefaultGOPATHGet(t *testing.T) {
1768 testenv.MustHaveExternalNetwork(t)
1772 tg.setenv("GOPATH", "")
1774 tg.setenv(homeEnvName(), tg.path("home"))
1776 // warn for creating directory
1777 tg.run("get", "-v", "github.com/golang/example/hello")
1778 tg.grepStderr("created GOPATH="+regexp.QuoteMeta(tg.path("home/go"))+"; see 'go help gopath'", "did not create GOPATH")
1780 // no warning if directory already exists
1781 tg.must(os.RemoveAll(tg.path("home/go")))
1782 tg.tempDir("home/go")
1783 tg.run("get", "github.com/golang/example/hello")
1784 tg.grepStderrNot(".", "expected no output on standard error")
1786 // error if $HOME/go is a file
1787 tg.must(os.RemoveAll(tg.path("home/go")))
1788 tg.tempFile("home/go", "")
1789 tg.runFail("get", "github.com/golang/example/hello")
1790 tg.grepStderr(`mkdir .*[/\\]go: .*(not a directory|cannot find the path)`, "expected error because $HOME/go is a file")
1793 func TestDefaultGOPATHPrintedSearchList(t *testing.T) {
1796 tg.setenv("GOPATH", "")
1798 tg.setenv(homeEnvName(), tg.path("home"))
1800 tg.runFail("install", "github.com/golang/example/hello")
1801 tg.grepStderr(regexp.QuoteMeta(tg.path("home/go/src/github.com/golang/example/hello"))+`.*from \$GOPATH`, "expected default GOPATH")
1804 // Issue 4186. go get cannot be used to download packages to $GOROOT.
1805 // Test that without GOPATH set, go get should fail.
1806 func TestGoGetIntoGOROOT(t *testing.T) {
1807 testenv.MustHaveExternalNetwork(t)
1814 // Fails because GOROOT=GOPATH
1815 tg.setenv("GOPATH", tg.path("."))
1816 tg.setenv("GOROOT", tg.path("."))
1817 tg.runFail("get", "-d", "github.com/golang/example/hello")
1818 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
1819 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
1821 // Fails because GOROOT=GOPATH after cleaning.
1822 tg.setenv("GOPATH", tg.path(".")+"/")
1823 tg.setenv("GOROOT", tg.path("."))
1824 tg.runFail("get", "-d", "github.com/golang/example/hello")
1825 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
1826 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
1828 tg.setenv("GOPATH", tg.path("."))
1829 tg.setenv("GOROOT", tg.path(".")+"/")
1830 tg.runFail("get", "-d", "github.com/golang/example/hello")
1831 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
1832 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
1834 // Fails because GOROOT=$HOME/go so default GOPATH unset.
1835 tg.tempDir("home/go")
1836 tg.setenv(homeEnvName(), tg.path("home"))
1837 tg.setenv("GOPATH", "")
1838 tg.setenv("GOROOT", tg.path("home/go"))
1839 tg.runFail("get", "-d", "github.com/golang/example/hello")
1840 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
1842 tg.setenv(homeEnvName(), tg.path("home")+"/")
1843 tg.setenv("GOPATH", "")
1844 tg.setenv("GOROOT", tg.path("home/go"))
1845 tg.runFail("get", "-d", "github.com/golang/example/hello")
1846 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
1848 tg.setenv(homeEnvName(), tg.path("home"))
1849 tg.setenv("GOPATH", "")
1850 tg.setenv("GOROOT", tg.path("home/go")+"/")
1851 tg.runFail("get", "-d", "github.com/golang/example/hello")
1852 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
1855 func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) {
1859 tg.tempFile("main.go", `package main
1864 tg.run("run", "-ldflags", `-X "main.extern=hello world"`, tg.path("main.go"))
1865 tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`)
1868 func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) {
1871 // TODO: tg.parallel()
1874 tg.run("test", "-cpuprofile", "errors.prof", "errors")
1875 tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test")
1878 func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) {
1881 // TODO: tg.parallel()
1884 tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
1885 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test")
1888 func TestGoTestMutexprofileLeavesBinaryBehind(t *testing.T) {
1891 // TODO: tg.parallel()
1894 tg.run("test", "-mutexprofile", "errors.prof", "errors")
1895 tg.wantExecutable("errors.test"+exeSuffix, "go test -mutexprofile did not create errors.test")
1898 func TestGoTestMutexprofileDashOControlsBinaryLocation(t *testing.T) {
1901 // TODO: tg.parallel()
1904 tg.run("test", "-mutexprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
1905 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -mutexprofile -o myerrors.test did not create myerrors.test")
1908 func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) {
1913 tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
1914 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test")
1917 func TestGoTestDashOWritesBinary(t *testing.T) {
1922 tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
1923 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
1926 func TestGoTestDashIDashOWritesBinary(t *testing.T) {
1931 tg.run("test", "-v", "-i", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
1932 tg.grepBothNot("PASS|FAIL", "test should not have run")
1933 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
1937 func TestSymlinksList(t *testing.T) {
1938 testenv.MustHaveSymlink(t)
1942 // TODO: tg.parallel()
1944 tg.must(os.Symlink(tg.path("."), tg.path("src/dir1")))
1945 tg.tempFile("src/dir1/p.go", "package p")
1946 tg.setenv("GOPATH", tg.path("."))
1947 tg.cd(tg.path("src"))
1948 tg.run("list", "-f", "{{.Root}}", "dir1")
1949 if strings.TrimSpace(tg.getStdout()) != tg.path(".") {
1950 t.Error("confused by symlinks")
1955 func TestSymlinksVendor(t *testing.T) {
1956 testenv.MustHaveSymlink(t)
1960 // TODO: tg.parallel()
1961 tg.tempDir("gopath/src/dir1/vendor/v")
1962 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}")
1963 tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v")
1964 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
1965 tg.setenv("GOPATH", tg.path("gopath"))
1966 tg.cd(tg.path("symdir1"))
1967 tg.run("list", "-f", "{{.Root}}", ".")
1968 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
1969 t.Error("list confused by symlinks")
1972 // All of these should succeed, not die in vendor-handling code.
1973 tg.run("run", "p.go")
1979 func TestSymlinksVendor15201(t *testing.T) {
1980 testenv.MustHaveSymlink(t)
1985 tg.tempDir("gopath/src/x/y/_vendor/src/x")
1986 tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y")))
1987 tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n")
1988 tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor")))
1989 tg.tempFile("gopath/src/x/y/z/z.go", "package z\n")
1991 tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath"))
1992 tg.cd(tg.path("gopath/src"))
1993 tg.run("list", "./...")
1996 func TestSymlinksInternal(t *testing.T) {
1997 testenv.MustHaveSymlink(t)
2001 tg.tempDir("gopath/src/dir1/internal/v")
2002 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}")
2003 tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v")
2004 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2005 tg.setenv("GOPATH", tg.path("gopath"))
2006 tg.cd(tg.path("symdir1"))
2007 tg.run("list", "-f", "{{.Root}}", ".")
2008 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2009 t.Error("list confused by symlinks")
2012 // All of these should succeed, not die in internal-handling code.
2013 tg.run("run", "p.go")
2019 func TestInstallWithTags(t *testing.T) {
2024 tg.tempFile("src/example/a/main.go", `package main
2026 tg.tempFile("src/example/b/main.go", `// +build mytag
2030 tg.setenv("GOPATH", tg.path("."))
2031 tg.run("install", "-tags", "mytag", "example/a", "example/b")
2032 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries")
2033 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries")
2034 tg.must(os.Remove(tg.path("bin/a" + exeSuffix)))
2035 tg.must(os.Remove(tg.path("bin/b" + exeSuffix)))
2036 tg.run("install", "-tags", "mytag", "example/...")
2037 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries")
2038 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries")
2039 tg.run("list", "-tags", "mytag", "example/b...")
2040 if strings.TrimSpace(tg.getStdout()) != "example/b" {
2041 t.Error("go list example/b did not find example/b")
2046 func TestCaseCollisions(t *testing.T) {
2050 tg.tempDir("src/example/a/pkg")
2051 tg.tempDir("src/example/a/Pkg")
2052 tg.tempDir("src/example/b")
2053 tg.setenv("GOPATH", tg.path("."))
2054 tg.tempFile("src/example/a/a.go", `package p
2059 tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`)
2060 tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`)
2061 tg.run("list", "-json", "example/a")
2062 tg.grepStdout("case-insensitive import collision", "go list -json example/a did not report import collision")
2063 tg.runFail("build", "example/a")
2064 tg.grepStderr("case-insensitive import collision", "go build example/a did not report import collision")
2065 tg.tempFile("src/example/b/file.go", `package b`)
2066 tg.tempFile("src/example/b/FILE.go", `package b`)
2067 f, err := os.Open(tg.path("src/example/b"))
2069 names, err := f.Readdirnames(0)
2072 args := []string{"list"}
2073 if len(names) == 2 {
2074 // case-sensitive file system, let directory read find both files
2075 args = append(args, "example/b")
2077 // case-insensitive file system, list files explicitly on command line
2078 args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go"))
2081 tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision")
2083 tg.runFail("list", "example/a/pkg", "example/a/Pkg")
2084 tg.grepStderr("case-insensitive import collision", "go list example/a/pkg example/a/Pkg did not report import collision")
2085 tg.run("list", "-json", "-e", "example/a/pkg", "example/a/Pkg")
2086 tg.grepStdout("case-insensitive import collision", "go list -json -e example/a/pkg example/a/Pkg did not report import collision")
2087 tg.runFail("build", "example/a/pkg", "example/a/Pkg")
2088 tg.grepStderr("case-insensitive import collision", "go build example/a/pkg example/a/Pkg did not report import collision")
2091 // Issue 17451, 17662.
2092 func TestSymlinkWarning(t *testing.T) {
2097 tg.setenv("GOPATH", tg.path("."))
2099 tg.tempDir("src/example/xx")
2101 tg.tempFile("yy/zz/zz.go", "package zz\n")
2102 if err := os.Symlink(tg.path("yy"), tg.path("src/example/xx/yy")); err != nil {
2103 t.Skip("symlink failed: %v", err)
2105 tg.run("list", "example/xx/z...")
2106 tg.grepStdoutNot(".", "list should not have matched anything")
2107 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2108 tg.grepStderrNot("symlink", "list should not have reported symlink")
2110 tg.run("list", "example/xx/...")
2111 tg.grepStdoutNot(".", "list should not have matched anything")
2112 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2113 tg.grepStderr("ignoring symlink", "list should have reported symlink")
2117 func TestGoGetDashTIssue8181(t *testing.T) {
2118 testenv.MustHaveExternalNetwork(t)
2124 tg.setenv("GOPATH", tg.path("."))
2125 tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b")
2126 tg.run("list", "...")
2127 tg.grepStdout("x/build/gerrit", "missing expected x/build/gerrit")
2130 func TestIssue11307(t *testing.T) {
2131 // go get -u was not working except in checkout directory
2132 testenv.MustHaveExternalNetwork(t)
2138 tg.setenv("GOPATH", tg.path("."))
2139 tg.run("get", "github.com/rsc/go-get-issue-11307")
2140 tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing
2143 func TestShadowingLogic(t *testing.T) {
2147 sep := string(filepath.ListSeparator)
2148 tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2"))
2150 // The math in root1 is not "math" because the standard math is.
2151 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math")
2152 pwdForwardSlash := strings.Replace(pwd, string(os.PathSeparator), "/", -1)
2153 if !strings.HasPrefix(pwdForwardSlash, "/") {
2154 pwdForwardSlash = "/" + pwdForwardSlash
2156 // The output will have makeImportValid applies, but we only
2157 // bother to deal with characters we might reasonably see.
2158 for _, r := range " :" {
2159 pwdForwardSlash = strings.Replace(pwdForwardSlash, string(r), "_", -1)
2161 want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")"
2162 if strings.TrimSpace(tg.getStdout()) != want {
2163 t.Error("shadowed math is not shadowed; looking for", want)
2166 // The foo in root1 is "foo".
2167 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo")
2168 if strings.TrimSpace(tg.getStdout()) != "(foo) ()" {
2169 t.Error("unshadowed foo is shadowed")
2172 // The foo in root2 is not "foo" because the foo in root1 got there first.
2173 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo")
2174 want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")"
2175 if strings.TrimSpace(tg.getStdout()) != want {
2176 t.Error("shadowed foo is not shadowed; looking for", want)
2179 // The error for go install should mention the conflicting directory.
2180 tg.runFail("install", "./testdata/shadow/root2/src/foo")
2181 want = "go install: no install location for " + filepath.Join(pwd, "testdata", "shadow", "root2", "src", "foo") + ": hidden by " + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo")
2182 if strings.TrimSpace(tg.getStderr()) != want {
2183 t.Error("wrong shadowed install error; looking for", want)
2187 // Only succeeds if source order is preserved.
2188 func TestSourceFileNameOrderPreserved(t *testing.T) {
2191 tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go")
2194 // Check that coverage analysis works at all.
2195 // Don't worry about the exact numbers but require not 0.0%.
2196 func checkCoverage(tg *testgoData, data string) {
2197 if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) {
2198 tg.t.Error("some coverage results are 0.0%")
2203 func TestCoverageRuns(t *testing.T) {
2204 if testing.Short() {
2205 t.Skip("don't build libraries for coverage in short mode")
2209 tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp")
2210 data := tg.getStdout() + tg.getStderr()
2211 tg.run("test", "-short", "-cover", "strings", "math", "regexp")
2212 data += tg.getStdout() + tg.getStderr()
2213 checkCoverage(tg, data)
2216 // Check that coverage analysis uses set mode.
2217 func TestCoverageUsesSetMode(t *testing.T) {
2218 if testing.Short() {
2219 t.Skip("don't build libraries for coverage in short mode")
2223 tg.creatingTemp("testdata/cover.out")
2224 tg.run("test", "-short", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
2225 data := tg.getStdout() + tg.getStderr()
2226 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2229 if !bytes.Contains(out, []byte("mode: set")) {
2230 t.Error("missing mode: set")
2233 checkCoverage(tg, data)
2236 func TestCoverageUsesAtomicModeForRace(t *testing.T) {
2237 if testing.Short() {
2238 t.Skip("don't build libraries for coverage in short mode")
2241 t.Skip("skipping because race detector not supported")
2246 tg.creatingTemp("testdata/cover.out")
2247 tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
2248 data := tg.getStdout() + tg.getStderr()
2249 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2252 if !bytes.Contains(out, []byte("mode: atomic")) {
2253 t.Error("missing mode: atomic")
2256 checkCoverage(tg, data)
2259 func TestCoverageImportMainLoop(t *testing.T) {
2262 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2263 tg.runFail("test", "importmain/test")
2264 tg.grepStderr("not an importable package", "did not detect import main")
2265 tg.runFail("test", "-cover", "importmain/test")
2266 tg.grepStderr("not an importable package", "did not detect import main")
2269 func TestPluginNonMain(t *testing.T) {
2270 wd, err := os.Getwd()
2275 pkg := filepath.Join(wd, "testdata", "testdep", "p2")
2280 tg.runFail("build", "-buildmode=plugin", pkg)
2283 func TestTestEmpty(t *testing.T) {
2285 t.Skip("no race detector")
2289 testdata := filepath.Join(wd, "testdata")
2290 for _, dir := range []string{"pkg", "test", "xtest", "pkgtest", "pkgxtest", "pkgtestxtest", "testxtest"} {
2291 t.Run(dir, func(t *testing.T) {
2294 tg.setenv("GOPATH", testdata)
2295 tg.cd(filepath.Join(testdata, "src/empty/"+dir))
2296 tg.run("test", "-cover", "-coverpkg=.", "-race")
2298 if testing.Short() {
2304 func TestNoGoError(t *testing.T) {
2306 testdata := filepath.Join(wd, "testdata")
2307 for _, dir := range []string{"empty/test", "empty/xtest", "empty/testxtest", "exclude", "exclude/ignore", "exclude/empty"} {
2308 t.Run(dir, func(t *testing.T) {
2311 tg.setenv("GOPATH", testdata)
2312 tg.cd(filepath.Join(testdata, "src"))
2313 tg.runFail("build", "./"+dir)
2315 if strings.Contains(dir, "test") {
2316 want = "no non-test Go files in "
2317 } else if dir == "exclude" {
2318 want = "build constraints exclude all Go files in "
2320 want = "no Go files in "
2322 tg.grepStderr(want, "wrong reason for failure")
2327 func TestTestRaceInstall(t *testing.T) {
2329 t.Skip("no race detector")
2331 if testing.Short() && testenv.Builder() == "" {
2332 t.Skip("don't rebuild the standard library in short mode")
2337 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2340 pkgdir := tg.path("pkg")
2341 tg.run("install", "-race", "-pkgdir="+pkgdir, "std")
2342 tg.run("test", "-race", "-pkgdir="+pkgdir, "-i", "-v", "empty/pkg")
2343 if tg.getStderr() != "" {
2344 t.Error("go test -i -race: rebuilds cached packages")
2348 func TestBuildDryRunWithCgo(t *testing.T) {
2350 t.Skip("skipping because cgo not enabled")
2355 tg.tempFile("foo.go", `package main
2365 tg.run("build", "-n", tg.path("foo.go"))
2366 tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file")
2369 func TestCoverageWithCgo(t *testing.T) {
2371 t.Skip("skipping because cgo not enabled")
2374 for _, dir := range []string{"cgocover", "cgocover2", "cgocover3", "cgocover4"} {
2375 t.Run(dir, func(t *testing.T) {
2379 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2380 tg.run("test", "-short", "-cover", dir)
2381 data := tg.getStdout() + tg.getStderr()
2382 checkCoverage(tg, data)
2387 func TestCgoAsmError(t *testing.T) {
2389 t.Skip("skipping because cgo not enabled")
2395 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2396 tg.runFail("build", "cgoasm")
2397 tg.grepBoth("package using cgo has Go assembly file", "did not detect Go assembly file")
2400 func TestCgoDependsOnSyscall(t *testing.T) {
2401 if testing.Short() {
2402 t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode")
2405 t.Skip("skipping because cgo not enabled")
2408 t.Skip("skipping because race detector not supported")
2413 files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race"))
2415 for _, file := range files {
2416 tg.check(os.RemoveAll(file))
2418 tg.tempFile("src/foo/foo.go", `
2420 //#include <stdio.h>
2422 tg.setenv("GOPATH", tg.path("."))
2423 tg.run("build", "-race", "foo")
2426 func TestCgoShowsFullPathNames(t *testing.T) {
2428 t.Skip("skipping because cgo not enabled")
2434 tg.tempFile("src/x/y/dirname/foo.go", `
2438 tg.setenv("GOPATH", tg.path("."))
2439 tg.runFail("build", "x/y/dirname")
2440 tg.grepBoth("x/y/dirname", "error did not use full path")
2443 func TestCgoHandlesWlORIGIN(t *testing.T) {
2445 t.Skip("skipping because cgo not enabled")
2451 tg.tempFile("src/origin/origin.go", `package origin
2452 // #cgo !darwin LDFLAGS: -Wl,-rpath -Wl,$ORIGIN
2455 func f() { C.f() }`)
2456 tg.setenv("GOPATH", tg.path("."))
2457 tg.run("build", "origin")
2460 func TestCgoPkgConfig(t *testing.T) {
2462 t.Skip("skipping because cgo not enabled")
2468 tg.run("env", "PKG_CONFIG")
2469 pkgConfig := strings.TrimSpace(tg.getStdout())
2470 if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil {
2471 t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out)
2474 // OpenBSD's pkg-config is strict about whitespace and only
2475 // supports backslash-escaped whitespace. It does not support
2476 // quotes, which the normal freedesktop.org pkg-config does
2477 // support. See http://man.openbsd.org/pkg-config.1
2478 tg.tempFile("foo.pc", `
2480 Description: The foo library
2482 Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world
2484 tg.tempFile("foo.go", `package main
2487 #cgo pkg-config: foo
2489 return DEFINED_FROM_PKG_CONFIG;
2496 if C.value() != 42 {
2497 println("value() =", C.value(), "wanted 42")
2502 tg.setenv("PKG_CONFIG_PATH", tg.path("."))
2503 tg.run("run", tg.path("foo.go"))
2506 // "go test -c -test.bench=XXX errors" should not hang
2507 func TestIssue6480(t *testing.T) {
2510 // TODO: tg.parallel()
2513 tg.run("test", "-c", "-test.bench=XXX", "errors")
2516 // cmd/cgo: undefined reference when linking a C-library using gccgo
2517 func TestIssue7573(t *testing.T) {
2519 t.Skip("skipping because cgo not enabled")
2521 if _, err := exec.LookPath("gccgo"); err != nil {
2522 t.Skip("skipping because no gccgo compiler found")
2528 tg.tempFile("src/cgoref/cgoref.go", `
2530 // #cgo LDFLAGS: -L alibpath -lalib
2534 func main() { C.f() }`)
2535 tg.setenv("GOPATH", tg.path("."))
2536 tg.run("build", "-n", "-compiler", "gccgo", "cgoref")
2537 tg.grepStderr(`gccgo.*\-L [^ ]*alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`)
2540 func TestListTemplateContextFunction(t *testing.T) {
2542 for _, tt := range []struct {
2546 {"GOARCH", runtime.GOARCH},
2547 {"GOOS", runtime.GOOS},
2548 {"GOROOT", filepath.Clean(runtime.GOROOT())},
2549 {"GOPATH", os.Getenv("GOPATH")},
2551 {"UseAllFiles", ""},
2554 {"ReleaseTags", ""},
2555 {"InstallSuffix", ""},
2558 t.Run(tt.v, func(t *testing.T) {
2562 tmpl := "{{context." + tt.v + "}}"
2563 tg.run("list", "-f", tmpl)
2567 if got := strings.TrimSpace(tg.getStdout()); got != tt.want {
2568 t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want)
2574 // cmd/go: "go test" should fail if package does not build
2575 func TestIssue7108(t *testing.T) {
2578 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2579 tg.runFail("test", "notest")
2582 // cmd/go: go test -a foo does not rebuild regexp.
2583 func TestIssue6844(t *testing.T) {
2584 if testing.Short() {
2585 t.Skip("don't rebuild the standard library in short mode")
2590 tg.creatingTemp("deps.test" + exeSuffix)
2591 tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go")
2592 tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp")
2595 func TestBuildDashIInstallsDependencies(t *testing.T) {
2599 tg.tempFile("src/x/y/foo/foo.go", `package foo
2601 tg.tempFile("src/x/y/bar/bar.go", `package bar
2603 func F() { foo.F() }`)
2604 tg.setenv("GOPATH", tg.path("."))
2606 checkbar := func(desc string) {
2608 tg.must(os.Chtimes(tg.path("src/x/y/foo/foo.go"), time.Now(), time.Now()))
2610 tg.run("build", "-v", "-i", "x/y/bar")
2611 tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo")
2612 tg.run("build", "-v", "-i", "x/y/bar")
2613 tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo")
2616 tg.creatingTemp("bar" + exeSuffix)
2617 tg.tempFile("src/x/y/bar/bar.go", `package main
2619 func main() { foo.F() }`)
2623 func TestGoBuildInTestOnlyDirectoryFailsWithAGoodError(t *testing.T) {
2626 tg.runFail("build", "./testdata/testonly")
2627 tg.grepStderr("no non-test Go files in", "go build ./testdata/testonly produced unexpected error")
2630 func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) {
2633 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2634 tg.runFail("test", "-c", "testcycle/p3")
2635 tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error")
2637 tg.runFail("test", "-c", "testcycle/q1")
2638 tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error")
2641 func TestGoTestFooTestWorks(t *testing.T) {
2644 tg.run("test", "testdata/standalone_test.go")
2647 func TestGoTestFlagsAfterPackage(t *testing.T) {
2650 tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags.
2651 tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags.
2654 func TestGoTestXtestonlyWorks(t *testing.T) {
2657 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2658 tg.run("clean", "-i", "xtestonly")
2659 tg.run("test", "xtestonly")
2662 func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) {
2665 tg.run("test", "-v", "./testdata/norunexample")
2666 tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built")
2669 func TestGoGenerateHandlesSimpleCommand(t *testing.T) {
2670 if runtime.GOOS == "windows" {
2671 t.Skip("skipping because windows has no echo command")
2676 tg.run("generate", "./testdata/generate/test1.go")
2677 tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output")
2680 func TestGoGenerateHandlesCommandAlias(t *testing.T) {
2681 if runtime.GOOS == "windows" {
2682 t.Skip("skipping because windows has no echo command")
2687 tg.run("generate", "./testdata/generate/test2.go")
2688 tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output")
2691 func TestGoGenerateVariableSubstitution(t *testing.T) {
2692 if runtime.GOOS == "windows" {
2693 t.Skip("skipping because windows has no echo command")
2698 tg.run("generate", "./testdata/generate/test3.go")
2699 tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output")
2702 func TestGoGenerateRunFlag(t *testing.T) {
2703 if runtime.GOOS == "windows" {
2704 t.Skip("skipping because windows has no echo command")
2709 tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go")
2710 tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes")
2711 tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no")
2714 func TestGoGenerateEnv(t *testing.T) {
2715 switch runtime.GOOS {
2716 case "plan9", "windows":
2717 t.Skipf("skipping because %s does not have the env command", runtime.GOOS)
2722 tg.tempFile("env.go", "package main\n\n//go:generate env")
2723 tg.run("generate", tg.path("env.go"))
2724 for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} {
2725 tg.grepStdout("^"+v+"=", "go generate environment missing "+v)
2729 func TestGoGenerateBadImports(t *testing.T) {
2730 if runtime.GOOS == "windows" {
2731 t.Skip("skipping because windows has no echo command")
2734 // This package has an invalid import causing an import cycle,
2735 // but go generate is supposed to still run.
2738 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2739 tg.run("generate", "gencycle")
2740 tg.grepStdout("hello world", "go generate gencycle did not run generator")
2743 func TestGoGetCustomDomainWildcard(t *testing.T) {
2744 testenv.MustHaveExternalNetwork(t)
2749 tg.setenv("GOPATH", tg.path("."))
2750 tg.run("get", "-u", "rsc.io/pdf/...")
2751 tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd")
2754 func TestGoGetInternalWildcard(t *testing.T) {
2755 testenv.MustHaveExternalNetwork(t)
2760 tg.setenv("GOPATH", tg.path("."))
2761 // used to fail with errors about internal packages
2762 tg.run("get", "github.com/rsc/go-get-issue-11960/...")
2765 func TestGoVetWithExternalTests(t *testing.T) {
2769 tg.run("install", "cmd/vet")
2770 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2771 tg.runFail("vet", "vetpkg")
2772 tg.grepBoth("missing argument for Printf", "go vet vetpkg did not find missing argument for Printf")
2775 func TestGoVetWithTags(t *testing.T) {
2779 tg.run("install", "cmd/vet")
2780 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2781 tg.runFail("vet", "-tags", "tagtest", "vetpkg")
2782 tg.grepBoth(`c\.go.*wrong number of args for format`, "go vet vetpkg did not run scan tagged file")
2785 func TestGoVetWithFlagsOn(t *testing.T) {
2789 tg.run("install", "cmd/vet")
2790 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2791 tg.runFail("vet", "-printf", "vetpkg")
2792 tg.grepBoth("missing argument for Printf", "go vet -printf vetpkg did not find missing argument for Printf")
2795 func TestGoVetWithFlagsOff(t *testing.T) {
2799 tg.run("install", "cmd/vet")
2800 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2801 tg.run("vet", "-printf=false", "vetpkg")
2804 // Issue 9767, 19769.
2805 func TestGoGetDotSlashDownload(t *testing.T) {
2806 testenv.MustHaveExternalNetwork(t)
2810 tg.tempDir("src/rsc.io")
2811 tg.setenv("GOPATH", tg.path("."))
2812 tg.cd(tg.path("src/rsc.io"))
2813 tg.run("get", "./pprof_mac_fix")
2816 // Issue 13037: Was not parsing <meta> tags in 404 served over HTTPS
2817 func TestGoGetHTTPS404(t *testing.T) {
2818 testenv.MustHaveExternalNetwork(t)
2819 switch runtime.GOOS {
2820 case "darwin", "linux", "freebsd":
2822 t.Skipf("test case does not work on %s", runtime.GOOS)
2828 tg.setenv("GOPATH", tg.path("."))
2829 tg.run("get", "bazil.org/fuse/fs/fstestutil")
2832 // Test that you cannot import a main package.
2833 // See golang.org/issue/4210 and golang.org/issue/17475.
2834 func TestImportMain(t *testing.T) {
2839 // Importing package main from that package main's test should work.
2840 tg.tempFile("src/x/main.go", `package main
2843 tg.tempFile("src/x/main_test.go", `package main_test
2847 func TestFoo(t *testing.T) {}
2849 tg.setenv("GOPATH", tg.path("."))
2850 tg.creatingTemp("x" + exeSuffix)
2851 tg.run("build", "x")
2854 // Importing package main from another package should fail.
2855 tg.tempFile("src/p1/p.go", `package p1
2859 tg.runFail("build", "p1")
2860 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
2862 // ... even in that package's test.
2863 tg.tempFile("src/p2/p.go", `package p2
2865 tg.tempFile("src/p2/p_test.go", `package p2
2869 func TestFoo(t *testing.T) {}
2871 tg.run("build", "p2")
2872 tg.runFail("test", "p2")
2873 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
2875 // ... even if that package's test is an xtest.
2876 tg.tempFile("src/p3/p.go", `package p
2878 tg.tempFile("src/p3/p_test.go", `package p_test
2882 func TestFoo(t *testing.T) {}
2884 tg.run("build", "p3")
2885 tg.runFail("test", "p3")
2886 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
2888 // ... even if that package is a package main
2889 tg.tempFile("src/p4/p.go", `package main
2892 tg.tempFile("src/p4/p_test.go", `package main
2896 func TestFoo(t *testing.T) {}
2898 tg.creatingTemp("p4" + exeSuffix)
2899 tg.run("build", "p4")
2900 tg.runFail("test", "p4")
2901 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
2903 // ... even if that package is a package main using an xtest.
2904 tg.tempFile("src/p5/p.go", `package main
2907 tg.tempFile("src/p5/p_test.go", `package main_test
2911 func TestFoo(t *testing.T) {}
2913 tg.creatingTemp("p5" + exeSuffix)
2914 tg.run("build", "p5")
2915 tg.runFail("test", "p5")
2916 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
2919 // Test that you cannot use a local import in a package
2920 // accessed by a non-local import (found in a GOPATH/GOROOT).
2921 // See golang.org/issue/17475.
2922 func TestImportLocal(t *testing.T) {
2927 tg.tempFile("src/dir/x/x.go", `package x
2930 tg.setenv("GOPATH", tg.path("."))
2931 tg.run("build", "dir/x")
2933 // Ordinary import should work.
2934 tg.tempFile("src/dir/p0/p.go", `package p0
2938 tg.run("build", "dir/p0")
2940 // Relative import should not.
2941 tg.tempFile("src/dir/p1/p.go", `package p1
2945 tg.runFail("build", "dir/p1")
2946 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
2948 // ... even in a test.
2949 tg.tempFile("src/dir/p2/p.go", `package p2
2951 tg.tempFile("src/dir/p2/p_test.go", `package p2
2955 func TestFoo(t *testing.T) {}
2957 tg.run("build", "dir/p2")
2958 tg.runFail("test", "dir/p2")
2959 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
2961 // ... even in an xtest.
2962 tg.tempFile("src/dir/p2/p_test.go", `package p2_test
2966 func TestFoo(t *testing.T) {}
2968 tg.run("build", "dir/p2")
2969 tg.runFail("test", "dir/p2")
2970 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
2972 // Relative import starting with ./ should not work either.
2973 tg.tempFile("src/dir/d.go", `package dir
2977 tg.runFail("build", "dir")
2978 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
2980 // ... even in a test.
2981 tg.tempFile("src/dir/d.go", `package dir
2983 tg.tempFile("src/dir/d_test.go", `package dir
2987 func TestFoo(t *testing.T) {}
2989 tg.run("build", "dir")
2990 tg.runFail("test", "dir")
2991 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
2993 // ... even in an xtest.
2994 tg.tempFile("src/dir/d_test.go", `package dir_test
2998 func TestFoo(t *testing.T) {}
3000 tg.run("build", "dir")
3001 tg.runFail("test", "dir")
3002 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3004 // Relative import plain ".." should not work.
3005 tg.tempFile("src/dir/x/y/y.go", `package dir
3009 tg.runFail("build", "dir/x/y")
3010 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3012 // ... even in a test.
3013 tg.tempFile("src/dir/x/y/y.go", `package y
3015 tg.tempFile("src/dir/x/y/y_test.go", `package y
3019 func TestFoo(t *testing.T) {}
3021 tg.run("build", "dir/x/y")
3022 tg.runFail("test", "dir/x/y")
3023 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3025 // ... even in an x test.
3026 tg.tempFile("src/dir/x/y/y_test.go", `package y_test
3030 func TestFoo(t *testing.T) {}
3032 tg.run("build", "dir/x/y")
3033 tg.runFail("test", "dir/x/y")
3034 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3036 // Relative import "." should not work.
3037 tg.tempFile("src/dir/x/xx.go", `package x
3041 tg.runFail("build", "dir/x")
3042 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3044 // ... even in a test.
3045 tg.tempFile("src/dir/x/xx.go", `package x
3047 tg.tempFile("src/dir/x/xx_test.go", `package x
3051 func TestFoo(t *testing.T) {}
3053 tg.run("build", "dir/x")
3054 tg.runFail("test", "dir/x")
3055 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3057 // ... even in an xtest.
3058 tg.tempFile("src/dir/x/xx.go", `package x
3060 tg.tempFile("src/dir/x/xx_test.go", `package x_test
3064 func TestFoo(t *testing.T) {}
3066 tg.run("build", "dir/x")
3067 tg.runFail("test", "dir/x")
3068 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3071 func TestGoGetInsecure(t *testing.T) {
3072 testenv.MustHaveExternalNetwork(t)
3077 tg.setenv("GOPATH", tg.path("."))
3080 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3082 // Try go get -d of HTTP-only repo (should fail).
3083 tg.runFail("get", "-d", repo)
3085 // Try again with -insecure (should succeed).
3086 tg.run("get", "-d", "-insecure", repo)
3088 // Try updating without -insecure (should fail).
3089 tg.runFail("get", "-d", "-u", "-f", repo)
3092 func TestGoGetUpdateInsecure(t *testing.T) {
3093 testenv.MustHaveExternalNetwork(t)
3098 tg.setenv("GOPATH", tg.path("."))
3100 const repo = "github.com/golang/example"
3102 // Clone the repo via HTTP manually.
3103 cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
3104 if out, err := cmd.CombinedOutput(); err != nil {
3105 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3108 // Update without -insecure should fail.
3109 // Update with -insecure should succeed.
3110 // We need -f to ignore import comments.
3111 const pkg = repo + "/hello"
3112 tg.runFail("get", "-d", "-u", "-f", pkg)
3113 tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
3116 func TestGoGetInsecureCustomDomain(t *testing.T) {
3117 testenv.MustHaveExternalNetwork(t)
3122 tg.setenv("GOPATH", tg.path("."))
3124 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3125 tg.runFail("get", "-d", repo)
3126 tg.run("get", "-d", "-insecure", repo)
3129 func TestGoRunDirs(t *testing.T) {
3132 tg.cd("testdata/rundir")
3133 tg.runFail("run", "x.go", "sub/sub.go")
3134 tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
3135 tg.runFail("run", "sub/sub.go", "x.go")
3136 tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
3139 func TestGoInstallPkgdir(t *testing.T) {
3145 tg.run("install", "-pkgdir", pkg, "errors")
3146 _, err := os.Stat(filepath.Join(pkg, "errors.a"))
3148 _, err = os.Stat(filepath.Join(pkg, "runtime.a"))
3152 func TestGoTestRaceInstallCgo(t *testing.T) {
3154 t.Skip("skipping because race detector not supported")
3157 // golang.org/issue/10500.
3158 // This used to install a race-enabled cgo.
3161 tg.run("tool", "-n", "cgo")
3162 cgo := strings.TrimSpace(tg.stdout.String())
3163 old, err := os.Stat(cgo)
3165 tg.run("test", "-race", "-i", "runtime/race")
3166 new, err := os.Stat(cgo)
3168 if !new.ModTime().Equal(old.ModTime()) {
3169 t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
3173 func TestGoTestRaceFailures(t *testing.T) {
3175 t.Skip("skipping because race detector not supported")
3181 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3183 tg.run("test", "testrace")
3185 tg.runFail("test", "-race", "testrace")
3186 tg.grepStdout("FAIL: TestRace", "TestRace did not fail")
3187 tg.grepBothNot("PASS", "something passed")
3189 tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".")
3190 tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail")
3191 tg.grepBothNot("PASS", "something passed")
3194 func TestGoTestImportErrorStack(t *testing.T) {
3195 const out = `package testdep/p1 (test)
3197 imports testdep/p3: build constraints exclude all Go files `
3201 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3202 tg.runFail("test", "testdep/p1")
3203 if !strings.Contains(tg.stderr.String(), out) {
3204 t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String())
3208 func TestGoGetUpdate(t *testing.T) {
3209 // golang.org/issue/9224.
3210 // The recursive updating was trying to walk to
3211 // former dependencies, not current ones.
3213 testenv.MustHaveExternalNetwork(t)
3218 tg.setenv("GOPATH", tg.path("."))
3221 tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
3222 cmd := exec.Command("git", "reset", "--hard", "HEAD~")
3223 cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
3224 out, err := cmd.CombinedOutput()
3226 t.Fatalf("git: %v\n%s", err, out)
3231 tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3233 // Again with -d -u.
3235 tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3239 func TestGoGetRace(t *testing.T) {
3240 testenv.MustHaveExternalNetwork(t)
3242 t.Skip("skipping because race detector not supported")
3248 tg.setenv("GOPATH", tg.path("."))
3249 tg.run("get", "-race", "github.com/rsc/go-get-issue-9224-cmd")
3252 func TestGoGetDomainRoot(t *testing.T) {
3253 // golang.org/issue/9357.
3254 // go get foo.io (not foo.io/subdir) was not working consistently.
3256 testenv.MustHaveExternalNetwork(t)
3261 tg.setenv("GOPATH", tg.path("."))
3263 // go-get-issue-9357.appspot.com is running
3264 // the code at github.com/rsc/go-get-issue-9357,
3265 // a trivial Go on App Engine app that serves a
3266 // <meta> tag for the domain root.
3267 tg.run("get", "-d", "go-get-issue-9357.appspot.com")
3268 tg.run("get", "go-get-issue-9357.appspot.com")
3269 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3271 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3272 tg.run("get", "go-get-issue-9357.appspot.com")
3274 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3275 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3278 func TestGoInstallShadowedGOPATH(t *testing.T) {
3279 // golang.org/issue/3652.
3280 // go get foo.io (not foo.io/subdir) was not working consistently.
3282 testenv.MustHaveExternalNetwork(t)
3287 tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
3289 tg.tempDir("gopath1/src/test")
3290 tg.tempDir("gopath2/src/test")
3291 tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
3293 tg.cd(tg.path("gopath2/src/test"))
3294 tg.runFail("install")
3295 tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
3298 func TestGoBuildGOPATHOrder(t *testing.T) {
3299 // golang.org/issue/14176#issuecomment-179895769
3300 // golang.org/issue/14192
3301 // -I arguments to compiler could end up not in GOPATH order,
3302 // leading to unexpected import resolution in the compiler.
3303 // This is still not a complete fix (see golang.org/issue/14271 and next test)
3304 // but it is clearly OK and enough to fix both of the two reported
3305 // instances of the underlying problem. It will have to do for now.
3310 tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2"))
3312 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3313 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3314 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3315 tg.tempFile("p1/src/bar/bar.go", `
3321 tg.run("install", "-x", "bar")
3324 func TestGoBuildGOPATHOrderBroken(t *testing.T) {
3325 // This test is known not to work.
3326 // See golang.org/issue/14271.
3327 t.Skip("golang.org/issue/14271")
3333 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3334 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3335 tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n")
3336 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3337 tg.tempFile("p1/src/bar/bar.go", `
3343 colon := string(filepath.ListSeparator)
3344 tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2"))
3345 tg.run("install", "-x", "bar")
3347 tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1"))
3348 tg.run("install", "-x", "bar")
3351 func TestIssue11709(t *testing.T) {
3354 tg.tempFile("run.go", `
3358 if os.Getenv("TERM") != "" {
3363 tg.run("run", tg.path("run.go"))
3366 func TestIssue12096(t *testing.T) {
3369 tg.tempFile("test_test.go", `
3371 import ("os"; "testing")
3372 func TestEnv(t *testing.T) {
3373 if os.Getenv("TERM") != "" {
3374 t.Fatal("TERM is set")
3378 tg.run("test", tg.path("test_test.go"))
3381 func TestGoBuildOutput(t *testing.T) {
3388 nonExeSuffix := ".exe"
3389 if exeSuffix == ".exe" {
3393 tg.tempFile("x.go", "package main\nfunc main(){}\n")
3394 tg.run("build", "x.go")
3395 tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
3396 tg.must(os.Remove(tg.path("x" + exeSuffix)))
3397 tg.mustNotExist("x" + nonExeSuffix)
3399 tg.run("build", "-o", "myprog", "x.go")
3400 tg.mustNotExist("x")
3401 tg.mustNotExist("x.exe")
3402 tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
3403 tg.mustNotExist("myprog.exe")
3405 tg.tempFile("p.go", "package p\n")
3406 tg.run("build", "p.go")
3407 tg.mustNotExist("p")
3408 tg.mustNotExist("p.a")
3409 tg.mustNotExist("p.o")
3410 tg.mustNotExist("p.exe")
3412 tg.run("build", "-o", "p.a", "p.go")
3413 tg.wantArchive("p.a")
3415 tg.run("build", "cmd/gofmt")
3416 tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
3417 tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
3418 tg.mustNotExist("gofmt" + nonExeSuffix)
3420 tg.run("build", "-o", "mygofmt", "cmd/gofmt")
3421 tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
3422 tg.mustNotExist("mygofmt.exe")
3423 tg.mustNotExist("gofmt")
3424 tg.mustNotExist("gofmt.exe")
3426 tg.run("build", "sync/atomic")
3427 tg.mustNotExist("atomic")
3428 tg.mustNotExist("atomic.exe")
3430 tg.run("build", "-o", "myatomic.a", "sync/atomic")
3431 tg.wantArchive("myatomic.a")
3432 tg.mustNotExist("atomic")
3433 tg.mustNotExist("atomic.a")
3434 tg.mustNotExist("atomic.exe")
3436 tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
3437 tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
3440 func TestGoBuildARM(t *testing.T) {
3441 if testing.Short() {
3442 t.Skip("skipping cross-compile in short mode")
3451 tg.setenv("GOARCH", "arm")
3452 tg.setenv("GOOS", "linux")
3453 tg.setenv("GOARM", "5")
3454 tg.tempFile("hello.go", `package main
3456 tg.run("build", "hello.go")
3457 tg.grepStderrNot("unable to find math.a", "did not build math.a correctly")
3460 func TestIssue13655(t *testing.T) {
3463 for _, pkg := range []string{"runtime", "runtime/internal/atomic"} {
3464 tg.run("list", "-f", "{{.Deps}}", pkg)
3465 tg.grepStdout("runtime/internal/sys", "did not find required dependency of "+pkg+" on runtime/internal/sys")
3470 func TestParallelTest(t *testing.T) {
3475 const testSrc = `package package_test
3479 func TestTest(t *testing.T) {
3481 tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
3482 tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
3483 tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
3484 tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
3485 tg.setenv("GOPATH", tg.path("."))
3486 tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
3489 func TestCgoConsistentResults(t *testing.T) {
3491 t.Skip("skipping because cgo not enabled")
3493 switch runtime.GOOS {
3495 testenv.SkipFlaky(t, 15405)
3497 testenv.SkipFlaky(t, 13247)
3504 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3505 exe1 := tg.path("cgotest1" + exeSuffix)
3506 exe2 := tg.path("cgotest2" + exeSuffix)
3507 tg.run("build", "-o", exe1, "cgotest")
3508 tg.run("build", "-x", "-o", exe2, "cgotest")
3509 b1, err := ioutil.ReadFile(exe1)
3511 b2, err := ioutil.ReadFile(exe2)
3514 if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) {
3515 t.Skip("skipping because C compiler does not support -fdebug-prefix-map")
3517 if !bytes.Equal(b1, b2) {
3518 t.Error("building cgotest twice did not produce the same output")
3522 // Issue 14444: go get -u .../ duplicate loads errors
3523 func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) {
3524 testenv.MustHaveExternalNetwork(t)
3529 tg.setenv("GOPATH", tg.path("."))
3530 tg.run("get", "-u", ".../")
3531 tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache")
3534 // Issue 17119 more duplicate load errors
3535 func TestIssue17119(t *testing.T) {
3536 testenv.MustHaveExternalNetwork(t)
3541 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3542 tg.runFail("build", "dupload")
3543 tg.grepBothNot("duplicate load|internal error", "internal error")
3546 func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) {
3549 // TODO: tg.parallel()
3550 tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal")
3551 tg.grepBothNot("^ok", "test passed unexpectedly")
3552 tg.grepBoth("FAIL.*benchfatal", "test did not run everything")
3555 func TestBinaryOnlyPackages(t *testing.T) {
3560 tg.setenv("GOPATH", tg.path("."))
3562 tg.tempFile("src/p1/p1.go", `//go:binary-only-package
3566 tg.wantStale("p1", "cannot access install target", "p1 is binary-only but has no binary, should be stale")
3567 tg.runFail("install", "p1")
3568 tg.grepStderr("missing or invalid package binary", "did not report attempt to compile binary-only package")
3570 tg.tempFile("src/p1/p1.go", `
3573 func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } }
3575 tg.run("install", "p1")
3576 os.Remove(tg.path("src/p1/p1.go"))
3577 tg.mustNotExist(tg.path("src/p1/p1.go"))
3579 tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great
3583 func F() { p1.F(true) }
3585 tg.runFail("install", "p2")
3586 tg.grepStderr("no Go files", "did not complain about missing sources")
3588 tg.tempFile("src/p1/missing.go", `//go:binary-only-package
3593 tg.wantNotStale("p1", "no source code", "should NOT want to rebuild p1 (first)")
3594 tg.run("install", "-x", "p1") // no-op, up to date
3595 tg.grepBothNot("/compile", "should not have run compiler")
3596 tg.run("install", "p2") // does not rebuild p1 (or else p2 will fail)
3597 tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
3599 // changes to the non-source-code do not matter,
3600 // and only one file needs the special comment.
3601 tg.tempFile("src/p1/missing2.go", `
3605 tg.wantNotStale("p1", "no source code", "should NOT want to rebuild p1 (second)")
3606 tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
3608 tg.tempFile("src/p3/p3.go", `
3619 tg.run("install", "p3")
3621 tg.run("run", tg.path("src/p3/p3.go"))
3622 tg.grepStdout("hello from p1", "did not see message from p1")
3624 tg.tempFile("src/p4/p4.go", `package main`)
3625 tg.tempFile("src/p4/p4not.go", `//go:binary-only-package
3631 tg.run("list", "-f", "{{.BinaryOnly}}", "p4")
3632 tg.grepStdout("false", "did not see BinaryOnly=false for p4")
3635 // Issue 16050 and 21884.
3636 func TestLinkSysoFiles(t *testing.T) {
3640 tg.tempDir("src/syso")
3641 tg.tempFile("src/syso/a.syso", ``)
3642 tg.tempFile("src/syso/b.go", `package syso`)
3643 tg.setenv("GOPATH", tg.path("."))
3645 // We should see the .syso file regardless of the setting of
3648 tg.setenv("CGO_ENABLED", "1")
3649 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
3650 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1")
3652 tg.setenv("CGO_ENABLED", "0")
3653 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
3654 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0")
3656 tg.setenv("CGO_ENABLED", "1")
3657 tg.run("list", "-msan", "-f", "{{.SysoFiles}}", "syso")
3658 tg.grepStdoutNot("a.syso", "unexpected syso file with -msan")
3662 func TestGenerateUsesBuildContext(t *testing.T) {
3663 if runtime.GOOS == "windows" {
3664 t.Skip("this test won't run under Windows")
3670 tg.tempDir("src/gen")
3671 tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n")
3672 tg.setenv("GOPATH", tg.path("."))
3674 tg.setenv("GOOS", "linux")
3675 tg.setenv("GOARCH", "amd64")
3676 tg.run("generate", "gen")
3677 tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination")
3679 tg.setenv("GOOS", "darwin")
3680 tg.setenv("GOARCH", "386")
3681 tg.run("generate", "gen")
3682 tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination")
3685 // Issue 14450: go get -u .../ tried to import not downloaded package
3686 func TestGoGetUpdateWithWildcard(t *testing.T) {
3687 testenv.MustHaveExternalNetwork(t)
3693 tg.setenv("GOPATH", tg.path("."))
3694 const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a"
3695 tg.run("get", aPkgImportPath)
3696 tg.run("get", "-u", ".../")
3697 tg.grepStderrNot("cannot find package", "did not update packages given wildcard path")
3699 var expectedPkgPaths = []string{
3700 "src/github.com/tmwh/go-get-issue-14450/b",
3701 "src/github.com/tmwh/go-get-issue-14450-b-dependency/c",
3702 "src/github.com/tmwh/go-get-issue-14450-b-dependency/d",
3705 for _, importPath := range expectedPkgPaths {
3706 _, err := os.Stat(tg.path(importPath))
3709 const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e"
3710 tg.mustNotExist(tg.path(notExpectedPkgPath))
3713 func TestGoEnv(t *testing.T) {
3717 tg.setenv("GOARCH", "arm")
3718 tg.run("env", "GOARCH")
3719 tg.grepStdout("^arm$", "GOARCH not honored")
3721 tg.run("env", "GCCGO")
3722 tg.grepStdout(".", "GCCGO unexpectedly empty")
3724 tg.run("env", "CGO_CFLAGS")
3725 tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty")
3727 tg.setenv("CGO_CFLAGS", "-foobar")
3728 tg.run("env", "CGO_CFLAGS")
3729 tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored")
3731 tg.setenv("CC", "gcc -fmust -fgo -ffaster")
3733 tg.grepStdout("gcc", "CC not found")
3734 tg.run("env", "GOGCCFLAGS")
3735 tg.grepStdout("-ffaster", "CC arguments not found")
3739 noMatchesPattern = `(?m)^ok.*\[no tests to run\]`
3740 okPattern = `(?m)^ok`
3743 func TestMatchesNoTests(t *testing.T) {
3746 // TODO: tg.parallel()
3747 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go")
3748 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
3751 func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) {
3755 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3756 tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror")
3757 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
3758 tg.grepBoth("FAIL", "go test did not say FAIL")
3761 func TestMatchesNoBenchmarksIsOK(t *testing.T) {
3764 // TODO: tg.parallel()
3765 tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go")
3766 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
3767 tg.grepBoth(okPattern, "go test did not say ok")
3770 func TestMatchesOnlyExampleIsOK(t *testing.T) {
3773 // TODO: tg.parallel()
3774 tg.run("test", "-run", "Example", "testdata/example1_test.go")
3775 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
3776 tg.grepBoth(okPattern, "go test did not say ok")
3779 func TestMatchesOnlyBenchmarkIsOK(t *testing.T) {
3782 // TODO: tg.parallel()
3783 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
3784 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
3785 tg.grepBoth(okPattern, "go test did not say ok")
3788 func TestBenchmarkLabels(t *testing.T) {
3791 // TODO: tg.parallel()
3792 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3793 tg.run("test", "-run", "^$", "-bench", ".", "bench")
3794 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
3795 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
3796 tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench")
3797 tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times")
3800 func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) {
3803 // TODO: tg.parallel()
3804 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
3805 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
3806 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
3807 tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:")
3810 func TestMatchesOnlyTestIsOK(t *testing.T) {
3813 // TODO: tg.parallel()
3814 tg.run("test", "-run", "Test", "testdata/standalone_test.go")
3815 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
3816 tg.grepBoth(okPattern, "go test did not say ok")
3819 func TestMatchesNoTestsWithSubtests(t *testing.T) {
3822 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go")
3823 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
3826 func TestMatchesNoSubtestsMatch(t *testing.T) {
3829 tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go")
3830 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
3833 func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) {
3836 tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go")
3837 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
3838 tg.grepBoth("FAIL", "go test did not say FAIL")
3841 func TestMatchesOnlySubtestIsOK(t *testing.T) {
3844 tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go")
3845 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
3846 tg.grepBoth(okPattern, "go test did not say ok")
3849 func TestMatchesNoSubtestsParallel(t *testing.T) {
3852 tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go")
3853 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
3856 func TestMatchesOnlySubtestParallelIsOK(t *testing.T) {
3859 tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go")
3860 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
3861 tg.grepBoth(okPattern, "go test did not say ok")
3865 func TestBenchTimeout(t *testing.T) {
3868 tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go")
3871 func TestLinkXImportPathEscape(t *testing.T) {
3872 // golang.org/issue/16710
3876 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3877 exe := "./linkx" + exeSuffix
3878 tg.creatingTemp(exe)
3879 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main")
3880 out, err := exec.Command(exe).CombinedOutput()
3884 if string(out) != "linkXworked\n" {
3885 tg.t.Log(string(out))
3886 tg.t.Fatal(`incorrect output: expected "linkXworked\n"`)
3891 func TestLdBindNow(t *testing.T) {
3895 tg.setenv("LD_BIND_NOW", "1")
3900 // This is really a cmd/asm issue but this is a convenient place to test it.
3901 func TestConcurrentAsm(t *testing.T) {
3905 asm := `DATA ·constants<>+0x0(SB)/8,$0
3906 GLOBL ·constants<>(SB),8,$8
3908 tg.tempFile("go/src/p/a.s", asm)
3909 tg.tempFile("go/src/p/b.s", asm)
3910 tg.tempFile("go/src/p/p.go", `package p`)
3911 tg.setenv("GOPATH", tg.path("go"))
3912 tg.run("build", "p")
3916 func TestDotDotDotOutsideGOPATH(t *testing.T) {
3920 tg.tempFile("pkgs/a.go", `package x`)
3921 tg.tempFile("pkgs/a_test.go", `package x_test
3923 func TestX(t *testing.T) {}`)
3925 tg.tempFile("pkgs/a/a.go", `package a`)
3926 tg.tempFile("pkgs/a/a_test.go", `package a_test
3928 func TestA(t *testing.T) {}`)
3930 tg.cd(tg.path("pkgs"))
3931 tg.run("build", "./...")
3932 tg.run("test", "./...")
3933 tg.run("list", "./...")
3934 tg.grepStdout("pkgs$", "expected package not listed")
3935 tg.grepStdout("pkgs/a", "expected package not listed")
3939 func TestFFLAGS(t *testing.T) {
3941 t.Skip("skipping because cgo not enabled")
3948 tg.tempFile("p/src/p/main.go", `package main
3949 // #cgo FFLAGS: -no-such-fortran-flag
3953 tg.tempFile("p/src/p/a.f", `! comment`)
3954 tg.setenv("GOPATH", tg.path("p"))
3956 // This should normally fail because we are passing an unknown flag,
3957 // but issue #19080 points to Fortran compilers that succeed anyhow.
3958 // To work either way we call doRun directly rather than run or runFail.
3959 tg.doRun([]string{"build", "-x", "p"})
3961 tg.grepStderr("no-such-fortran-flag", `missing expected "-no-such-fortran-flag"`)
3965 // This is really a cmd/link issue but this is a convenient place to test it.
3966 func TestDuplicateGlobalAsmSymbols(t *testing.T) {
3967 if runtime.GOARCH != "386" && runtime.GOARCH != "amd64" {
3968 t.Skipf("skipping test on %s", runtime.GOARCH)
3971 t.Skip("skipping because cgo not enabled")
3979 #include "textflag.h"
3981 DATA sym<>+0x0(SB)/8,$0
3982 GLOBL sym<>(SB),(NOPTR+RODATA),$8
3984 TEXT ·Data(SB),NOSPLIT,$0
3989 tg.tempFile("go/src/a/a.s", asm)
3990 tg.tempFile("go/src/a/a.go", `package a; func Data() uint8`)
3991 tg.tempFile("go/src/b/b.s", asm)
3992 tg.tempFile("go/src/b/b.go", `package b; func Data() uint8`)
3993 tg.tempFile("go/src/p/p.go", `
3999 _ = a.Data() + b.Data()
4002 tg.setenv("GOPATH", tg.path("go"))
4003 exe := filepath.Join(tg.tempdir, "p.exe")
4004 tg.creatingTemp(exe)
4005 tg.run("build", "-o", exe, "p")
4008 func TestBuildTagsNoComma(t *testing.T) {
4012 tg.setenv("GOPATH", tg.path("go"))
4013 tg.run("install", "-tags", "tag1 tag2", "math")
4014 tg.runFail("install", "-tags", "tag1,tag2", "math")
4015 tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
4016 tg.runFail("build", "-tags", "tag1,tag2", "math")
4017 tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
4020 func copyFile(src, dst string, perm os.FileMode) error {
4021 sf, err := os.Open(src)
4027 df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
4032 _, err = io.Copy(df, sf)
4040 func TestExecutableGOROOT(t *testing.T) {
4041 if runtime.GOOS == "openbsd" {
4042 t.Skipf("test case does not work on %s, missing os.Executable", runtime.GOOS)
4045 // Env with no GOROOT.
4047 for _, e := range os.Environ() {
4048 if !strings.HasPrefix(e, "GOROOT=") {
4049 env = append(env, e)
4053 check := func(t *testing.T, exe, want string) {
4054 cmd := exec.Command(exe, "env", "GOROOT")
4056 out, err := cmd.CombinedOutput()
4058 t.Fatalf("%s env GOROOT: %v, %s", exe, err, out)
4060 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4064 want, err = filepath.EvalSymlinks(want)
4068 if !strings.EqualFold(goroot, want) {
4069 t.Errorf("go env GOROOT:\nhave %s\nwant %s", goroot, want)
4071 t.Logf("go env GOROOT: %s", goroot)
4075 // Note: Must not call tg methods inside subtests: tg is attached to outer t.
4080 tg.tempDir("new/bin")
4081 newGoTool := tg.path("new/bin/go" + exeSuffix)
4082 tg.must(copyFile(tg.goTool(), newGoTool, 0775))
4083 newRoot := tg.path("new")
4085 t.Run("RelocatedExe", func(t *testing.T) {
4086 t.Skip("TODO: skipping known broken test; see golang.org/issue/20284")
4088 // Should fall back to default location in binary.
4089 // No way to dig out other than look at source code.
4090 data, err := ioutil.ReadFile("../../runtime/internal/sys/zversion.go")
4094 m := regexp.MustCompile("const DefaultGoroot = `([^`]+)`").FindStringSubmatch(string(data))
4096 t.Fatal("cannot find DefaultGoroot in ../../runtime/internal/sys/zversion.go")
4098 check(t, newGoTool, m[1])
4101 // If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT,
4102 // so it should find the new tree.
4103 tg.tempDir("new/pkg/tool")
4104 t.Run("RelocatedTree", func(t *testing.T) {
4105 check(t, newGoTool, newRoot)
4108 tg.tempDir("other/bin")
4109 symGoTool := tg.path("other/bin/go" + exeSuffix)
4111 // Symlink into go tree should still find go tree.
4112 t.Run("SymlinkedExe", func(t *testing.T) {
4113 testenv.MustHaveSymlink(t)
4114 if err := os.Symlink(newGoTool, symGoTool); err != nil {
4117 check(t, symGoTool, newRoot)
4121 func TestNeedVersion(t *testing.T) {
4125 tg.tempFile("goversion.go", `package main; func main() {}`)
4126 path := tg.path("goversion.go")
4127 tg.setenv("TESTGO_VERSION", "go1.testgo")
4128 tg.runFail("run", path)
4129 tg.grepStderr("compile", "does not match go tool version")
4132 // Test that user can override default code generation flags.
4133 func TestUserOverrideFlags(t *testing.T) {
4135 t.Skip("skipping because cgo not enabled")
4137 if runtime.GOOS != "linux" {
4138 // We are testing platform-independent code, so it's
4139 // OK to skip cases that work differently.
4140 t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS)
4146 tg.tempFile("override.go", `package main
4154 tg.creatingTemp("override.a")
4155 tg.creatingTemp("override.h")
4156 tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=-shared=false", tg.path("override.go"))
4157 tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag")
4160 func TestCgoFlagContainsSpace(t *testing.T) {
4162 t.Skip("skipping because cgo not enabled")
4168 ccName := filepath.Base(testCC)
4170 tg.tempFile(fmt.Sprintf("src/%s/main.go", ccName), fmt.Sprintf(`package main
4178 cmd := exec.Command(%q, os.Args[1:]...)
4179 cmd.Stdin = os.Stdin
4180 cmd.Stdout = os.Stdout
4181 cmd.Stderr = os.Stderr
4187 if os.Args[len(os.Args)-1] == "trivial.c" {
4192 for _, arg := range os.Args {
4194 case strings.Contains(arg, "c flags"):
4196 panic("duplicate CFLAGS")
4199 case strings.Contains(arg, "ld flags"):
4201 panic("duplicate LDFLAGS")
4207 panic("args should contains '-Ic flags' or '-Lld flags'")
4211 tg.cd(tg.path(fmt.Sprintf("src/%s", ccName)))
4213 tg.setenv("CC", tg.path(fmt.Sprintf("src/%s/%s", ccName, ccName)))
4215 tg.tempFile("src/cgo/main.go", `package main
4216 // #cgo CFLAGS: -I"c flags"
4217 // #cgo LDFLAGS: -L"ld flags"
4221 tg.cd(tg.path("src/cgo"))
4222 tg.run("run", "main.go")
4226 func TestGoTestRaceCoverModeFailures(t *testing.T) {
4228 t.Skip("skipping because race detector not supported")
4234 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4236 tg.run("test", "testrace")
4238 tg.runFail("test", "-race", "-covermode=set", "testrace")
4239 tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed")
4240 tg.grepBothNot("PASS", "something passed")
4243 // Issue 9737: verify that GOARM and GO386 affect the computed build ID.
4244 func TestBuildIDContainsArchModeEnv(t *testing.T) {
4245 if testing.Short() {
4246 t.Skip("skipping in short mode")
4250 testWith := func(before, after func()) func(*testing.T) {
4251 return func(t *testing.T) {
4254 tg.tempFile("src/mycmd/x.go", `package main
4256 tg.setenv("GOPATH", tg.path("."))
4258 tg.cd(tg.path("src/mycmd"))
4259 tg.setenv("GOOS", "linux")
4261 tg.run("install", "mycmd")
4263 tg.wantStale("mycmd", "build ID mismatch", "should be stale after environment variable change")
4267 t.Run("386", testWith(func() {
4268 tg.setenv("GOARCH", "386")
4269 tg.setenv("GO386", "387")
4271 tg.setenv("GO386", "sse2")
4274 t.Run("arm", testWith(func() {
4275 tg.setenv("GOARCH", "arm")
4276 tg.setenv("GOARM", "5")
4278 tg.setenv("GOARM", "7")
4282 func TestTestRegexps(t *testing.T) {
4285 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4286 tg.run("test", "-cpu=1", "-run=X/Y", "-bench=X/Y", "-count=2", "-v", "testregexp")
4288 for _, line := range strings.SplitAfter(tg.getStdout(), "\n") {
4289 if strings.Contains(line, "=== RUN") || strings.Contains(line, "--- BENCH") || strings.Contains(line, "LOG") {
4290 lines = append(lines, line)
4295 // TestX is run, twice
4296 // TestX/Y is run, twice
4297 // TestXX is run, twice
4299 // BenchmarkX is run but only with N=1, once
4300 // BenchmarkXX is run but only with N=1, once
4301 // BenchmarkX/Y is run in full, twice
4302 want := `=== RUN TestX
4304 x_test.go:6: LOG: X running
4305 x_test.go:8: LOG: Y running
4307 z_test.go:10: LOG: XX running
4310 x_test.go:6: LOG: X running
4311 x_test.go:8: LOG: Y running
4313 z_test.go:10: LOG: XX running
4314 --- BENCH: BenchmarkX/Y
4315 x_test.go:15: LOG: Y running N=1
4316 x_test.go:15: LOG: Y running N=100
4317 x_test.go:15: LOG: Y running N=10000
4318 x_test.go:15: LOG: Y running N=1000000
4319 x_test.go:15: LOG: Y running N=100000000
4320 x_test.go:15: LOG: Y running N=2000000000
4321 --- BENCH: BenchmarkX/Y
4322 x_test.go:15: LOG: Y running N=1
4323 x_test.go:15: LOG: Y running N=100
4324 x_test.go:15: LOG: Y running N=10000
4325 x_test.go:15: LOG: Y running N=1000000
4326 x_test.go:15: LOG: Y running N=100000000
4327 x_test.go:15: LOG: Y running N=2000000000
4328 --- BENCH: BenchmarkX
4329 x_test.go:13: LOG: X running N=1
4330 --- BENCH: BenchmarkXX
4331 z_test.go:18: LOG: XX running N=1
4334 have := strings.Join(lines, "")
4336 t.Errorf("reduced output:<<<\n%s>>> want:<<<\n%s>>>", have, want)
4340 func TestListTests(t *testing.T) {
4342 testWith := func(listName, expected string) func(*testing.T) {
4343 return func(t *testing.T) {
4346 tg.run("test", "./testdata/src/testlist/...", fmt.Sprintf("-list=%s", listName))
4347 tg.grepStdout(expected, fmt.Sprintf("-test.list=%s returned %q, expected %s", listName, tg.getStdout(), expected))
4351 t.Run("Test", testWith("Test", "TestSimple"))
4352 t.Run("Bench", testWith("Benchmark", "BenchmarkSimple"))
4353 t.Run("Example1", testWith("Example", "ExampleSimple"))
4354 t.Run("Example2", testWith("Example", "ExampleWithEmptyOutput"))