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.
29 canRun = true // whether we can run go or ./testgo
30 canRace = false // whether we can run the race detector
31 canCgo = false // whether we can use cgo
32 canMSan = false // whether we can run the memory sanitizer
34 exeSuffix string // ".exe" on Windows
36 skipExternal = false // skip external tests
41 case "android", "nacl":
44 switch runtime.GOARCH {
49 switch runtime.GOARCH {
51 // many linux/arm machines are too slow to run
52 // the full set of external tests.
54 case "mips", "mipsle", "mips64", "mips64le":
57 if testenv.Builder() != "" {
58 // On the builders, skip the cmd/go
59 // tests. They're too slow and already
60 // covered by other ports. There's
61 // nothing os/arch specific in the
67 switch runtime.GOARCH {
69 // many freebsd/arm machines are too slow to run
70 // the full set of external tests.
79 // testGOROOT is the GOROOT to use when running testgo, a cmd/go binary
80 // build from this process's current GOROOT, but run from a different
86 // The TestMain function creates a go command for testing purposes and
87 // deletes it after the tests have been run.
88 func TestMain(m *testing.M) {
89 if os.Getenv("GO_GCFLAGS") != "" {
90 fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
91 fmt.Printf("cmd/go test is not compatible with $GO_GCFLAGS being set\n")
97 args := []string{"build", "-tags", "testgo", "-o", "testgo" + exeSuffix}
99 args = append(args, "-race")
101 gotool, err := testenv.GoTool()
103 fmt.Fprintln(os.Stderr, err)
107 goEnv := func(name string) string {
108 out, err := exec.Command(gotool, "env", name).CombinedOutput()
110 fmt.Fprintf(os.Stderr, "go env %s: %v\n%s", name, err, out)
113 return strings.TrimSpace(string(out))
115 testGOROOT = goEnv("GOROOT")
117 // The whole GOROOT/pkg tree was installed using the GOHOSTOS/GOHOSTARCH
118 // toolchain (installed in GOROOT/pkg/tool/GOHOSTOS_GOHOSTARCH).
119 // The testgo.exe we are about to create will be built for GOOS/GOARCH,
120 // which means it will use the GOOS/GOARCH toolchain
121 // (installed in GOROOT/pkg/tool/GOOS_GOARCH).
122 // If these are not the same toolchain, then the entire standard library
123 // will look out of date (the compilers in those two different tool directories
124 // are built for different architectures and have different buid IDs),
125 // which will cause many tests to do unnecessary rebuilds and some
126 // tests to attempt to overwrite the installed standard library.
127 // Bail out entirely in this case.
128 hostGOOS := goEnv("GOHOSTOS")
129 hostGOARCH := goEnv("GOHOSTARCH")
130 if hostGOOS != runtime.GOOS || hostGOARCH != runtime.GOARCH {
131 fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
132 fmt.Printf("cmd/go test is not compatible with GOOS/GOARCH != GOHOSTOS/GOHOSTARCH (%s/%s != %s/%s)\n", runtime.GOOS, runtime.GOARCH, hostGOOS, hostGOARCH)
137 out, err := exec.Command(gotool, args...).CombinedOutput()
139 fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out)
143 out, err = exec.Command(gotool, "env", "CC").CombinedOutput()
145 fmt.Fprintf(os.Stderr, "could not find testing CC: %v\n%s", err, out)
148 testCC = strings.TrimSpace(string(out))
150 if out, err := exec.Command("./testgo"+exeSuffix, "env", "CGO_ENABLED").Output(); err != nil {
151 fmt.Fprintf(os.Stderr, "running testgo failed: %v\n", err)
154 canCgo, err = strconv.ParseBool(strings.TrimSpace(string(out)))
156 fmt.Fprintf(os.Stderr, "can't parse go env CGO_ENABLED output: %v\n", strings.TrimSpace(string(out)))
160 // As of Sept 2017, MSan is only supported on linux/amd64.
161 // https://github.com/google/sanitizers/wiki/MemorySanitizer#getting-memorysanitizer
162 canMSan = canCgo && runtime.GOOS == "linux" && runtime.GOARCH == "amd64"
164 switch runtime.GOOS {
165 case "linux", "darwin", "freebsd", "windows":
166 // The race detector doesn't work on Alpine Linux:
167 // golang.org/issue/14481
168 canRace = canCgo && runtime.GOARCH == "amd64" && !isAlpineLinux()
171 // Don't let these environment variables confuse the test.
173 os.Unsetenv("GOPATH")
174 os.Unsetenv("GIT_ALLOW_PROTOCOL")
175 if home, ccacheDir := os.Getenv("HOME"), os.Getenv("CCACHE_DIR"); home != "" && ccacheDir == "" {
176 // On some systems the default C compiler is ccache.
177 // Setting HOME to a non-existent directory will break
178 // those systems. Set CCACHE_DIR to cope. Issue 17668.
179 os.Setenv("CCACHE_DIR", filepath.Join(home, ".ccache"))
181 os.Setenv("HOME", "/test-go-home-does-not-exist")
182 if os.Getenv("GOCACHE") == "" {
183 os.Setenv("GOCACHE", "off") // because $HOME is gone
189 os.Remove("testgo" + exeSuffix)
195 func isAlpineLinux() bool {
196 if runtime.GOOS != "linux" {
199 fi, err := os.Lstat("/etc/alpine-release")
200 return err == nil && fi.Mode().IsRegular()
203 // The length of an mtime tick on this system. This is an estimate of
204 // how long we need to sleep to ensure that the mtime of two files is
206 // We used to try to be clever but that didn't always work (see golang.org/issue/12205).
207 var mtimeTick time.Duration = 1 * time.Second
209 // Manage a single run of the testgo binary.
210 type testgoData struct {
218 stdout, stderr bytes.Buffer
221 // testgo sets up for a test that runs testgo.
222 func testgo(t *testing.T) *testgoData {
224 testenv.MustHaveGoBuild(t)
227 t.Skip("skipping external tests on %s/%s", runtime.GOOS, runtime.GOARCH)
230 return &testgoData{t: t}
233 // must gives a fatal error if err is not nil.
234 func (tg *testgoData) must(err error) {
241 // check gives a test non-fatal error if err is not nil.
242 func (tg *testgoData) check(err error) {
249 // parallel runs the test in parallel by calling t.Parallel.
250 func (tg *testgoData) parallel() {
253 tg.t.Fatal("internal testsuite error: call to parallel after run")
256 tg.t.Fatal("internal testsuite error: call to parallel after cd")
258 for _, e := range tg.env {
259 if strings.HasPrefix(e, "GOROOT=") || strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
260 val := e[strings.Index(e, "=")+1:]
261 if strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata") {
262 tg.t.Fatalf("internal testsuite error: call to parallel with testdata in environment (%s)", e)
270 // pwd returns the current directory.
271 func (tg *testgoData) pwd() string {
273 wd, err := os.Getwd()
275 tg.t.Fatalf("could not get working directory: %v", err)
280 // cd changes the current directory to the named directory. Note that
281 // using this means that the test must not be run in parallel with any
283 func (tg *testgoData) cd(dir string) {
286 tg.t.Fatal("internal testsuite error: changing directory when running in parallel")
291 abs, err := filepath.Abs(dir)
292 tg.must(os.Chdir(dir))
294 tg.setenv("PWD", abs)
298 // sleep sleeps for one tick, where a tick is a conservative estimate
299 // of how long it takes for a file modification to get a different
301 func (tg *testgoData) sleep() {
302 time.Sleep(mtimeTick)
305 // setenv sets an environment variable to use when running the test go
307 func (tg *testgoData) setenv(name, val string) {
309 if tg.inParallel && (name == "GOROOT" || name == "GOPATH" || name == "GOBIN") && (strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata")) {
310 tg.t.Fatalf("internal testsuite error: call to setenv with testdata (%s=%s) after parallel", name, val)
313 tg.env = append(tg.env, name+"="+val)
316 // unsetenv removes an environment variable.
317 func (tg *testgoData) unsetenv(name string) {
319 tg.env = append([]string(nil), os.Environ()...)
321 for i, v := range tg.env {
322 if strings.HasPrefix(v, name+"=") {
323 tg.env = append(tg.env[:i], tg.env[i+1:]...)
329 func (tg *testgoData) goTool() string {
331 return "./testgo" + exeSuffix
333 return filepath.Join(tg.wd, "testgo"+exeSuffix)
336 // doRun runs the test go command, recording stdout and stderr and
337 // returning exit status.
338 func (tg *testgoData) doRun(args []string) error {
341 panic("testgoData.doRun called but canRun false")
344 for _, arg := range args {
345 if strings.HasPrefix(arg, "testdata") || strings.HasPrefix(arg, "./testdata") {
346 tg.t.Fatal("internal testsuite error: parallel run using testdata")
352 for _, v := range tg.env {
353 if strings.HasPrefix(v, "GOROOT=") {
360 tg.setenv("GOROOT", testGOROOT)
363 tg.t.Logf("running testgo %v", args)
364 cmd := exec.Command(prog, args...)
367 cmd.Stdout = &tg.stdout
368 cmd.Stderr = &tg.stderr
371 if tg.stdout.Len() > 0 {
372 tg.t.Log("standard output:")
373 tg.t.Log(tg.stdout.String())
375 if tg.stderr.Len() > 0 {
376 tg.t.Log("standard error:")
377 tg.t.Log(tg.stderr.String())
383 // run runs the test go command, and expects it to succeed.
384 func (tg *testgoData) run(args ...string) {
386 if status := tg.doRun(args); status != nil {
387 tg.t.Logf("go %v failed unexpectedly: %v", args, status)
392 // runFail runs the test go command, and expects it to fail.
393 func (tg *testgoData) runFail(args ...string) {
395 if status := tg.doRun(args); status == nil {
396 tg.t.Fatal("testgo succeeded unexpectedly")
398 tg.t.Log("testgo failed as expected:", status)
402 // runGit runs a git command, and expects it to succeed.
403 func (tg *testgoData) runGit(dir string, args ...string) {
405 cmd := exec.Command("git", args...)
408 cmd.Stdout = &tg.stdout
409 cmd.Stderr = &tg.stderr
413 if tg.stdout.Len() > 0 {
414 tg.t.Log("git standard output:")
415 tg.t.Log(tg.stdout.String())
417 if tg.stderr.Len() > 0 {
418 tg.t.Log("git standard error:")
419 tg.t.Log(tg.stderr.String())
422 tg.t.Logf("git %v failed unexpectedly: %v", args, status)
427 // getStdout returns standard output of the testgo run as a string.
428 func (tg *testgoData) getStdout() string {
431 tg.t.Fatal("internal testsuite error: stdout called before run")
433 return tg.stdout.String()
436 // getStderr returns standard error of the testgo run as a string.
437 func (tg *testgoData) getStderr() string {
440 tg.t.Fatal("internal testsuite error: stdout called before run")
442 return tg.stderr.String()
445 // doGrepMatch looks for a regular expression in a buffer, and returns
446 // whether it is found. The regular expression is matched against
447 // each line separately, as with the grep command.
448 func (tg *testgoData) doGrepMatch(match string, b *bytes.Buffer) bool {
451 tg.t.Fatal("internal testsuite error: grep called before run")
453 re := regexp.MustCompile(match)
454 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
462 // doGrep looks for a regular expression in a buffer and fails if it
463 // is not found. The name argument is the name of the output we are
464 // searching, "output" or "error". The msg argument is logged on
466 func (tg *testgoData) doGrep(match string, b *bytes.Buffer, name, msg string) {
468 if !tg.doGrepMatch(match, b) {
470 tg.t.Logf("pattern %v not found in standard %s", match, name)
475 // grepStdout looks for a regular expression in the test run's
476 // standard output and fails, logging msg, if it is not found.
477 func (tg *testgoData) grepStdout(match, msg string) {
479 tg.doGrep(match, &tg.stdout, "output", msg)
482 // grepStderr looks for a regular expression in the test run's
483 // standard error and fails, logging msg, if it is not found.
484 func (tg *testgoData) grepStderr(match, msg string) {
486 tg.doGrep(match, &tg.stderr, "error", msg)
489 // grepBoth looks for a regular expression in the test run's standard
490 // output or stand error and fails, logging msg, if it is not found.
491 func (tg *testgoData) grepBoth(match, msg string) {
493 if !tg.doGrepMatch(match, &tg.stdout) && !tg.doGrepMatch(match, &tg.stderr) {
495 tg.t.Logf("pattern %v not found in standard output or standard error", match)
500 // doGrepNot looks for a regular expression in a buffer and fails if
501 // it is found. The name and msg arguments are as for doGrep.
502 func (tg *testgoData) doGrepNot(match string, b *bytes.Buffer, name, msg string) {
504 if tg.doGrepMatch(match, b) {
506 tg.t.Logf("pattern %v found unexpectedly in standard %s", match, name)
511 // grepStdoutNot looks for a regular expression in the test run's
512 // standard output and fails, logging msg, if it is found.
513 func (tg *testgoData) grepStdoutNot(match, msg string) {
515 tg.doGrepNot(match, &tg.stdout, "output", msg)
518 // grepStderrNot looks for a regular expression in the test run's
519 // standard error and fails, logging msg, if it is found.
520 func (tg *testgoData) grepStderrNot(match, msg string) {
522 tg.doGrepNot(match, &tg.stderr, "error", msg)
525 // grepBothNot looks for a regular expression in the test run's
526 // standard output or stand error and fails, logging msg, if it is
528 func (tg *testgoData) grepBothNot(match, msg string) {
530 if tg.doGrepMatch(match, &tg.stdout) || tg.doGrepMatch(match, &tg.stderr) {
532 tg.t.Fatalf("pattern %v found unexpectedly in standard output or standard error", match)
536 // doGrepCount counts the number of times a regexp is seen in a buffer.
537 func (tg *testgoData) doGrepCount(match string, b *bytes.Buffer) int {
540 tg.t.Fatal("internal testsuite error: doGrepCount called before run")
542 re := regexp.MustCompile(match)
544 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
552 // grepCountBoth returns the number of times a regexp is seen in both
553 // standard output and standard error.
554 func (tg *testgoData) grepCountBoth(match string) int {
556 return tg.doGrepCount(match, &tg.stdout) + tg.doGrepCount(match, &tg.stderr)
559 // creatingTemp records that the test plans to create a temporary file
560 // or directory. If the file or directory exists already, it will be
561 // removed. When the test completes, the file or directory will be
562 // removed if it exists.
563 func (tg *testgoData) creatingTemp(path string) {
565 if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) {
566 tg.t.Fatalf("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path)
568 // If we have changed the working directory, make sure we have
569 // an absolute path, because we are going to change directory
570 // back before we remove the temporary.
571 if tg.wd != "" && !filepath.IsAbs(path) {
572 path = filepath.Join(tg.pwd(), path)
574 tg.must(os.RemoveAll(path))
575 tg.temps = append(tg.temps, path)
578 // makeTempdir makes a temporary directory for a run of testgo. If
579 // the temporary directory was already created, this does nothing.
580 func (tg *testgoData) makeTempdir() {
582 if tg.tempdir == "" {
584 tg.tempdir, err = ioutil.TempDir("", "gotest")
589 // tempFile adds a temporary file for a run of testgo.
590 func (tg *testgoData) tempFile(path, contents string) {
593 tg.must(os.MkdirAll(filepath.Join(tg.tempdir, filepath.Dir(path)), 0755))
594 bytes := []byte(contents)
595 if strings.HasSuffix(path, ".go") {
596 formatted, err := format.Source(bytes)
601 tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644))
604 // tempDir adds a temporary directory for a run of testgo.
605 func (tg *testgoData) tempDir(path string) {
608 if err := os.MkdirAll(filepath.Join(tg.tempdir, path), 0755); err != nil && !os.IsExist(err) {
613 // path returns the absolute pathname to file with the temporary
615 func (tg *testgoData) path(name string) string {
617 if tg.tempdir == "" {
618 tg.t.Fatalf("internal testsuite error: path(%q) with no tempdir", name)
623 return filepath.Join(tg.tempdir, name)
626 // mustExist fails if path does not exist.
627 func (tg *testgoData) mustExist(path string) {
629 if _, err := os.Stat(path); err != nil {
630 if os.IsNotExist(err) {
631 tg.t.Fatalf("%s does not exist but should", path)
633 tg.t.Fatalf("%s stat failed: %v", path, err)
637 // mustNotExist fails if path exists.
638 func (tg *testgoData) mustNotExist(path string) {
640 if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
641 tg.t.Fatalf("%s exists but should not (%v)", path, err)
645 // mustHaveContent succeeds if filePath is a path to a file,
646 // and that file is readable and not empty.
647 func (tg *testgoData) mustHaveContent(filePath string) {
648 tg.mustExist(filePath)
649 f, err := os.Stat(filePath)
654 tg.t.Fatalf("expected %s to have data, but is empty", filePath)
658 // wantExecutable fails with msg if path is not executable.
659 func (tg *testgoData) wantExecutable(path, msg string) {
661 if st, err := os.Stat(path); err != nil {
662 if !os.IsNotExist(err) {
667 if runtime.GOOS != "windows" && st.Mode()&0111 == 0 {
668 tg.t.Fatalf("binary %s exists but is not executable", path)
673 // wantArchive fails if path is not an archive.
674 func (tg *testgoData) wantArchive(path string) {
676 f, err := os.Open(path)
680 buf := make([]byte, 100)
683 if !bytes.HasPrefix(buf, []byte("!<arch>\n")) {
684 tg.t.Fatalf("file %s exists but is not an archive", path)
688 // isStale reports whether pkg is stale, and why
689 func (tg *testgoData) isStale(pkg string) (bool, string) {
691 tg.run("list", "-f", "{{.Stale}}:{{.StaleReason}}", pkg)
692 v := strings.TrimSpace(tg.getStdout())
693 f := strings.SplitN(v, ":", 2)
702 tg.t.Fatalf("unexpected output checking staleness of package %v: %v", pkg, v)
706 // wantStale fails with msg if pkg is not stale.
707 func (tg *testgoData) wantStale(pkg, reason, msg string) {
709 stale, why := tg.isStale(pkg)
713 if reason == "" && why != "" || !strings.Contains(why, reason) {
714 tg.t.Errorf("wrong reason for Stale=true: %q, want %q", why, reason)
718 // wantNotStale fails with msg if pkg is stale.
719 func (tg *testgoData) wantNotStale(pkg, reason, msg string) {
721 stale, why := tg.isStale(pkg)
725 if reason == "" && why != "" || !strings.Contains(why, reason) {
726 tg.t.Errorf("wrong reason for Stale=false: %q, want %q", why, reason)
730 // cleanup cleans up a test that runs testgo.
731 func (tg *testgoData) cleanup() {
734 if err := os.Chdir(tg.wd); err != nil {
735 // We are unlikely to be able to continue.
736 fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err)
740 for _, path := range tg.temps {
741 tg.check(os.RemoveAll(path))
743 if tg.tempdir != "" {
744 tg.check(os.RemoveAll(tg.tempdir))
748 // failSSH puts an ssh executable in the PATH that always fails.
749 // This is to stub out uses of ssh by go get.
750 func (tg *testgoData) failSSH() {
752 wd, err := os.Getwd()
756 fail := filepath.Join(wd, "testdata/failssh")
757 tg.setenv("PATH", fmt.Sprintf("%v%c%v", fail, filepath.ListSeparator, os.Getenv("PATH")))
760 func TestBuildComplex(t *testing.T) {
761 // Simple smoke test for build configuration.
765 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
766 tg.run("build", "-x", "-o", os.DevNull, "complex")
768 if _, err := exec.LookPath("gccgo"); err == nil {
769 t.Skip("golang.org/issue/22472")
770 tg.run("build", "-x", "-o", os.DevNull, "-compiler=gccgo", "complex")
774 func TestFileLineInErrorMessages(t *testing.T) {
778 tg.tempFile("err.go", `package main; import "bar"`)
779 path := tg.path("err.go")
780 tg.runFail("run", path)
782 if rel, err := filepath.Rel(tg.pwd(), path); err == nil && len(rel) < len(path) {
785 tg.grepStderr("^"+regexp.QuoteMeta(shortPath)+":", "missing file:line in error message")
788 func TestProgramNameInCrashMessages(t *testing.T) {
792 tg.tempFile("triv.go", `package main; func main() {}`)
793 tg.runFail("build", "-ldflags", "-crash_for_testing", tg.path("triv.go"))
794 tg.grepStderr(`[/\\]tool[/\\].*[/\\]link`, "missing linker name in error message")
797 func TestBrokenTestsWithoutTestFunctionsAllFail(t *testing.T) {
800 // TODO: tg.parallel()
801 tg.runFail("test", "./testdata/src/badtest/...")
802 tg.grepBothNot("^ok", "test passed unexpectedly")
803 tg.grepBoth("FAIL.*badtest/badexec", "test did not run everything")
804 tg.grepBoth("FAIL.*badtest/badsyntax", "test did not run everything")
805 tg.grepBoth("FAIL.*badtest/badvar", "test did not run everything")
808 func TestGoBuildDashAInDevBranch(t *testing.T) {
810 t.Skip("don't rebuild the standard library in short mode")
815 tg.run("install", "math") // should be up to date already but just in case
816 tg.setenv("TESTGO_IS_GO_RELEASE", "0")
817 tg.run("build", "-v", "-a", "math")
818 tg.grepStderr("runtime", "testgo build -a math in dev branch DID NOT build runtime, but should have")
820 // Everything is out of date. Rebuild to leave things in a better state.
821 tg.run("install", "std")
824 func TestGoBuildDashAInReleaseBranch(t *testing.T) {
826 t.Skip("don't rebuild the standard library in short mode")
831 tg.run("install", "math", "net/http") // should be up to date already but just in case
832 tg.setenv("TESTGO_IS_GO_RELEASE", "1")
833 tg.run("install", "-v", "-a", "math")
834 tg.grepStderr("runtime", "testgo build -a math in release branch DID NOT build runtime, but should have")
836 // Now runtime.a is updated (newer mtime), so everything would look stale if not for being a release.
837 tg.run("build", "-v", "net/http")
838 tg.grepStderrNot("strconv", "testgo build -v net/http in release branch with newer runtime.a DID build strconv but should not have")
839 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")
840 tg.grepStderrNot("net/http", "testgo build -v net/http in release branch with newer runtime.a DID build net/http but should not have")
842 // Everything is out of date. Rebuild to leave things in a better state.
843 tg.run("install", "std")
846 func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) {
848 t.Skip("don't rebuild the standard library in short mode")
854 addNL := func(name string) (restore func()) {
855 data, err := ioutil.ReadFile(name)
860 data = append(data, '\n')
861 if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil {
866 if err := ioutil.WriteFile(name, old, 0666); err != nil {
872 tg.tempFile("d1/src/p1/p1.go", `package p1`)
873 tg.setenv("GOPATH", tg.path("d1"))
874 tg.run("install", "-a", "p1")
875 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, before any changes")
877 // Changing mtime of runtime/internal/sys/sys.go
878 // should have no effect: only the content matters.
879 // In fact this should be true even outside a release branch.
880 sys := runtime.GOROOT() + "/src/runtime/internal/sys/sys.go"
882 restore := addNL(sys)
884 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after updating mtime of runtime/internal/sys/sys.go")
886 // But changing content of any file should have an effect.
887 // Previously zversion.go was the only one that mattered;
888 // now they all matter, so keep using sys.go.
891 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go")
893 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after changing back to old release")
895 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go again")
896 tg.run("install", "p1")
897 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with new release")
899 // Restore to "old" release.
901 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after restoring sys.go")
902 tg.run("install", "p1")
903 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release")
905 // Everything is out of date. Rebuild to leave things in a better state.
906 tg.run("install", "std")
909 func TestGoListStandard(t *testing.T) {
912 // TODO: tg.parallel()
913 tg.cd(runtime.GOROOT() + "/src")
914 tg.run("list", "-f", "{{if not .Standard}}{{.ImportPath}}{{end}}", "./...")
915 stdout := tg.getStdout()
916 for _, line := range strings.Split(stdout, "\n") {
917 if strings.HasPrefix(line, "_/") && strings.HasSuffix(line, "/src") {
918 // $GOROOT/src shows up if there are any .go files there.
925 t.Errorf("package in GOROOT not listed as standard: %v", line)
928 // Similarly, expanding std should include some of our vendored code.
929 tg.run("list", "std", "cmd")
930 tg.grepStdout("golang.org/x/net/http2/hpack", "list std cmd did not mention vendored hpack")
931 tg.grepStdout("golang.org/x/arch/x86/x86asm", "list std cmd did not mention vendored x86asm")
934 func TestGoInstallCleansUpAfterGoBuild(t *testing.T) {
937 // TODO: tg.parallel()
938 tg.tempFile("src/mycmd/main.go", `package main; func main(){}`)
939 tg.setenv("GOPATH", tg.path("."))
940 tg.cd(tg.path("src/mycmd"))
942 doesNotExist := func(file, msg string) {
943 if _, err := os.Stat(file); err == nil {
945 } else if !os.IsNotExist(err) {
946 t.Fatal(msg, "error:", err)
951 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary")
953 doesNotExist("mycmd"+exeSuffix, "testgo install did not remove command binary")
955 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (second time)")
956 // Running install with arguments does not remove the target,
957 // even in the same directory.
958 tg.run("install", "mycmd")
959 tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary when run in mycmd")
961 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (third time)")
962 // And especially not outside the directory.
964 if data, err := ioutil.ReadFile("src/mycmd/mycmd" + exeSuffix); err != nil {
965 t.Fatal("could not read file:", err)
967 if err := ioutil.WriteFile("mycmd"+exeSuffix, data, 0555); err != nil {
968 t.Fatal("could not write file:", err)
971 tg.run("install", "mycmd")
972 tg.wantExecutable("src/mycmd/mycmd"+exeSuffix, "testgo install mycmd removed command binary from its source dir when run outside mycmd")
973 tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary from current dir when run outside mycmd")
976 func TestGoInstallRebuildsStalePackagesInOtherGOPATH(t *testing.T) {
980 tg.tempFile("d1/src/p1/p1.go", `package p1
982 func F() { p2.F() }`)
983 tg.tempFile("d2/src/p2/p2.go", `package p2
985 sep := string(filepath.ListSeparator)
986 tg.setenv("GOPATH", tg.path("d1")+sep+tg.path("d2"))
987 tg.run("install", "-i", "p1")
988 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly")
989 tg.wantNotStale("p2", "", "./testgo list claims p2 is stale, incorrectly")
991 if f, err := os.OpenFile(tg.path("d2/src/p2/p2.go"), os.O_WRONLY|os.O_APPEND, 0); err != nil {
993 } else if _, err = f.WriteString(`func G() {}`); err != nil {
998 tg.wantStale("p2", "build ID mismatch", "./testgo list claims p2 is NOT stale, incorrectly")
999 tg.wantStale("p1", "stale dependency: p2", "./testgo list claims p1 is NOT stale, incorrectly")
1001 tg.run("install", "-i", "p1")
1002 tg.wantNotStale("p2", "", "./testgo list claims p2 is stale after reinstall, incorrectly")
1003 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after reinstall, incorrectly")
1006 func TestGoInstallDetectsRemovedFiles(t *testing.T) {
1010 tg.tempFile("src/mypkg/x.go", `package mypkg`)
1011 tg.tempFile("src/mypkg/y.go", `package mypkg`)
1012 tg.tempFile("src/mypkg/z.go", `// +build missingtag
1015 tg.setenv("GOPATH", tg.path("."))
1016 tg.run("install", "mypkg")
1017 tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale, incorrectly")
1018 // z.go was not part of the build; removing it is okay.
1019 tg.must(os.Remove(tg.path("src/mypkg/z.go")))
1020 tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale after removing z.go; should not be stale")
1021 // y.go was part of the package; removing it should be detected.
1022 tg.must(os.Remove(tg.path("src/mypkg/y.go")))
1023 tg.wantStale("mypkg", "build ID mismatch", "./testgo list mypkg claims mypkg is NOT stale after removing y.go; should be stale")
1026 func TestWildcardMatchesSyntaxErrorDirs(t *testing.T) {
1029 // TODO: tg.parallel()
1030 tg.tempFile("src/mypkg/x.go", `package mypkg`)
1031 tg.tempFile("src/mypkg/y.go", `pkg mypackage`)
1032 tg.setenv("GOPATH", tg.path("."))
1033 tg.cd(tg.path("src/mypkg"))
1034 tg.runFail("list", "./...")
1035 tg.runFail("build", "./...")
1036 tg.runFail("install", "./...")
1039 func TestGoListWithTags(t *testing.T) {
1042 tg.tempFile("src/mypkg/x.go", "// +build thetag\n\npackage mypkg\n")
1043 tg.setenv("GOPATH", tg.path("."))
1044 tg.cd(tg.path("./src"))
1045 tg.run("list", "-tags=thetag", "./my...")
1046 tg.grepStdout("mypkg", "did not find mypkg")
1049 func TestGoInstallErrorOnCrossCompileToBin(t *testing.T) {
1050 if testing.Short() {
1051 t.Skip("don't install into GOROOT in short mode")
1056 tg.tempFile("src/mycmd/x.go", `package main
1058 tg.setenv("GOPATH", tg.path("."))
1059 tg.cd(tg.path("src/mycmd"))
1061 tg.run("build", "mycmd")
1064 if runtime.GOARCH == "386" {
1067 tg.setenv("GOOS", "linux")
1068 tg.setenv("GOARCH", goarch)
1069 tg.run("install", "mycmd")
1070 tg.setenv("GOBIN", tg.path("."))
1071 tg.runFail("install", "mycmd")
1072 tg.run("install", "cmd/pack")
1075 func TestGoInstallDetectsRemovedFilesInPackageMain(t *testing.T) {
1079 tg.tempFile("src/mycmd/x.go", `package main
1081 tg.tempFile("src/mycmd/y.go", `package main`)
1082 tg.tempFile("src/mycmd/z.go", `// +build missingtag
1085 tg.setenv("GOPATH", tg.path("."))
1086 tg.run("install", "mycmd")
1087 tg.wantNotStale("mycmd", "", "./testgo list mypkg claims mycmd is stale, incorrectly")
1088 // z.go was not part of the build; removing it is okay.
1089 tg.must(os.Remove(tg.path("src/mycmd/z.go")))
1090 tg.wantNotStale("mycmd", "", "./testgo list mycmd claims mycmd is stale after removing z.go; should not be stale")
1091 // y.go was part of the package; removing it should be detected.
1092 tg.must(os.Remove(tg.path("src/mycmd/y.go")))
1093 tg.wantStale("mycmd", "build ID mismatch", "./testgo list mycmd claims mycmd is NOT stale after removing y.go; should be stale")
1096 func testLocalRun(tg *testgoData, exepath, local, match string) {
1098 out, err := exec.Command(exepath).Output()
1100 tg.t.Fatalf("error running %v: %v", exepath, err)
1102 if !regexp.MustCompile(match).Match(out) {
1103 tg.t.Log(string(out))
1104 tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local)
1108 func testLocalEasy(tg *testgoData, local string) {
1110 exepath := "./easy" + exeSuffix
1111 tg.creatingTemp(exepath)
1112 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go"))
1113 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1116 func testLocalEasySub(tg *testgoData, local string) {
1118 exepath := "./easysub" + exeSuffix
1119 tg.creatingTemp(exepath)
1120 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go"))
1121 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1124 func testLocalHard(tg *testgoData, local string) {
1126 exepath := "./hard" + exeSuffix
1127 tg.creatingTemp(exepath)
1128 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go"))
1129 testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`)
1132 func testLocalInstall(tg *testgoData, local string) {
1134 tg.runFail("install", filepath.Join("testdata", local, "easy.go"))
1137 func TestLocalImportsEasy(t *testing.T) {
1140 testLocalEasy(tg, "local")
1143 func TestLocalImportsEasySub(t *testing.T) {
1146 testLocalEasySub(tg, "local")
1149 func TestLocalImportsHard(t *testing.T) {
1152 testLocalHard(tg, "local")
1155 func TestLocalImportsGoInstallShouldFail(t *testing.T) {
1158 testLocalInstall(tg, "local")
1161 const badDirName = `#$%:, &()*;<=>?\^{}`
1163 func copyBad(tg *testgoData) {
1165 if runtime.GOOS == "windows" {
1166 tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName)
1169 tg.must(filepath.Walk("testdata/local",
1170 func(path string, info os.FileInfo, err error) error {
1178 data, err = ioutil.ReadFile(path)
1182 newpath := strings.Replace(path, "local", badDirName, 1)
1183 tg.tempFile(newpath, string(data))
1189 func TestBadImportsEasy(t *testing.T) {
1192 // TODO: tg.parallel()
1194 testLocalEasy(tg, badDirName)
1197 func TestBadImportsEasySub(t *testing.T) {
1201 testLocalEasySub(tg, badDirName)
1204 func TestBadImportsHard(t *testing.T) {
1208 testLocalHard(tg, badDirName)
1211 func TestBadImportsGoInstallShouldFail(t *testing.T) {
1215 testLocalInstall(tg, badDirName)
1218 func TestInternalPackagesInGOROOTAreRespected(t *testing.T) {
1221 tg.runFail("build", "-v", "./testdata/testinternal")
1222 tg.grepBoth(`testinternal(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrong error message for testdata/testinternal")
1225 func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) {
1228 tg.runFail("build", "-v", "./testdata/testinternal2")
1229 tg.grepBoth(`testinternal2(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrote error message for testdata/testinternal2")
1232 func TestRunInternal(t *testing.T) {
1235 dir := filepath.Join(tg.pwd(), "testdata")
1236 tg.setenv("GOPATH", dir)
1237 tg.run("run", filepath.Join(dir, "src/run/good.go"))
1238 tg.runFail("run", filepath.Join(dir, "src/run/bad.go"))
1239 tg.grepStderr(`testdata(\/|\\)src(\/|\\)run(\/|\\)bad\.go\:3\:8\: use of internal package not allowed`, "unexpected error for run/bad.go")
1242 func testMove(t *testing.T, vcs, url, base, config string) {
1243 testenv.MustHaveExternalNetwork(t)
1249 tg.setenv("GOPATH", tg.path("."))
1250 tg.run("get", "-d", url)
1251 tg.run("get", "-d", "-u", url)
1254 // SVN doesn't believe in text files so we can't just edit the config.
1255 // Check out a different repo into the wrong place.
1256 tg.must(os.RemoveAll(tg.path("src/code.google.com/p/rsc-svn")))
1257 tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk")
1258 tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn")))
1260 path := tg.path(filepath.Join("src", config))
1261 data, err := ioutil.ReadFile(path)
1263 data = bytes.Replace(data, []byte(base), []byte(base+"XXX"), -1)
1264 tg.must(ioutil.WriteFile(path, data, 0644))
1267 // git will ask for a username and password when we
1268 // run go get -d -f -u. An empty username and
1269 // password will work. Prevent asking by setting
1271 tg.creatingTemp("sink" + exeSuffix)
1272 tg.tempFile("src/sink/sink.go", `package main; func main() {}`)
1273 tg.run("build", "-o", "sink"+exeSuffix, "sink")
1274 tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix))
1276 tg.runFail("get", "-d", "-u", url)
1277 tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason")
1278 tg.runFail("get", "-d", "-f", "-u", url)
1279 tg.grepStderr("validating server certificate|[nN]ot [fF]ound", "go get -d -f -u "+url+" failed for wrong reason")
1282 func TestInternalPackageErrorsAreHandled(t *testing.T) {
1285 tg.run("list", "./testdata/testinternal3")
1288 func TestInternalCache(t *testing.T) {
1291 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4"))
1292 tg.runFail("build", "p")
1293 tg.grepStderr("internal", "did not fail to build p")
1296 func TestMoveGit(t *testing.T) {
1297 testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config")
1300 func TestMoveHG(t *testing.T) {
1301 testMove(t, "hg", "vcs-test.golang.org/go/custom-hg-hello", "custom-hg-hello", "vcs-test.golang.org/go/custom-hg-hello/.hg/hgrc")
1304 // TODO(rsc): Set up a test case on SourceForge (?) for svn.
1305 // func testMoveSVN(t *testing.T) {
1306 // testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-")
1309 func TestImportCommandMatch(t *testing.T) {
1312 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1313 tg.run("build", "./testdata/importcom/works.go")
1316 func TestImportCommentMismatch(t *testing.T) {
1319 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1320 tg.runFail("build", "./testdata/importcom/wrongplace.go")
1321 tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import")
1324 func TestImportCommentSyntaxError(t *testing.T) {
1327 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1328 tg.runFail("build", "./testdata/importcom/bad.go")
1329 tg.grepStderr("cannot parse import comment", "go build did not mention syntax error")
1332 func TestImportCommentConflict(t *testing.T) {
1335 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1336 tg.runFail("build", "./testdata/importcom/conflict.go")
1337 tg.grepStderr("found import comments", "go build did not mention comment conflict")
1340 // cmd/go: custom import path checking should not apply to Go packages without import comment.
1341 func TestIssue10952(t *testing.T) {
1342 testenv.MustHaveExternalNetwork(t)
1343 if _, err := exec.LookPath("git"); err != nil {
1344 t.Skip("skipping because git binary not found")
1351 tg.setenv("GOPATH", tg.path("."))
1352 const importPath = "github.com/zombiezen/go-get-issue-10952"
1353 tg.run("get", "-d", "-u", importPath)
1354 repoDir := tg.path("src/" + importPath)
1355 tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git")
1356 tg.run("get", "-d", "-u", importPath)
1359 func TestIssue16471(t *testing.T) {
1360 testenv.MustHaveExternalNetwork(t)
1361 if _, err := exec.LookPath("git"); err != nil {
1362 t.Skip("skipping because git binary not found")
1369 tg.setenv("GOPATH", tg.path("."))
1370 tg.must(os.MkdirAll(tg.path("src/rsc.io/go-get-issue-10952"), 0755))
1371 tg.runGit(tg.path("src/rsc.io"), "clone", "https://github.com/zombiezen/go-get-issue-10952")
1372 tg.runFail("get", "-u", "rsc.io/go-get-issue-10952")
1373 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")
1376 // Test git clone URL that uses SCP-like syntax and custom import path checking.
1377 func TestIssue11457(t *testing.T) {
1378 testenv.MustHaveExternalNetwork(t)
1379 if _, err := exec.LookPath("git"); err != nil {
1380 t.Skip("skipping because git binary not found")
1387 tg.setenv("GOPATH", tg.path("."))
1388 const importPath = "rsc.io/go-get-issue-11457"
1389 tg.run("get", "-d", "-u", importPath)
1390 repoDir := tg.path("src/" + importPath)
1391 tg.runGit(repoDir, "remote", "set-url", "origin", "git@github.com:rsc/go-get-issue-11457")
1393 // At this time, custom import path checking compares remotes verbatim (rather than
1394 // just the host and path, skipping scheme and user), so we expect go get -u to fail.
1395 // However, the goal of this test is to verify that gitRemoteRepo correctly parsed
1396 // the SCP-like syntax, and we expect it to appear in the error message.
1397 tg.runFail("get", "-d", "-u", importPath)
1398 want := " is checked out from ssh://git@github.com/rsc/go-get-issue-11457"
1399 if !strings.HasSuffix(strings.TrimSpace(tg.getStderr()), want) {
1400 t.Error("expected clone URL to appear in stderr")
1404 func TestGetGitDefaultBranch(t *testing.T) {
1405 testenv.MustHaveExternalNetwork(t)
1406 if _, err := exec.LookPath("git"); err != nil {
1407 t.Skip("skipping because git binary not found")
1414 tg.setenv("GOPATH", tg.path("."))
1416 // This repo has two branches, master and another-branch.
1417 // The another-branch is the default that you get from 'git clone'.
1418 // The go get command variants should not override this.
1419 const importPath = "github.com/rsc/go-get-default-branch"
1421 tg.run("get", "-d", importPath)
1422 repoDir := tg.path("src/" + importPath)
1423 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1424 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1426 tg.run("get", "-d", "-u", importPath)
1427 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1428 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1431 func TestAccidentalGitCheckout(t *testing.T) {
1432 testenv.MustHaveExternalNetwork(t)
1433 if _, err := exec.LookPath("git"); err != nil {
1434 t.Skip("skipping because git binary not found")
1441 tg.setenv("GOPATH", tg.path("."))
1443 tg.runFail("get", "-u", "vcs-test.golang.org/go/test1-svn-git")
1444 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1446 tg.runFail("get", "-u", "vcs-test.golang.org/go/test2-svn-git/test2main")
1447 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1450 func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) {
1453 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1454 tg.runFail("test", "syntaxerror")
1455 tg.grepStderr("FAIL", "go test did not say FAIL")
1458 func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) {
1461 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1462 tg.runFail("list", "...")
1463 tg.grepBoth("badpkg", "go list ... failure does not mention badpkg")
1464 tg.run("list", "m...")
1467 func TestRelativeImportsGoTest(t *testing.T) {
1470 tg.run("test", "./testdata/testimport")
1473 func TestRelativeImportsGoTestDashI(t *testing.T) {
1477 // don't let test -i overwrite runtime
1478 tg.wantNotStale("runtime", "", "must be non-stale before test -i")
1480 tg.run("test", "-i", "./testdata/testimport")
1483 func TestRelativeImportsInCommandLinePackage(t *testing.T) {
1486 // TODO: tg.parallel()
1487 files, err := filepath.Glob("./testdata/testimport/*.go")
1489 tg.run(append([]string{"test"}, files...)...)
1492 func TestNonCanonicalImportPaths(t *testing.T) {
1496 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1497 tg.runFail("build", "canonical/d")
1498 tg.grepStderr("package canonical/d", "did not report canonical/d")
1499 tg.grepStderr("imports canonical/b", "did not report canonical/b")
1500 tg.grepStderr("imports canonical/a/: non-canonical", "did not report canonical/a/")
1503 func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) {
1506 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1"))
1507 tg.runFail("get", "-u", "foo")
1509 // TODO(iant): We should not have to use strconv.Quote here.
1510 // The code in vcs.go should be changed so that it is not required.
1511 quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo"))
1512 quoted = quoted[1 : len(quoted)-1]
1514 tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo")
1517 func TestInstallFailsWithNoBuildableFiles(t *testing.T) {
1520 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1521 tg.setenv("CGO_ENABLED", "0")
1522 tg.runFail("install", "cgotest")
1523 tg.grepStderr("build constraints exclude all Go files", "go install cgotest did not report 'build constraints exclude all Go files'")
1527 func TestMSanAndRaceRequireCgo(t *testing.T) {
1528 if !canMSan && !canRace {
1529 t.Skip("skipping because both msan and the race detector are not supported")
1534 tg.tempFile("triv.go", `package main; func main() {}`)
1535 tg.setenv("CGO_ENABLED", "0")
1537 tg.runFail("install", "-race", "triv.go")
1538 tg.grepStderr("-race requires cgo", "did not correctly report that -race requires cgo")
1539 tg.grepStderrNot("-msan", "reported that -msan instead of -race requires cgo")
1542 tg.runFail("install", "-msan", "triv.go")
1543 tg.grepStderr("-msan requires cgo", "did not correctly report that -msan requires cgo")
1544 tg.grepStderrNot("-race", "reported that -race instead of -msan requires cgo")
1548 func TestRelativeGOBINFail(t *testing.T) {
1551 tg.tempFile("triv.go", `package main; func main() {}`)
1552 tg.setenv("GOBIN", ".")
1553 tg.runFail("install")
1554 tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path")
1557 // Test that without $GOBIN set, binaries get installed
1558 // into the GOPATH bin directory.
1559 func TestInstallIntoGOPATH(t *testing.T) {
1562 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1563 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1564 tg.run("install", "go-cmd-test")
1565 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1569 func TestBuildOutputToDevNull(t *testing.T) {
1572 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1573 tg.run("build", "-o", os.DevNull, "go-cmd-test")
1576 func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) {
1580 gobin := filepath.Join(tg.pwd(), "testdata", "bin")
1581 tg.creatingTemp(gobin)
1582 tg.setenv("GOBIN", gobin)
1583 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1584 tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now()))
1586 tg.run("test", "main_test")
1587 tg.run("install", "main_test")
1588 tg.wantNotStale("main_test", "", "after go install, main listed as stale")
1589 tg.run("test", "main_test")
1592 // The runtime version string takes one of two forms:
1593 // "go1.X[.Y]" for Go releases, and "devel +hash" at tip.
1594 // Determine whether we are in a released copy by
1595 // inspecting the version.
1596 var isGoRelease = strings.HasPrefix(runtime.Version(), "go1")
1599 func TestPackageNotStaleWithTrailingSlash(t *testing.T) {
1603 // Make sure the packages below are not stale.
1604 tg.wantNotStale("runtime", "", "must be non-stale before test runs")
1605 tg.wantNotStale("os", "", "must be non-stale before test runs")
1606 tg.wantNotStale("io", "", "must be non-stale before test runs")
1608 goroot := runtime.GOROOT()
1609 tg.setenv("GOROOT", goroot+"/")
1611 tg.wantNotStale("runtime", "", "with trailing slash in GOROOT, runtime listed as stale")
1612 tg.wantNotStale("os", "", "with trailing slash in GOROOT, os listed as stale")
1613 tg.wantNotStale("io", "", "with trailing slash in GOROOT, io listed as stale")
1616 // With $GOBIN set, binaries get installed to $GOBIN.
1617 func TestInstallIntoGOBIN(t *testing.T) {
1620 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1621 tg.creatingTemp(gobin)
1622 tg.setenv("GOBIN", gobin)
1623 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1624 tg.run("install", "go-cmd-test")
1625 tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test")
1629 func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) {
1632 pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test")
1633 tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix))
1634 tg.setenv("GOBIN", pkg)
1635 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1638 tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory")
1641 // Without $GOBIN set, installing a program outside $GOPATH should fail
1642 // (there is nowhere to install it).
1643 func TestInstallWithoutDestinationFails(t *testing.T) {
1646 tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go")
1647 tg.grepStderr("no install location for .go files listed on command line", "wrong error")
1650 // With $GOBIN set, should install there.
1651 func TestInstallToGOBINCommandLinePackage(t *testing.T) {
1654 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1655 tg.creatingTemp(gobin)
1656 tg.setenv("GOBIN", gobin)
1657 tg.run("install", "testdata/src/go-cmd-test/helloworld.go")
1658 tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld")
1661 func TestGoGetNonPkg(t *testing.T) {
1662 testenv.MustHaveExternalNetwork(t)
1667 tg.setenv("GOPATH", tg.path("."))
1668 tg.setenv("GOBIN", tg.path("gobin"))
1669 tg.runFail("get", "-d", "golang.org/x/tools")
1670 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1671 tg.runFail("get", "-d", "-u", "golang.org/x/tools")
1672 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1673 tg.runFail("get", "-d", "golang.org/x/tools")
1674 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1677 func TestGoGetTestOnlyPkg(t *testing.T) {
1678 testenv.MustHaveExternalNetwork(t)
1682 tg.tempDir("gopath")
1683 tg.setenv("GOPATH", tg.path("gopath"))
1684 tg.run("get", "golang.org/x/tour/content")
1685 tg.run("get", "-t", "golang.org/x/tour/content")
1688 func TestInstalls(t *testing.T) {
1689 if testing.Short() {
1690 t.Skip("don't install into GOROOT in short mode")
1697 tg.setenv("GOPATH", tg.path("."))
1698 goroot := runtime.GOROOT()
1699 tg.setenv("GOROOT", goroot)
1701 // cmd/fix installs into tool
1702 tg.run("env", "GOOS")
1703 goos := strings.TrimSpace(tg.getStdout())
1704 tg.setenv("GOOS", goos)
1705 tg.run("env", "GOARCH")
1706 goarch := strings.TrimSpace(tg.getStdout())
1707 tg.setenv("GOARCH", goarch)
1708 fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix
1709 tg.must(os.RemoveAll(fixbin))
1710 tg.run("install", "cmd/fix")
1711 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool")
1712 tg.must(os.Remove(fixbin))
1713 tg.setenv("GOBIN", tg.path("gobin"))
1714 tg.run("install", "cmd/fix")
1715 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set")
1716 tg.unsetenv("GOBIN")
1718 // gopath program installs into GOBIN
1719 tg.tempFile("src/progname/p.go", `package main; func main() {}`)
1720 tg.setenv("GOBIN", tg.path("gobin"))
1721 tg.run("install", "progname")
1722 tg.unsetenv("GOBIN")
1723 tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname")
1725 // gopath program installs into GOPATH/bin
1726 tg.run("install", "progname")
1727 tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname")
1730 func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) {
1733 tg.setenv("GOPATH", ".")
1734 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1735 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1738 func TestRejectRelativePathsInGOPATH(t *testing.T) {
1741 sep := string(filepath.ListSeparator)
1742 tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".")
1743 tg.runFail("build", "go-cmd-test")
1744 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1747 func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) {
1750 tg.setenv("GOPATH", "testdata")
1751 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1752 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1756 func TestRejectBlankPathsInGOPATH(t *testing.T) {
1759 sep := string(filepath.ListSeparator)
1760 tg.setenv("GOPATH", " "+sep+filepath.Join(tg.pwd(), "testdata"))
1761 tg.runFail("build", "go-cmd-test")
1762 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1766 func TestIgnoreEmptyPathsInGOPATH(t *testing.T) {
1769 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1770 sep := string(filepath.ListSeparator)
1771 tg.setenv("GOPATH", ""+sep+filepath.Join(tg.pwd(), "testdata"))
1772 tg.run("install", "go-cmd-test")
1773 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1777 func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
1781 tg.run("test", "errors", "errors", "errors", "errors", "errors")
1782 if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") {
1783 t.Error("go test errors errors errors errors errors tested the same package multiple times")
1787 func TestGoListHasAConsistentOrder(t *testing.T) {
1791 tg.run("list", "std")
1792 first := tg.getStdout()
1793 tg.run("list", "std")
1794 if first != tg.getStdout() {
1795 t.Error("go list std ordering is inconsistent")
1799 func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
1803 tg.run("list", "std")
1804 tg.grepStdoutNot("cmd/", "go list std shows commands")
1807 func TestGoListCmdOnlyShowsCommands(t *testing.T) {
1811 tg.run("list", "cmd")
1812 out := strings.TrimSpace(tg.getStdout())
1813 for _, line := range strings.Split(out, "\n") {
1814 if !strings.Contains(line, "cmd/") {
1815 t.Error("go list cmd shows non-commands")
1821 func TestGoListDedupsPackages(t *testing.T) {
1824 // TODO: tg.parallel()
1825 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1826 tg.run("list", "xtestonly", "./testdata/src/xtestonly/...")
1827 got := strings.TrimSpace(tg.getStdout())
1828 const want = "xtestonly"
1830 t.Errorf("got %q; want %q", got, want)
1834 func TestGoListDeps(t *testing.T) {
1838 tg.tempDir("src/p1/p2/p3/p4")
1839 tg.setenv("GOPATH", tg.path("."))
1840 tg.tempFile("src/p1/p.go", "package p1\nimport _ \"p1/p2\"\n")
1841 tg.tempFile("src/p1/p2/p.go", "package p2\nimport _ \"p1/p2/p3\"\n")
1842 tg.tempFile("src/p1/p2/p3/p.go", "package p3\nimport _ \"p1/p2/p3/p4\"\n")
1843 tg.tempFile("src/p1/p2/p3/p4/p.go", "package p4\n")
1844 tg.run("list", "-f", "{{.Deps}}", "p1")
1845 tg.grepStdout("p1/p2/p3/p4", "Deps(p1) does not mention p4")
1848 // Issue 4096. Validate the output of unsuccessful go install foo/quxx.
1849 func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) {
1853 tg.runFail("install", "foo/quxx")
1854 if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 {
1855 t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`)
1859 func TestGOROOTSearchFailureReporting(t *testing.T) {
1863 tg.runFail("install", "foo/quxx")
1864 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 {
1865 t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`)
1869 func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) {
1873 sep := string(filepath.ListSeparator)
1874 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1875 tg.runFail("install", "foo/quxx")
1876 if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 {
1877 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`)
1881 // Test (from $GOPATH) annotation is reported for the first GOPATH entry,
1882 func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) {
1886 sep := string(filepath.ListSeparator)
1887 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1888 tg.runFail("install", "foo/quxx")
1889 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 {
1890 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`)
1894 // but not on the second.
1895 func TestMentionGOPATHNotOnSecondEntry(t *testing.T) {
1899 sep := string(filepath.ListSeparator)
1900 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1901 tg.runFail("install", "foo/quxx")
1902 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 {
1903 t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`)
1907 func homeEnvName() string {
1908 switch runtime.GOOS {
1910 return "USERPROFILE"
1918 func TestDefaultGOPATH(t *testing.T) {
1922 tg.tempDir("home/go")
1923 tg.setenv(homeEnvName(), tg.path("home"))
1925 tg.run("env", "GOPATH")
1926 tg.grepStdout(regexp.QuoteMeta(tg.path("home/go")), "want GOPATH=$HOME/go")
1928 tg.setenv("GOROOT", tg.path("home/go"))
1929 tg.run("env", "GOPATH")
1930 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go")
1932 tg.setenv("GOROOT", tg.path("home/go")+"/")
1933 tg.run("env", "GOPATH")
1934 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go/")
1937 func TestDefaultGOPATHGet(t *testing.T) {
1938 testenv.MustHaveExternalNetwork(t)
1942 tg.setenv("GOPATH", "")
1944 tg.setenv(homeEnvName(), tg.path("home"))
1946 // warn for creating directory
1947 tg.run("get", "-v", "github.com/golang/example/hello")
1948 tg.grepStderr("created GOPATH="+regexp.QuoteMeta(tg.path("home/go"))+"; see 'go help gopath'", "did not create GOPATH")
1950 // no warning if directory already exists
1951 tg.must(os.RemoveAll(tg.path("home/go")))
1952 tg.tempDir("home/go")
1953 tg.run("get", "github.com/golang/example/hello")
1954 tg.grepStderrNot(".", "expected no output on standard error")
1956 // error if $HOME/go is a file
1957 tg.must(os.RemoveAll(tg.path("home/go")))
1958 tg.tempFile("home/go", "")
1959 tg.runFail("get", "github.com/golang/example/hello")
1960 tg.grepStderr(`mkdir .*[/\\]go: .*(not a directory|cannot find the path)`, "expected error because $HOME/go is a file")
1963 func TestDefaultGOPATHPrintedSearchList(t *testing.T) {
1966 tg.setenv("GOPATH", "")
1968 tg.setenv(homeEnvName(), tg.path("home"))
1970 tg.runFail("install", "github.com/golang/example/hello")
1971 tg.grepStderr(regexp.QuoteMeta(tg.path("home/go/src/github.com/golang/example/hello"))+`.*from \$GOPATH`, "expected default GOPATH")
1974 // Issue 4186. go get cannot be used to download packages to $GOROOT.
1975 // Test that without GOPATH set, go get should fail.
1976 func TestGoGetIntoGOROOT(t *testing.T) {
1977 testenv.MustHaveExternalNetwork(t)
1984 // Fails because GOROOT=GOPATH
1985 tg.setenv("GOPATH", tg.path("."))
1986 tg.setenv("GOROOT", tg.path("."))
1987 tg.runFail("get", "-d", "github.com/golang/example/hello")
1988 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
1989 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
1991 // Fails because GOROOT=GOPATH after cleaning.
1992 tg.setenv("GOPATH", tg.path(".")+"/")
1993 tg.setenv("GOROOT", tg.path("."))
1994 tg.runFail("get", "-d", "github.com/golang/example/hello")
1995 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
1996 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
1998 tg.setenv("GOPATH", tg.path("."))
1999 tg.setenv("GOROOT", tg.path(".")+"/")
2000 tg.runFail("get", "-d", "github.com/golang/example/hello")
2001 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2002 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2004 // Fails because GOROOT=$HOME/go so default GOPATH unset.
2005 tg.tempDir("home/go")
2006 tg.setenv(homeEnvName(), tg.path("home"))
2007 tg.setenv("GOPATH", "")
2008 tg.setenv("GOROOT", tg.path("home/go"))
2009 tg.runFail("get", "-d", "github.com/golang/example/hello")
2010 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2012 tg.setenv(homeEnvName(), tg.path("home")+"/")
2013 tg.setenv("GOPATH", "")
2014 tg.setenv("GOROOT", tg.path("home/go"))
2015 tg.runFail("get", "-d", "github.com/golang/example/hello")
2016 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2018 tg.setenv(homeEnvName(), tg.path("home"))
2019 tg.setenv("GOPATH", "")
2020 tg.setenv("GOROOT", tg.path("home/go")+"/")
2021 tg.runFail("get", "-d", "github.com/golang/example/hello")
2022 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2025 func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) {
2029 tg.tempFile("main.go", `package main
2034 tg.run("run", "-ldflags", `-X "main.extern=hello world"`, tg.path("main.go"))
2035 tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`)
2038 func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) {
2041 // TODO: tg.parallel()
2044 tg.run("test", "-cpuprofile", "errors.prof", "errors")
2045 tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test")
2048 func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) {
2051 // TODO: tg.parallel()
2054 tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2055 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test")
2058 func TestGoTestMutexprofileLeavesBinaryBehind(t *testing.T) {
2061 // TODO: tg.parallel()
2064 tg.run("test", "-mutexprofile", "errors.prof", "errors")
2065 tg.wantExecutable("errors.test"+exeSuffix, "go test -mutexprofile did not create errors.test")
2068 func TestGoTestMutexprofileDashOControlsBinaryLocation(t *testing.T) {
2071 // TODO: tg.parallel()
2074 tg.run("test", "-mutexprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2075 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -mutexprofile -o myerrors.test did not create myerrors.test")
2078 func TestGoBuildNonMain(t *testing.T) {
2081 // TODO: tg.parallel()
2082 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2083 tg.runFail("build", "-buildmode=exe", "-o", "not_main"+exeSuffix, "not_main")
2084 tg.grepStderr("-buildmode=exe requires exactly one main package", "go build with -o and -buildmode=exe should on a non-main package should throw an error")
2085 tg.mustNotExist("not_main" + exeSuffix)
2088 func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) {
2093 tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2094 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test")
2097 func TestGoTestDashOWritesBinary(t *testing.T) {
2102 tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2103 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2106 func TestGoTestDashIDashOWritesBinary(t *testing.T) {
2112 // don't let test -i overwrite runtime
2113 tg.wantNotStale("runtime", "", "must be non-stale before test -i")
2115 tg.run("test", "-v", "-i", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2116 tg.grepBothNot("PASS|FAIL", "test should not have run")
2117 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2121 func TestSymlinksList(t *testing.T) {
2122 testenv.MustHaveSymlink(t)
2126 // TODO: tg.parallel()
2128 tg.must(os.Symlink(tg.path("."), tg.path("src/dir1")))
2129 tg.tempFile("src/dir1/p.go", "package p")
2130 tg.setenv("GOPATH", tg.path("."))
2131 tg.cd(tg.path("src"))
2132 tg.run("list", "-f", "{{.Root}}", "dir1")
2133 if strings.TrimSpace(tg.getStdout()) != tg.path(".") {
2134 t.Error("confused by symlinks")
2139 func TestSymlinksVendor(t *testing.T) {
2140 testenv.MustHaveSymlink(t)
2144 // TODO: tg.parallel()
2145 tg.tempDir("gopath/src/dir1/vendor/v")
2146 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}")
2147 tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v")
2148 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2149 tg.setenv("GOPATH", tg.path("gopath"))
2150 tg.cd(tg.path("symdir1"))
2151 tg.run("list", "-f", "{{.Root}}", ".")
2152 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2153 t.Error("list confused by symlinks")
2156 // All of these should succeed, not die in vendor-handling code.
2157 tg.run("run", "p.go")
2163 func TestSymlinksVendor15201(t *testing.T) {
2164 testenv.MustHaveSymlink(t)
2169 tg.tempDir("gopath/src/x/y/_vendor/src/x")
2170 tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y")))
2171 tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n")
2172 tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor")))
2173 tg.tempFile("gopath/src/x/y/z/z.go", "package z\n")
2175 tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath"))
2176 tg.cd(tg.path("gopath/src"))
2177 tg.run("list", "./...")
2180 func TestSymlinksInternal(t *testing.T) {
2181 testenv.MustHaveSymlink(t)
2185 tg.tempDir("gopath/src/dir1/internal/v")
2186 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}")
2187 tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v")
2188 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2189 tg.setenv("GOPATH", tg.path("gopath"))
2190 tg.cd(tg.path("symdir1"))
2191 tg.run("list", "-f", "{{.Root}}", ".")
2192 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2193 t.Error("list confused by symlinks")
2196 // All of these should succeed, not die in internal-handling code.
2197 tg.run("run", "p.go")
2203 func TestInstallWithTags(t *testing.T) {
2208 tg.tempFile("src/example/a/main.go", `package main
2210 tg.tempFile("src/example/b/main.go", `// +build mytag
2214 tg.setenv("GOPATH", tg.path("."))
2215 tg.run("install", "-tags", "mytag", "example/a", "example/b")
2216 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries")
2217 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries")
2218 tg.must(os.Remove(tg.path("bin/a" + exeSuffix)))
2219 tg.must(os.Remove(tg.path("bin/b" + exeSuffix)))
2220 tg.run("install", "-tags", "mytag", "example/...")
2221 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries")
2222 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries")
2223 tg.run("list", "-tags", "mytag", "example/b...")
2224 if strings.TrimSpace(tg.getStdout()) != "example/b" {
2225 t.Error("go list example/b did not find example/b")
2230 func TestCaseCollisions(t *testing.T) {
2234 tg.tempDir("src/example/a/pkg")
2235 tg.tempDir("src/example/a/Pkg")
2236 tg.tempDir("src/example/b")
2237 tg.setenv("GOPATH", tg.path("."))
2238 tg.tempFile("src/example/a/a.go", `package p
2243 tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`)
2244 tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`)
2245 tg.run("list", "-json", "example/a")
2246 tg.grepStdout("case-insensitive import collision", "go list -json example/a did not report import collision")
2247 tg.runFail("build", "example/a")
2248 tg.grepStderr("case-insensitive import collision", "go build example/a did not report import collision")
2249 tg.tempFile("src/example/b/file.go", `package b`)
2250 tg.tempFile("src/example/b/FILE.go", `package b`)
2251 f, err := os.Open(tg.path("src/example/b"))
2253 names, err := f.Readdirnames(0)
2256 args := []string{"list"}
2257 if len(names) == 2 {
2258 // case-sensitive file system, let directory read find both files
2259 args = append(args, "example/b")
2261 // case-insensitive file system, list files explicitly on command line
2262 args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go"))
2265 tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision")
2267 tg.runFail("list", "example/a/pkg", "example/a/Pkg")
2268 tg.grepStderr("case-insensitive import collision", "go list example/a/pkg example/a/Pkg did not report import collision")
2269 tg.run("list", "-json", "-e", "example/a/pkg", "example/a/Pkg")
2270 tg.grepStdout("case-insensitive import collision", "go list -json -e example/a/pkg example/a/Pkg did not report import collision")
2271 tg.runFail("build", "example/a/pkg", "example/a/Pkg")
2272 tg.grepStderr("case-insensitive import collision", "go build example/a/pkg example/a/Pkg did not report import collision")
2275 // Issue 17451, 17662.
2276 func TestSymlinkWarning(t *testing.T) {
2281 tg.setenv("GOPATH", tg.path("."))
2283 tg.tempDir("src/example/xx")
2285 tg.tempFile("yy/zz/zz.go", "package zz\n")
2286 if err := os.Symlink(tg.path("yy"), tg.path("src/example/xx/yy")); err != nil {
2287 t.Skip("symlink failed: %v", err)
2289 tg.run("list", "example/xx/z...")
2290 tg.grepStdoutNot(".", "list should not have matched anything")
2291 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2292 tg.grepStderrNot("symlink", "list should not have reported symlink")
2294 tg.run("list", "example/xx/...")
2295 tg.grepStdoutNot(".", "list should not have matched anything")
2296 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2297 tg.grepStderr("ignoring symlink", "list should have reported symlink")
2301 func TestGoGetDashTIssue8181(t *testing.T) {
2302 testenv.MustHaveExternalNetwork(t)
2308 tg.setenv("GOPATH", tg.path("."))
2309 tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b")
2310 tg.run("list", "...")
2311 tg.grepStdout("x/build/gerrit", "missing expected x/build/gerrit")
2314 func TestIssue11307(t *testing.T) {
2315 // go get -u was not working except in checkout directory
2316 testenv.MustHaveExternalNetwork(t)
2322 tg.setenv("GOPATH", tg.path("."))
2323 tg.run("get", "github.com/rsc/go-get-issue-11307")
2324 tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing
2327 func TestShadowingLogic(t *testing.T) {
2331 sep := string(filepath.ListSeparator)
2332 tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2"))
2334 // The math in root1 is not "math" because the standard math is.
2335 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math")
2336 pwdForwardSlash := strings.Replace(pwd, string(os.PathSeparator), "/", -1)
2337 if !strings.HasPrefix(pwdForwardSlash, "/") {
2338 pwdForwardSlash = "/" + pwdForwardSlash
2340 // The output will have makeImportValid applies, but we only
2341 // bother to deal with characters we might reasonably see.
2342 for _, r := range " :" {
2343 pwdForwardSlash = strings.Replace(pwdForwardSlash, string(r), "_", -1)
2345 want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")"
2346 if strings.TrimSpace(tg.getStdout()) != want {
2347 t.Error("shadowed math is not shadowed; looking for", want)
2350 // The foo in root1 is "foo".
2351 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo")
2352 if strings.TrimSpace(tg.getStdout()) != "(foo) ()" {
2353 t.Error("unshadowed foo is shadowed")
2356 // The foo in root2 is not "foo" because the foo in root1 got there first.
2357 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo")
2358 want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")"
2359 if strings.TrimSpace(tg.getStdout()) != want {
2360 t.Error("shadowed foo is not shadowed; looking for", want)
2363 // The error for go install should mention the conflicting directory.
2364 tg.runFail("install", "./testdata/shadow/root2/src/foo")
2365 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")
2366 if strings.TrimSpace(tg.getStderr()) != want {
2367 t.Error("wrong shadowed install error; looking for", want)
2371 // Only succeeds if source order is preserved.
2372 func TestSourceFileNameOrderPreserved(t *testing.T) {
2375 tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go")
2378 // Check that coverage analysis works at all.
2379 // Don't worry about the exact numbers but require not 0.0%.
2380 func checkCoverage(tg *testgoData, data string) {
2382 if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) {
2383 tg.t.Error("some coverage results are 0.0%")
2387 func TestCoverageRuns(t *testing.T) {
2388 if testing.Short() {
2389 t.Skip("don't build libraries for coverage in short mode")
2393 tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp")
2394 data := tg.getStdout() + tg.getStderr()
2395 tg.run("test", "-short", "-cover", "strings", "math", "regexp")
2396 data += tg.getStdout() + tg.getStderr()
2397 checkCoverage(tg, data)
2400 // Check that coverage analysis uses set mode.
2401 // Also check that coverage profiles merge correctly.
2402 func TestCoverageUsesSetMode(t *testing.T) {
2403 if testing.Short() {
2404 t.Skip("don't build libraries for coverage in short mode")
2408 tg.creatingTemp("testdata/cover.out")
2409 tg.run("test", "-short", "-cover", "encoding/binary", "errors", "-coverprofile=testdata/cover.out")
2410 data := tg.getStdout() + tg.getStderr()
2411 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2414 if !bytes.Contains(out, []byte("mode: set")) {
2415 t.Error("missing mode: set")
2417 if !bytes.Contains(out, []byte("errors.go")) {
2418 t.Error("missing errors.go")
2420 if !bytes.Contains(out, []byte("binary.go")) {
2421 t.Error("missing binary.go")
2423 if bytes.Count(out, []byte("mode: set")) != 1 {
2424 t.Error("too many mode: set")
2427 checkCoverage(tg, data)
2430 func TestCoverageUsesAtomicModeForRace(t *testing.T) {
2431 if testing.Short() {
2432 t.Skip("don't build libraries for coverage in short mode")
2435 t.Skip("skipping because race detector not supported")
2440 tg.creatingTemp("testdata/cover.out")
2441 tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
2442 data := tg.getStdout() + tg.getStderr()
2443 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2446 if !bytes.Contains(out, []byte("mode: atomic")) {
2447 t.Error("missing mode: atomic")
2450 checkCoverage(tg, data)
2453 func TestCoverageSyncAtomicImport(t *testing.T) {
2457 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2458 tg.run("test", "-short", "-cover", "-covermode=atomic", "-coverpkg=coverdep/p1", "coverdep")
2461 func TestCoverageImportMainLoop(t *testing.T) {
2464 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2465 tg.runFail("test", "importmain/test")
2466 tg.grepStderr("not an importable package", "did not detect import main")
2467 tg.runFail("test", "-cover", "importmain/test")
2468 tg.grepStderr("not an importable package", "did not detect import main")
2471 func TestCoveragePattern(t *testing.T) {
2476 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2478 // If coverpkg=sleepy... expands by package loading
2479 // (as opposed to pattern matching on deps)
2480 // then it will try to load sleepybad, which does not compile,
2481 // and the test command will fail.
2482 tg.run("test", "-coverprofile="+filepath.Join(tg.tempdir, "cover.out"), "-coverpkg=sleepy...", "-run=^$", "sleepy1")
2485 func TestCoverageErrorLine(t *testing.T) {
2490 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2491 tg.setenv("GOTMPDIR", tg.tempdir)
2493 tg.runFail("test", "coverbad")
2494 tg.grepStderr(`coverbad[\\/]p\.go:4`, "did not find coverbad/p.go:4")
2496 tg.grepStderr(`coverbad[\\/]p1\.go:6`, "did not find coverbad/p1.go:6")
2498 tg.grepStderrNot(regexp.QuoteMeta(tg.tempdir), "found temporary directory in error")
2499 stderr := tg.getStderr()
2501 tg.runFail("test", "-cover", "coverbad")
2502 stderr2 := tg.getStderr()
2504 // It's OK that stderr2 drops the character position in the error,
2505 // because of the //line directive (see golang.org/issue/22662).
2506 stderr = strings.Replace(stderr, "p.go:4:2:", "p.go:4:", -1)
2507 if stderr != stderr2 {
2508 t.Logf("test -cover changed error messages:\nbefore:\n%s\n\nafter:\n%s", stderr, stderr2)
2509 t.Skip("golang.org/issue/22660")
2514 func TestTestBuildFailureOutput(t *testing.T) {
2518 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2520 // Doesn't build, -x output should not claim to run test.
2521 tg.runFail("test", "-x", "coverbad")
2522 tg.grepStderrNot(`[\\/]coverbad\.test( |$)`, "claimed to run test")
2525 func TestCoverageFunc(t *testing.T) {
2530 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2532 tg.run("test", "-outputdir="+tg.tempdir, "-coverprofile=cover.out", "coverasm")
2533 tg.run("tool", "cover", "-func="+filepath.Join(tg.tempdir, "cover.out"))
2534 tg.grepStdout(`\tg\t*100.0%`, "did not find g 100% covered")
2535 tg.grepStdoutNot(`\tf\t*[0-9]`, "reported coverage for assembly function f")
2538 func TestPluginNonMain(t *testing.T) {
2539 wd, err := os.Getwd()
2544 pkg := filepath.Join(wd, "testdata", "testdep", "p2")
2549 tg.runFail("build", "-buildmode=plugin", pkg)
2552 func TestTestEmpty(t *testing.T) {
2554 t.Skip("no race detector")
2558 testdata := filepath.Join(wd, "testdata")
2559 for _, dir := range []string{"pkg", "test", "xtest", "pkgtest", "pkgxtest", "pkgtestxtest", "testxtest"} {
2560 t.Run(dir, func(t *testing.T) {
2563 tg.setenv("GOPATH", testdata)
2564 tg.cd(filepath.Join(testdata, "src/empty/"+dir))
2565 tg.run("test", "-cover", "-coverpkg=.", "-race")
2567 if testing.Short() {
2573 func TestNoGoError(t *testing.T) {
2575 testdata := filepath.Join(wd, "testdata")
2576 for _, dir := range []string{"empty/test", "empty/xtest", "empty/testxtest", "exclude", "exclude/ignore", "exclude/empty"} {
2577 t.Run(dir, func(t *testing.T) {
2580 tg.setenv("GOPATH", testdata)
2581 tg.cd(filepath.Join(testdata, "src"))
2582 tg.runFail("build", "./"+dir)
2584 if strings.Contains(dir, "test") {
2585 want = "no non-test Go files in "
2586 } else if dir == "exclude" {
2587 want = "build constraints exclude all Go files in "
2589 want = "no Go files in "
2591 tg.grepStderr(want, "wrong reason for failure")
2596 func TestTestRaceInstall(t *testing.T) {
2598 t.Skip("no race detector")
2600 if testing.Short() && testenv.Builder() == "" {
2601 t.Skip("don't rebuild the standard library in short mode")
2606 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2609 pkgdir := tg.path("pkg")
2610 tg.run("install", "-race", "-pkgdir="+pkgdir, "std")
2611 tg.run("test", "-race", "-pkgdir="+pkgdir, "-i", "-v", "empty/pkg")
2612 if tg.getStderr() != "" {
2613 t.Error("go test -i -race: rebuilds cached packages")
2617 func TestBuildDryRunWithCgo(t *testing.T) {
2619 t.Skip("skipping because cgo not enabled")
2624 tg.tempFile("foo.go", `package main
2634 tg.run("build", "-n", tg.path("foo.go"))
2635 tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file")
2638 func TestCoverageWithCgo(t *testing.T) {
2640 t.Skip("skipping because cgo not enabled")
2643 for _, dir := range []string{"cgocover", "cgocover2", "cgocover3", "cgocover4"} {
2644 t.Run(dir, func(t *testing.T) {
2648 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2649 tg.run("test", "-short", "-cover", dir)
2650 data := tg.getStdout() + tg.getStderr()
2651 checkCoverage(tg, data)
2656 func TestCgoAsmError(t *testing.T) {
2658 t.Skip("skipping because cgo not enabled")
2664 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2665 tg.runFail("build", "cgoasm")
2666 tg.grepBoth("package using cgo has Go assembly file", "did not detect Go assembly file")
2669 func TestCgoDependsOnSyscall(t *testing.T) {
2670 if testing.Short() {
2671 t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode")
2674 t.Skip("skipping because cgo not enabled")
2677 t.Skip("skipping because race detector not supported")
2682 files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race"))
2684 for _, file := range files {
2685 tg.check(os.RemoveAll(file))
2687 tg.tempFile("src/foo/foo.go", `
2689 //#include <stdio.h>
2691 tg.setenv("GOPATH", tg.path("."))
2692 tg.run("build", "-race", "foo")
2695 func TestCgoShowsFullPathNames(t *testing.T) {
2697 t.Skip("skipping because cgo not enabled")
2703 tg.tempFile("src/x/y/dirname/foo.go", `
2707 tg.setenv("GOPATH", tg.path("."))
2708 tg.runFail("build", "x/y/dirname")
2709 tg.grepBoth("x/y/dirname", "error did not use full path")
2712 func TestCgoHandlesWlORIGIN(t *testing.T) {
2714 t.Skip("skipping because cgo not enabled")
2720 tg.tempFile("src/origin/origin.go", `package origin
2721 // #cgo !darwin LDFLAGS: -Wl,-rpath -Wl,$ORIGIN
2724 func f() { C.f() }`)
2725 tg.setenv("GOPATH", tg.path("."))
2726 tg.run("build", "origin")
2729 func TestCgoPkgConfig(t *testing.T) {
2731 t.Skip("skipping because cgo not enabled")
2737 tg.run("env", "PKG_CONFIG")
2738 pkgConfig := strings.TrimSpace(tg.getStdout())
2739 if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil {
2740 t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out)
2743 // OpenBSD's pkg-config is strict about whitespace and only
2744 // supports backslash-escaped whitespace. It does not support
2745 // quotes, which the normal freedesktop.org pkg-config does
2746 // support. See http://man.openbsd.org/pkg-config.1
2747 tg.tempFile("foo.pc", `
2749 Description: The foo library
2751 Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world
2753 tg.tempFile("foo.go", `package main
2756 #cgo pkg-config: foo
2758 return DEFINED_FROM_PKG_CONFIG;
2765 if C.value() != 42 {
2766 println("value() =", C.value(), "wanted 42")
2771 tg.setenv("PKG_CONFIG_PATH", tg.path("."))
2772 tg.run("run", tg.path("foo.go"))
2775 // "go test -c -test.bench=XXX errors" should not hang.
2776 // "go test -c" should also produce reproducible binaries.
2777 // "go test -c" should also appear to write a new binary every time,
2778 // even if it's really just updating the mtime on an existing up-to-date binary.
2779 func TestIssue6480(t *testing.T) {
2782 // TODO: tg.parallel()
2785 tg.run("test", "-c", "-test.bench=XXX", "errors")
2786 tg.run("test", "-c", "-o", "errors2.test", "errors")
2788 data1, err := ioutil.ReadFile("errors.test" + exeSuffix)
2790 data2, err := ioutil.ReadFile("errors2.test") // no exeSuffix because -o above doesn't have it
2792 if !bytes.Equal(data1, data2) {
2793 t.Fatalf("go test -c errors produced different binaries when run twice")
2797 tg.run("test", "-x", "-c", "-test.bench=XXX", "errors")
2798 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
2799 info, err := os.Stat("errors.test" + exeSuffix)
2803 start = truncateLike(start, info.ModTime())
2804 if info.ModTime().Before(start) {
2805 t.Fatalf("mtime of errors.test predates test -c command (%v < %v)", info.ModTime(), start)
2809 tg.run("test", "-x", "-c", "-o", "errors2.test", "errors")
2810 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
2811 info, err = os.Stat("errors2.test")
2815 start = truncateLike(start, info.ModTime())
2816 if info.ModTime().Before(start) {
2817 t.Fatalf("mtime of errors2.test predates test -c command (%v < %v)", info.ModTime(), start)
2821 // truncateLike returns the result of truncating t to the apparent precision of p.
2822 func truncateLike(t, p time.Time) time.Time {
2823 nano := p.UnixNano()
2824 d := 1 * time.Nanosecond
2825 for nano%int64(d) == 0 && d < 1*time.Second {
2828 for nano%int64(d) == 0 && d < 2*time.Second {
2831 return t.Truncate(d)
2834 // cmd/cgo: undefined reference when linking a C-library using gccgo
2835 func TestIssue7573(t *testing.T) {
2837 t.Skip("skipping because cgo not enabled")
2839 if _, err := exec.LookPath("gccgo"); err != nil {
2840 t.Skip("skipping because no gccgo compiler found")
2842 t.Skip("golang.org/issue/22472")
2847 tg.tempFile("src/cgoref/cgoref.go", `
2849 // #cgo LDFLAGS: -L alibpath -lalib
2853 func main() { C.f() }`)
2854 tg.setenv("GOPATH", tg.path("."))
2855 tg.run("build", "-n", "-compiler", "gccgo", "cgoref")
2856 tg.grepStderr(`gccgo.*\-L [^ ]*alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`)
2859 func TestListTemplateContextFunction(t *testing.T) {
2861 for _, tt := range []struct {
2865 {"GOARCH", runtime.GOARCH},
2866 {"GOOS", runtime.GOOS},
2867 {"GOROOT", filepath.Clean(runtime.GOROOT())},
2868 {"GOPATH", os.Getenv("GOPATH")},
2870 {"UseAllFiles", ""},
2873 {"ReleaseTags", ""},
2874 {"InstallSuffix", ""},
2877 t.Run(tt.v, func(t *testing.T) {
2881 tmpl := "{{context." + tt.v + "}}"
2882 tg.run("list", "-f", tmpl)
2886 if got := strings.TrimSpace(tg.getStdout()); got != tt.want {
2887 t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want)
2893 // cmd/go: "go test" should fail if package does not build
2894 func TestIssue7108(t *testing.T) {
2897 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2898 tg.runFail("test", "notest")
2901 // cmd/go: go test -a foo does not rebuild regexp.
2902 func TestIssue6844(t *testing.T) {
2903 if testing.Short() {
2904 t.Skip("don't rebuild the standard library in short mode")
2909 tg.creatingTemp("deps.test" + exeSuffix)
2910 tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go")
2911 tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp")
2914 func TestBuildDashIInstallsDependencies(t *testing.T) {
2918 tg.tempFile("src/x/y/foo/foo.go", `package foo
2920 tg.tempFile("src/x/y/bar/bar.go", `package bar
2922 func F() { foo.F() }`)
2923 tg.setenv("GOPATH", tg.path("."))
2925 // don't let build -i overwrite runtime
2926 tg.wantNotStale("runtime", "", "must be non-stale before build -i")
2928 checkbar := func(desc string) {
2929 tg.run("build", "-v", "-i", "x/y/bar")
2930 tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo")
2931 tg.run("build", "-v", "-i", "x/y/bar")
2932 tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo")
2936 tg.creatingTemp("bar" + exeSuffix)
2938 tg.tempFile("src/x/y/foo/foo.go", `package foo
2940 tg.tempFile("src/x/y/bar/bar.go", `package main
2942 func main() { foo.F() }`)
2946 func TestGoBuildInTestOnlyDirectoryFailsWithAGoodError(t *testing.T) {
2949 tg.runFail("build", "./testdata/testonly")
2950 tg.grepStderr("no non-test Go files in", "go build ./testdata/testonly produced unexpected error")
2953 func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) {
2956 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2957 tg.runFail("test", "-c", "testcycle/p3")
2958 tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error")
2960 tg.runFail("test", "-c", "testcycle/q1")
2961 tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error")
2964 func TestGoTestFooTestWorks(t *testing.T) {
2967 tg.run("test", "testdata/standalone_test.go")
2971 func TestGoTestMainWithWrongSignature(t *testing.T) {
2974 tg.runFail("test", "testdata/standalone_main_wrong_test.go")
2975 tg.grepStderr(`wrong signature for TestMain, must be: func TestMain\(m \*testing.M\)`, "detected wrong error message")
2978 func TestGoTestMainAsNormalTest(t *testing.T) {
2981 tg.run("test", "testdata/standalone_main_normal_test.go")
2982 tg.grepBoth(okPattern, "go test did not say ok")
2985 func TestGoTestFlagsAfterPackage(t *testing.T) {
2988 tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags.
2989 tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags.
2992 func TestGoTestXtestonlyWorks(t *testing.T) {
2995 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2996 tg.run("clean", "-i", "xtestonly")
2997 tg.run("test", "xtestonly")
3000 func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) {
3003 tg.run("test", "-v", "./testdata/norunexample")
3004 tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built")
3007 func TestGoGenerateHandlesSimpleCommand(t *testing.T) {
3008 if runtime.GOOS == "windows" {
3009 t.Skip("skipping because windows has no echo command")
3014 tg.run("generate", "./testdata/generate/test1.go")
3015 tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output")
3018 func TestGoGenerateHandlesCommandAlias(t *testing.T) {
3019 if runtime.GOOS == "windows" {
3020 t.Skip("skipping because windows has no echo command")
3025 tg.run("generate", "./testdata/generate/test2.go")
3026 tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output")
3029 func TestGoGenerateVariableSubstitution(t *testing.T) {
3030 if runtime.GOOS == "windows" {
3031 t.Skip("skipping because windows has no echo command")
3036 tg.run("generate", "./testdata/generate/test3.go")
3037 tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output")
3040 func TestGoGenerateRunFlag(t *testing.T) {
3041 if runtime.GOOS == "windows" {
3042 t.Skip("skipping because windows has no echo command")
3047 tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go")
3048 tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes")
3049 tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no")
3052 func TestGoGenerateEnv(t *testing.T) {
3053 switch runtime.GOOS {
3054 case "plan9", "windows":
3055 t.Skipf("skipping because %s does not have the env command", runtime.GOOS)
3060 tg.tempFile("env.go", "package main\n\n//go:generate env")
3061 tg.run("generate", tg.path("env.go"))
3062 for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} {
3063 tg.grepStdout("^"+v+"=", "go generate environment missing "+v)
3067 func TestGoGenerateBadImports(t *testing.T) {
3068 if runtime.GOOS == "windows" {
3069 t.Skip("skipping because windows has no echo command")
3072 // This package has an invalid import causing an import cycle,
3073 // but go generate is supposed to still run.
3076 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3077 tg.run("generate", "gencycle")
3078 tg.grepStdout("hello world", "go generate gencycle did not run generator")
3081 func TestGoGetCustomDomainWildcard(t *testing.T) {
3082 testenv.MustHaveExternalNetwork(t)
3087 tg.setenv("GOPATH", tg.path("."))
3088 tg.run("get", "-u", "rsc.io/pdf/...")
3089 tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd")
3092 func TestGoGetInternalWildcard(t *testing.T) {
3093 testenv.MustHaveExternalNetwork(t)
3098 tg.setenv("GOPATH", tg.path("."))
3099 // used to fail with errors about internal packages
3100 tg.run("get", "github.com/rsc/go-get-issue-11960/...")
3103 func TestGoVetWithExternalTests(t *testing.T) {
3107 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3108 tg.runFail("vet", "vetpkg")
3109 tg.grepBoth("Printf", "go vet vetpkg did not find missing argument for Printf")
3112 func TestGoVetWithTags(t *testing.T) {
3116 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3117 tg.runFail("vet", "-tags", "tagtest", "vetpkg")
3118 tg.grepBoth(`c\.go.*Printf`, "go vet vetpkg did not run scan tagged file")
3121 func TestGoVetWithFlagsOn(t *testing.T) {
3125 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3126 tg.runFail("vet", "-printf", "vetpkg")
3127 tg.grepBoth("Printf", "go vet -printf vetpkg did not find missing argument for Printf")
3130 func TestGoVetWithFlagsOff(t *testing.T) {
3134 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3135 tg.run("vet", "-printf=false", "vetpkg")
3138 // Issue 9767, 19769.
3139 func TestGoGetDotSlashDownload(t *testing.T) {
3140 testenv.MustHaveExternalNetwork(t)
3144 tg.tempDir("src/rsc.io")
3145 tg.setenv("GOPATH", tg.path("."))
3146 tg.cd(tg.path("src/rsc.io"))
3147 tg.run("get", "./pprof_mac_fix")
3150 // Issue 13037: Was not parsing <meta> tags in 404 served over HTTPS
3151 func TestGoGetHTTPS404(t *testing.T) {
3152 testenv.MustHaveExternalNetwork(t)
3153 switch runtime.GOOS {
3154 case "darwin", "linux", "freebsd":
3156 t.Skipf("test case does not work on %s", runtime.GOOS)
3162 tg.setenv("GOPATH", tg.path("."))
3163 tg.run("get", "bazil.org/fuse/fs/fstestutil")
3166 // Test that you cannot import a main package.
3167 // See golang.org/issue/4210 and golang.org/issue/17475.
3168 func TestImportMain(t *testing.T) {
3173 // Importing package main from that package main's test should work.
3174 tg.tempFile("src/x/main.go", `package main
3177 tg.tempFile("src/x/main_test.go", `package main_test
3181 func TestFoo(t *testing.T) {}
3183 tg.setenv("GOPATH", tg.path("."))
3184 tg.creatingTemp("x" + exeSuffix)
3185 tg.run("build", "x")
3188 // Importing package main from another package should fail.
3189 tg.tempFile("src/p1/p.go", `package p1
3193 tg.runFail("build", "p1")
3194 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3196 // ... even in that package's test.
3197 tg.tempFile("src/p2/p.go", `package p2
3199 tg.tempFile("src/p2/p_test.go", `package p2
3203 func TestFoo(t *testing.T) {}
3205 tg.run("build", "p2")
3206 tg.runFail("test", "p2")
3207 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3209 // ... even if that package's test is an xtest.
3210 tg.tempFile("src/p3/p.go", `package p
3212 tg.tempFile("src/p3/p_test.go", `package p_test
3216 func TestFoo(t *testing.T) {}
3218 tg.run("build", "p3")
3219 tg.runFail("test", "p3")
3220 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3222 // ... even if that package is a package main
3223 tg.tempFile("src/p4/p.go", `package main
3226 tg.tempFile("src/p4/p_test.go", `package main
3230 func TestFoo(t *testing.T) {}
3232 tg.creatingTemp("p4" + exeSuffix)
3233 tg.run("build", "p4")
3234 tg.runFail("test", "p4")
3235 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3237 // ... even if that package is a package main using an xtest.
3238 tg.tempFile("src/p5/p.go", `package main
3241 tg.tempFile("src/p5/p_test.go", `package main_test
3245 func TestFoo(t *testing.T) {}
3247 tg.creatingTemp("p5" + exeSuffix)
3248 tg.run("build", "p5")
3249 tg.runFail("test", "p5")
3250 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3253 // Test that you cannot use a local import in a package
3254 // accessed by a non-local import (found in a GOPATH/GOROOT).
3255 // See golang.org/issue/17475.
3256 func TestImportLocal(t *testing.T) {
3261 tg.tempFile("src/dir/x/x.go", `package x
3264 tg.setenv("GOPATH", tg.path("."))
3265 tg.run("build", "dir/x")
3267 // Ordinary import should work.
3268 tg.tempFile("src/dir/p0/p.go", `package p0
3272 tg.run("build", "dir/p0")
3274 // Relative import should not.
3275 tg.tempFile("src/dir/p1/p.go", `package p1
3279 tg.runFail("build", "dir/p1")
3280 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3282 // ... even in a test.
3283 tg.tempFile("src/dir/p2/p.go", `package p2
3285 tg.tempFile("src/dir/p2/p_test.go", `package p2
3289 func TestFoo(t *testing.T) {}
3291 tg.run("build", "dir/p2")
3292 tg.runFail("test", "dir/p2")
3293 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3295 // ... even in an xtest.
3296 tg.tempFile("src/dir/p2/p_test.go", `package p2_test
3300 func TestFoo(t *testing.T) {}
3302 tg.run("build", "dir/p2")
3303 tg.runFail("test", "dir/p2")
3304 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3306 // Relative import starting with ./ should not work either.
3307 tg.tempFile("src/dir/d.go", `package dir
3311 tg.runFail("build", "dir")
3312 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3314 // ... even in a test.
3315 tg.tempFile("src/dir/d.go", `package dir
3317 tg.tempFile("src/dir/d_test.go", `package dir
3321 func TestFoo(t *testing.T) {}
3323 tg.run("build", "dir")
3324 tg.runFail("test", "dir")
3325 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3327 // ... even in an xtest.
3328 tg.tempFile("src/dir/d_test.go", `package dir_test
3332 func TestFoo(t *testing.T) {}
3334 tg.run("build", "dir")
3335 tg.runFail("test", "dir")
3336 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3338 // Relative import plain ".." should not work.
3339 tg.tempFile("src/dir/x/y/y.go", `package dir
3343 tg.runFail("build", "dir/x/y")
3344 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3346 // ... even in a test.
3347 tg.tempFile("src/dir/x/y/y.go", `package y
3349 tg.tempFile("src/dir/x/y/y_test.go", `package y
3353 func TestFoo(t *testing.T) {}
3355 tg.run("build", "dir/x/y")
3356 tg.runFail("test", "dir/x/y")
3357 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3359 // ... even in an x test.
3360 tg.tempFile("src/dir/x/y/y_test.go", `package y_test
3364 func TestFoo(t *testing.T) {}
3366 tg.run("build", "dir/x/y")
3367 tg.runFail("test", "dir/x/y")
3368 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3370 // Relative import "." should not work.
3371 tg.tempFile("src/dir/x/xx.go", `package x
3375 tg.runFail("build", "dir/x")
3376 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3378 // ... even in a test.
3379 tg.tempFile("src/dir/x/xx.go", `package x
3381 tg.tempFile("src/dir/x/xx_test.go", `package x
3385 func TestFoo(t *testing.T) {}
3387 tg.run("build", "dir/x")
3388 tg.runFail("test", "dir/x")
3389 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3391 // ... even in an xtest.
3392 tg.tempFile("src/dir/x/xx.go", `package x
3394 tg.tempFile("src/dir/x/xx_test.go", `package x_test
3398 func TestFoo(t *testing.T) {}
3400 tg.run("build", "dir/x")
3401 tg.runFail("test", "dir/x")
3402 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3405 func TestGoGetInsecure(t *testing.T) {
3406 testenv.MustHaveExternalNetwork(t)
3411 tg.setenv("GOPATH", tg.path("."))
3414 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3416 // Try go get -d of HTTP-only repo (should fail).
3417 tg.runFail("get", "-d", repo)
3419 // Try again with -insecure (should succeed).
3420 tg.run("get", "-d", "-insecure", repo)
3422 // Try updating without -insecure (should fail).
3423 tg.runFail("get", "-d", "-u", "-f", repo)
3426 func TestGoGetUpdateInsecure(t *testing.T) {
3427 testenv.MustHaveExternalNetwork(t)
3432 tg.setenv("GOPATH", tg.path("."))
3434 const repo = "github.com/golang/example"
3436 // Clone the repo via HTTP manually.
3437 cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
3438 if out, err := cmd.CombinedOutput(); err != nil {
3439 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3442 // Update without -insecure should fail.
3443 // Update with -insecure should succeed.
3444 // We need -f to ignore import comments.
3445 const pkg = repo + "/hello"
3446 tg.runFail("get", "-d", "-u", "-f", pkg)
3447 tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
3450 func TestGoGetInsecureCustomDomain(t *testing.T) {
3451 testenv.MustHaveExternalNetwork(t)
3456 tg.setenv("GOPATH", tg.path("."))
3458 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3459 tg.runFail("get", "-d", repo)
3460 tg.run("get", "-d", "-insecure", repo)
3463 func TestGoRunDirs(t *testing.T) {
3466 tg.cd("testdata/rundir")
3467 tg.runFail("run", "x.go", "sub/sub.go")
3468 tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
3469 tg.runFail("run", "sub/sub.go", "x.go")
3470 tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
3473 func TestGoInstallPkgdir(t *testing.T) {
3479 tg.run("install", "-pkgdir", pkg, "sync")
3480 tg.mustExist(filepath.Join(pkg, "sync.a"))
3481 tg.mustNotExist(filepath.Join(pkg, "sync/atomic.a"))
3482 tg.run("install", "-i", "-pkgdir", pkg, "sync")
3483 tg.mustExist(filepath.Join(pkg, "sync.a"))
3484 tg.mustExist(filepath.Join(pkg, "sync/atomic.a"))
3487 func TestGoTestRaceInstallCgo(t *testing.T) {
3489 t.Skip("skipping because race detector not supported")
3492 // golang.org/issue/10500.
3493 // This used to install a race-enabled cgo.
3496 tg.run("tool", "-n", "cgo")
3497 cgo := strings.TrimSpace(tg.stdout.String())
3498 old, err := os.Stat(cgo)
3500 tg.run("test", "-race", "-i", "runtime/race")
3501 new, err := os.Stat(cgo)
3503 if !new.ModTime().Equal(old.ModTime()) {
3504 t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
3508 func TestGoTestRaceFailures(t *testing.T) {
3510 t.Skip("skipping because race detector not supported")
3516 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3518 tg.run("test", "testrace")
3520 tg.runFail("test", "-race", "testrace")
3521 tg.grepStdout("FAIL: TestRace", "TestRace did not fail")
3522 tg.grepBothNot("PASS", "something passed")
3524 tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".")
3525 tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail")
3526 tg.grepBothNot("PASS", "something passed")
3529 func TestGoTestImportErrorStack(t *testing.T) {
3530 const out = `package testdep/p1 (test)
3532 imports testdep/p3: build constraints exclude all Go files `
3536 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3537 tg.runFail("test", "testdep/p1")
3538 if !strings.Contains(tg.stderr.String(), out) {
3539 t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String())
3543 func TestGoGetUpdate(t *testing.T) {
3544 // golang.org/issue/9224.
3545 // The recursive updating was trying to walk to
3546 // former dependencies, not current ones.
3548 testenv.MustHaveExternalNetwork(t)
3553 tg.setenv("GOPATH", tg.path("."))
3556 tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
3557 cmd := exec.Command("git", "reset", "--hard", "HEAD~")
3558 cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
3559 out, err := cmd.CombinedOutput()
3561 t.Fatalf("git: %v\n%s", err, out)
3566 tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3568 // Again with -d -u.
3570 tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3574 func TestGoGetRace(t *testing.T) {
3575 testenv.MustHaveExternalNetwork(t)
3577 t.Skip("skipping because race detector not supported")
3583 tg.setenv("GOPATH", tg.path("."))
3584 tg.run("get", "-race", "github.com/rsc/go-get-issue-9224-cmd")
3587 func TestGoGetDomainRoot(t *testing.T) {
3588 // golang.org/issue/9357.
3589 // go get foo.io (not foo.io/subdir) was not working consistently.
3591 testenv.MustHaveExternalNetwork(t)
3596 tg.setenv("GOPATH", tg.path("."))
3598 // go-get-issue-9357.appspot.com is running
3599 // the code at github.com/rsc/go-get-issue-9357,
3600 // a trivial Go on App Engine app that serves a
3601 // <meta> tag for the domain root.
3602 tg.run("get", "-d", "go-get-issue-9357.appspot.com")
3603 tg.run("get", "go-get-issue-9357.appspot.com")
3604 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3606 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3607 tg.run("get", "go-get-issue-9357.appspot.com")
3609 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3610 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3613 func TestGoInstallShadowedGOPATH(t *testing.T) {
3614 // golang.org/issue/3652.
3615 // go get foo.io (not foo.io/subdir) was not working consistently.
3617 testenv.MustHaveExternalNetwork(t)
3622 tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
3624 tg.tempDir("gopath1/src/test")
3625 tg.tempDir("gopath2/src/test")
3626 tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
3628 tg.cd(tg.path("gopath2/src/test"))
3629 tg.runFail("install")
3630 tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
3633 func TestGoBuildGOPATHOrder(t *testing.T) {
3634 // golang.org/issue/14176#issuecomment-179895769
3635 // golang.org/issue/14192
3636 // -I arguments to compiler could end up not in GOPATH order,
3637 // leading to unexpected import resolution in the compiler.
3638 // This is still not a complete fix (see golang.org/issue/14271 and next test)
3639 // but it is clearly OK and enough to fix both of the two reported
3640 // instances of the underlying problem. It will have to do for now.
3645 tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2"))
3647 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3648 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3649 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3650 tg.tempFile("p1/src/bar/bar.go", `
3656 tg.run("install", "-x", "bar")
3659 func TestGoBuildGOPATHOrderBroken(t *testing.T) {
3660 // This test is known not to work.
3661 // See golang.org/issue/14271.
3662 t.Skip("golang.org/issue/14271")
3668 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3669 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3670 tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n")
3671 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3672 tg.tempFile("p1/src/bar/bar.go", `
3678 colon := string(filepath.ListSeparator)
3679 tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2"))
3680 tg.run("install", "-x", "bar")
3682 tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1"))
3683 tg.run("install", "-x", "bar")
3686 func TestIssue11709(t *testing.T) {
3689 tg.tempFile("run.go", `
3693 if os.Getenv("TERM") != "" {
3698 tg.run("run", tg.path("run.go"))
3701 func TestIssue12096(t *testing.T) {
3704 tg.tempFile("test_test.go", `
3706 import ("os"; "testing")
3707 func TestEnv(t *testing.T) {
3708 if os.Getenv("TERM") != "" {
3709 t.Fatal("TERM is set")
3713 tg.run("test", tg.path("test_test.go"))
3716 func TestGoBuildOutput(t *testing.T) {
3723 nonExeSuffix := ".exe"
3724 if exeSuffix == ".exe" {
3728 tg.tempFile("x.go", "package main\nfunc main(){}\n")
3729 tg.run("build", "x.go")
3730 tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
3731 tg.must(os.Remove(tg.path("x" + exeSuffix)))
3732 tg.mustNotExist("x" + nonExeSuffix)
3734 tg.run("build", "-o", "myprog", "x.go")
3735 tg.mustNotExist("x")
3736 tg.mustNotExist("x.exe")
3737 tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
3738 tg.mustNotExist("myprog.exe")
3740 tg.tempFile("p.go", "package p\n")
3741 tg.run("build", "p.go")
3742 tg.mustNotExist("p")
3743 tg.mustNotExist("p.a")
3744 tg.mustNotExist("p.o")
3745 tg.mustNotExist("p.exe")
3747 tg.run("build", "-o", "p.a", "p.go")
3748 tg.wantArchive("p.a")
3750 tg.run("build", "cmd/gofmt")
3751 tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
3752 tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
3753 tg.mustNotExist("gofmt" + nonExeSuffix)
3755 tg.run("build", "-o", "mygofmt", "cmd/gofmt")
3756 tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
3757 tg.mustNotExist("mygofmt.exe")
3758 tg.mustNotExist("gofmt")
3759 tg.mustNotExist("gofmt.exe")
3761 tg.run("build", "sync/atomic")
3762 tg.mustNotExist("atomic")
3763 tg.mustNotExist("atomic.exe")
3765 tg.run("build", "-o", "myatomic.a", "sync/atomic")
3766 tg.wantArchive("myatomic.a")
3767 tg.mustNotExist("atomic")
3768 tg.mustNotExist("atomic.a")
3769 tg.mustNotExist("atomic.exe")
3771 tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
3772 tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
3775 func TestGoBuildARM(t *testing.T) {
3776 if testing.Short() {
3777 t.Skip("skipping cross-compile in short mode")
3786 tg.setenv("GOARCH", "arm")
3787 tg.setenv("GOOS", "linux")
3788 tg.setenv("GOARM", "5")
3789 tg.tempFile("hello.go", `package main
3791 tg.run("build", "hello.go")
3792 tg.grepStderrNot("unable to find math.a", "did not build math.a correctly")
3796 func TestParallelTest(t *testing.T) {
3801 const testSrc = `package package_test
3805 func TestTest(t *testing.T) {
3807 tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
3808 tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
3809 tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
3810 tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
3811 tg.setenv("GOPATH", tg.path("."))
3812 tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
3815 func TestCgoConsistentResults(t *testing.T) {
3817 t.Skip("skipping because cgo not enabled")
3819 switch runtime.GOOS {
3821 testenv.SkipFlaky(t, 15405)
3823 testenv.SkipFlaky(t, 13247)
3830 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3831 exe1 := tg.path("cgotest1" + exeSuffix)
3832 exe2 := tg.path("cgotest2" + exeSuffix)
3833 tg.run("build", "-o", exe1, "cgotest")
3834 tg.run("build", "-x", "-o", exe2, "cgotest")
3835 b1, err := ioutil.ReadFile(exe1)
3837 b2, err := ioutil.ReadFile(exe2)
3840 if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) {
3841 t.Skip("skipping because C compiler does not support -fdebug-prefix-map")
3843 if !bytes.Equal(b1, b2) {
3844 t.Error("building cgotest twice did not produce the same output")
3848 // Issue 14444: go get -u .../ duplicate loads errors
3849 func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) {
3850 testenv.MustHaveExternalNetwork(t)
3855 tg.setenv("GOPATH", tg.path("."))
3856 tg.run("get", "-u", ".../")
3857 tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache")
3860 // Issue 17119 more duplicate load errors
3861 func TestIssue17119(t *testing.T) {
3862 testenv.MustHaveExternalNetwork(t)
3867 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3868 tg.runFail("build", "dupload")
3869 tg.grepBothNot("duplicate load|internal error", "internal error")
3872 func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) {
3875 // TODO: tg.parallel()
3876 tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal")
3877 tg.grepBothNot("^ok", "test passed unexpectedly")
3878 tg.grepBoth("FAIL.*benchfatal", "test did not run everything")
3881 func TestBinaryOnlyPackages(t *testing.T) {
3886 tg.setenv("GOPATH", tg.path("."))
3888 tg.tempFile("src/p1/p1.go", `//go:binary-only-package
3892 tg.wantStale("p1", "missing or invalid binary-only package", "p1 is binary-only but has no binary, should be stale")
3893 tg.runFail("install", "p1")
3894 tg.grepStderr("missing or invalid binary-only package", "did not report attempt to compile binary-only package")
3896 tg.tempFile("src/p1/p1.go", `
3899 func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } }
3901 tg.run("install", "p1")
3902 os.Remove(tg.path("src/p1/p1.go"))
3903 tg.mustNotExist(tg.path("src/p1/p1.go"))
3905 tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great
3909 func F() { p1.F(true) }
3911 tg.runFail("install", "p2")
3912 tg.grepStderr("no Go files", "did not complain about missing sources")
3914 tg.tempFile("src/p1/missing.go", `//go:binary-only-package
3920 tg.wantNotStale("p1", "binary-only package", "should NOT want to rebuild p1 (first)")
3921 tg.run("install", "-x", "p1") // no-op, up to date
3922 tg.grepBothNot(`[\\/]compile`, "should not have run compiler")
3923 tg.run("install", "p2") // does not rebuild p1 (or else p2 will fail)
3924 tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
3926 // changes to the non-source-code do not matter,
3927 // and only one file needs the special comment.
3928 tg.tempFile("src/p1/missing2.go", `
3932 tg.wantNotStale("p1", "binary-only package", "should NOT want to rebuild p1 (second)")
3933 tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
3935 tg.tempFile("src/p3/p3.go", `
3946 tg.run("install", "p3")
3948 tg.run("run", tg.path("src/p3/p3.go"))
3949 tg.grepStdout("hello from p1", "did not see message from p1")
3951 tg.tempFile("src/p4/p4.go", `package main`)
3952 // The odd string split below avoids vet complaining about
3953 // a // +build line appearing too late in this source file.
3954 tg.tempFile("src/p4/p4not.go", `//go:binary-only-package
3960 tg.run("list", "-f", "{{.BinaryOnly}}", "p4")
3961 tg.grepStdout("false", "did not see BinaryOnly=false for p4")
3965 func TestAlwaysLinkSysoFiles(t *testing.T) {
3969 tg.tempDir("src/syso")
3970 tg.tempFile("src/syso/a.syso", ``)
3971 tg.tempFile("src/syso/b.go", `package syso`)
3972 tg.setenv("GOPATH", tg.path("."))
3974 // We should see the .syso file regardless of the setting of
3977 tg.setenv("CGO_ENABLED", "1")
3978 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
3979 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1")
3981 tg.setenv("CGO_ENABLED", "0")
3982 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
3983 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0")
3987 func TestGenerateUsesBuildContext(t *testing.T) {
3988 if runtime.GOOS == "windows" {
3989 t.Skip("this test won't run under Windows")
3995 tg.tempDir("src/gen")
3996 tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n")
3997 tg.setenv("GOPATH", tg.path("."))
3999 tg.setenv("GOOS", "linux")
4000 tg.setenv("GOARCH", "amd64")
4001 tg.run("generate", "gen")
4002 tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination")
4004 tg.setenv("GOOS", "darwin")
4005 tg.setenv("GOARCH", "386")
4006 tg.run("generate", "gen")
4007 tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination")
4010 // Issue 14450: go get -u .../ tried to import not downloaded package
4011 func TestGoGetUpdateWithWildcard(t *testing.T) {
4012 testenv.MustHaveExternalNetwork(t)
4018 tg.setenv("GOPATH", tg.path("."))
4019 const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a"
4020 tg.run("get", aPkgImportPath)
4021 tg.run("get", "-u", ".../")
4022 tg.grepStderrNot("cannot find package", "did not update packages given wildcard path")
4024 var expectedPkgPaths = []string{
4025 "src/github.com/tmwh/go-get-issue-14450/b",
4026 "src/github.com/tmwh/go-get-issue-14450-b-dependency/c",
4027 "src/github.com/tmwh/go-get-issue-14450-b-dependency/d",
4030 for _, importPath := range expectedPkgPaths {
4031 _, err := os.Stat(tg.path(importPath))
4034 const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e"
4035 tg.mustNotExist(tg.path(notExpectedPkgPath))
4038 func TestGoEnv(t *testing.T) {
4042 tg.setenv("GOOS", "freebsd") // to avoid invalid pair errors
4043 tg.setenv("GOARCH", "arm")
4044 tg.run("env", "GOARCH")
4045 tg.grepStdout("^arm$", "GOARCH not honored")
4047 tg.run("env", "GCCGO")
4048 tg.grepStdout(".", "GCCGO unexpectedly empty")
4050 tg.run("env", "CGO_CFLAGS")
4051 tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty")
4053 tg.setenv("CGO_CFLAGS", "-foobar")
4054 tg.run("env", "CGO_CFLAGS")
4055 tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored")
4057 tg.setenv("CC", "gcc -fmust -fgo -ffaster")
4059 tg.grepStdout("gcc", "CC not found")
4060 tg.run("env", "GOGCCFLAGS")
4061 tg.grepStdout("-ffaster", "CC arguments not found")
4065 noMatchesPattern = `(?m)^ok.*\[no tests to run\]`
4066 okPattern = `(?m)^ok`
4069 func TestMatchesNoTests(t *testing.T) {
4072 // TODO: tg.parallel()
4073 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go")
4074 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4077 func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) {
4081 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4082 tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror")
4083 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4084 tg.grepBoth("FAIL", "go test did not say FAIL")
4087 func TestMatchesNoBenchmarksIsOK(t *testing.T) {
4090 // TODO: tg.parallel()
4091 tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go")
4092 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4093 tg.grepBoth(okPattern, "go test did not say ok")
4096 func TestMatchesOnlyExampleIsOK(t *testing.T) {
4099 // TODO: tg.parallel()
4100 tg.run("test", "-run", "Example", "testdata/example1_test.go")
4101 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4102 tg.grepBoth(okPattern, "go test did not say ok")
4105 func TestMatchesOnlyBenchmarkIsOK(t *testing.T) {
4108 // TODO: tg.parallel()
4109 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4110 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4111 tg.grepBoth(okPattern, "go test did not say ok")
4114 func TestBenchmarkLabels(t *testing.T) {
4117 // TODO: tg.parallel()
4118 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4119 tg.run("test", "-run", "^$", "-bench", ".", "bench")
4120 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4121 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4122 tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench")
4123 tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times")
4126 func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) {
4129 // TODO: tg.parallel()
4130 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4131 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4132 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4133 tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:")
4136 func TestMatchesOnlyTestIsOK(t *testing.T) {
4139 // TODO: tg.parallel()
4140 tg.run("test", "-run", "Test", "testdata/standalone_test.go")
4141 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4142 tg.grepBoth(okPattern, "go test did not say ok")
4145 func TestMatchesNoTestsWithSubtests(t *testing.T) {
4148 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go")
4149 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4152 func TestMatchesNoSubtestsMatch(t *testing.T) {
4155 tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go")
4156 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4159 func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) {
4162 tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go")
4163 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4164 tg.grepBoth("FAIL", "go test did not say FAIL")
4167 func TestMatchesOnlySubtestIsOK(t *testing.T) {
4170 tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go")
4171 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4172 tg.grepBoth(okPattern, "go test did not say ok")
4175 func TestMatchesNoSubtestsParallel(t *testing.T) {
4178 tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go")
4179 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4182 func TestMatchesOnlySubtestParallelIsOK(t *testing.T) {
4185 tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go")
4186 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4187 tg.grepBoth(okPattern, "go test did not say ok")
4191 func TestBenchTimeout(t *testing.T) {
4194 tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go")
4198 func TestWriteProfilesOnTimeout(t *testing.T) {
4201 tg.tempDir("profiling")
4202 tg.tempFile("profiling/timeouttest_test.go", `package timeouttest_test
4205 func TestSleep(t *testing.T) { time.Sleep(time.Second) }`)
4206 tg.cd(tg.path("profiling"))
4209 "-cpuprofile", tg.path("profiling/cpu.pprof"), "-memprofile", tg.path("profiling/mem.pprof"),
4211 tg.mustHaveContent(tg.path("profiling/cpu.pprof"))
4212 tg.mustHaveContent(tg.path("profiling/mem.pprof"))
4215 func TestLinkXImportPathEscape(t *testing.T) {
4216 // golang.org/issue/16710
4220 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4221 exe := "./linkx" + exeSuffix
4222 tg.creatingTemp(exe)
4223 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main")
4224 out, err := exec.Command(exe).CombinedOutput()
4228 if string(out) != "linkXworked\n" {
4229 tg.t.Log(string(out))
4230 tg.t.Fatal(`incorrect output: expected "linkXworked\n"`)
4235 func TestLdBindNow(t *testing.T) {
4239 tg.setenv("LD_BIND_NOW", "1")
4244 // This is really a cmd/asm issue but this is a convenient place to test it.
4245 func TestConcurrentAsm(t *testing.T) {
4249 asm := `DATA ·constants<>+0x0(SB)/8,$0
4250 GLOBL ·constants<>(SB),8,$8
4252 tg.tempFile("go/src/p/a.s", asm)
4253 tg.tempFile("go/src/p/b.s", asm)
4254 tg.tempFile("go/src/p/p.go", `package p`)
4255 tg.setenv("GOPATH", tg.path("go"))
4256 tg.run("build", "p")
4260 func TestDotDotDotOutsideGOPATH(t *testing.T) {
4264 tg.tempFile("pkgs/a.go", `package x`)
4265 tg.tempFile("pkgs/a_test.go", `package x_test
4267 func TestX(t *testing.T) {}`)
4269 tg.tempFile("pkgs/a/a.go", `package a`)
4270 tg.tempFile("pkgs/a/a_test.go", `package a_test
4272 func TestA(t *testing.T) {}`)
4274 tg.cd(tg.path("pkgs"))
4275 tg.run("build", "./...")
4276 tg.run("test", "./...")
4277 tg.run("list", "./...")
4278 tg.grepStdout("pkgs$", "expected package not listed")
4279 tg.grepStdout("pkgs/a", "expected package not listed")
4283 func TestFFLAGS(t *testing.T) {
4285 t.Skip("skipping because cgo not enabled")
4292 tg.tempFile("p/src/p/main.go", `package main
4293 // #cgo FFLAGS: -no-such-fortran-flag
4297 tg.tempFile("p/src/p/a.f", `! comment`)
4298 tg.setenv("GOPATH", tg.path("p"))
4300 // This should normally fail because we are passing an unknown flag,
4301 // but issue #19080 points to Fortran compilers that succeed anyhow.
4302 // To work either way we call doRun directly rather than run or runFail.
4303 tg.doRun([]string{"build", "-x", "p"})
4305 tg.grepStderr("no-such-fortran-flag", `missing expected "-no-such-fortran-flag"`)
4309 // This is really a cmd/link issue but this is a convenient place to test it.
4310 func TestDuplicateGlobalAsmSymbols(t *testing.T) {
4311 if runtime.GOARCH != "386" && runtime.GOARCH != "amd64" {
4312 t.Skipf("skipping test on %s", runtime.GOARCH)
4315 t.Skip("skipping because cgo not enabled")
4323 #include "textflag.h"
4325 DATA sym<>+0x0(SB)/8,$0
4326 GLOBL sym<>(SB),(NOPTR+RODATA),$8
4328 TEXT ·Data(SB),NOSPLIT,$0
4333 tg.tempFile("go/src/a/a.s", asm)
4334 tg.tempFile("go/src/a/a.go", `package a; func Data() uint8`)
4335 tg.tempFile("go/src/b/b.s", asm)
4336 tg.tempFile("go/src/b/b.go", `package b; func Data() uint8`)
4337 tg.tempFile("go/src/p/p.go", `
4343 _ = a.Data() + b.Data()
4346 tg.setenv("GOPATH", tg.path("go"))
4347 exe := filepath.Join(tg.tempdir, "p.exe")
4348 tg.creatingTemp(exe)
4349 tg.run("build", "-o", exe, "p")
4352 func TestBuildTagsNoComma(t *testing.T) {
4356 tg.setenv("GOPATH", tg.path("go"))
4357 tg.run("build", "-tags", "tag1 tag2", "math")
4358 tg.runFail("build", "-tags", "tag1,tag2", "math")
4359 tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
4362 func copyFile(src, dst string, perm os.FileMode) error {
4363 sf, err := os.Open(src)
4369 df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
4374 _, err = io.Copy(df, sf)
4382 func TestExecutableGOROOT(t *testing.T) {
4383 if runtime.GOOS == "openbsd" {
4384 t.Skipf("test case does not work on %s, missing os.Executable", runtime.GOOS)
4387 // Env with no GOROOT.
4389 for _, e := range os.Environ() {
4390 if !strings.HasPrefix(e, "GOROOT=") {
4391 env = append(env, e)
4395 check := func(t *testing.T, exe, want string) {
4396 cmd := exec.Command(exe, "env", "GOROOT")
4398 out, err := cmd.CombinedOutput()
4400 t.Fatalf("%s env GOROOT: %v, %s", exe, err, out)
4402 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4406 want, err = filepath.EvalSymlinks(want)
4410 if !strings.EqualFold(goroot, want) {
4411 t.Errorf("go env GOROOT:\nhave %s\nwant %s", goroot, want)
4413 t.Logf("go env GOROOT: %s", goroot)
4417 // Note: Must not call tg methods inside subtests: tg is attached to outer t.
4422 tg.tempDir("new/bin")
4423 newGoTool := tg.path("new/bin/go" + exeSuffix)
4424 tg.must(copyFile(tg.goTool(), newGoTool, 0775))
4425 newRoot := tg.path("new")
4427 t.Run("RelocatedExe", func(t *testing.T) {
4428 t.Skip("TODO: skipping known broken test; see golang.org/issue/20284")
4430 // Should fall back to default location in binary.
4431 // No way to dig out other than look at source code.
4432 data, err := ioutil.ReadFile("../../runtime/internal/sys/zversion.go")
4436 m := regexp.MustCompile("var DefaultGoroot = `([^`]+)`").FindStringSubmatch(string(data))
4438 t.Fatal("cannot find DefaultGoroot in ../../runtime/internal/sys/zversion.go")
4440 check(t, newGoTool, m[1])
4443 // If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT,
4444 // so it should find the new tree.
4445 tg.tempDir("new/pkg/tool")
4446 t.Run("RelocatedTree", func(t *testing.T) {
4447 check(t, newGoTool, newRoot)
4450 tg.tempDir("other/bin")
4451 symGoTool := tg.path("other/bin/go" + exeSuffix)
4453 // Symlink into go tree should still find go tree.
4454 t.Run("SymlinkedExe", func(t *testing.T) {
4455 testenv.MustHaveSymlink(t)
4456 if err := os.Symlink(newGoTool, symGoTool); err != nil {
4459 check(t, symGoTool, newRoot)
4462 tg.must(os.RemoveAll(tg.path("new/pkg")))
4464 // Binaries built in the new tree should report the
4465 // new tree when they call runtime.GOROOT().
4466 // This is implemented by having the go tool pass a -X option
4467 // to the linker setting runtime/internal/sys.DefaultGoroot.
4468 t.Run("RuntimeGoroot", func(t *testing.T) {
4469 // Build a working GOROOT the easy way, with symlinks.
4470 testenv.MustHaveSymlink(t)
4471 if err := os.Symlink(filepath.Join(testGOROOT, "src"), tg.path("new/src")); err != nil {
4474 if err := os.Symlink(filepath.Join(testGOROOT, "pkg"), tg.path("new/pkg")); err != nil {
4478 cmd := exec.Command(newGoTool, "run", "testdata/print_goroot.go")
4480 out, err := cmd.CombinedOutput()
4482 t.Fatalf("%s run testdata/print_goroot.go: %v, %s", newGoTool, err, out)
4484 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4488 want, err := filepath.EvalSymlinks(tg.path("new"))
4492 if !strings.EqualFold(goroot, want) {
4493 t.Errorf("go run testdata/print_goroot.go:\nhave %s\nwant %s", goroot, want)
4495 t.Logf("go run testdata/print_goroot.go: %s", goroot)
4500 func TestNeedVersion(t *testing.T) {
4504 tg.tempFile("goversion.go", `package main; func main() {}`)
4505 path := tg.path("goversion.go")
4506 tg.setenv("TESTGO_VERSION", "go1.testgo")
4507 tg.runFail("run", path)
4508 tg.grepStderr("compile", "does not match go tool version")
4511 // Test that user can override default code generation flags.
4512 func TestUserOverrideFlags(t *testing.T) {
4514 t.Skip("skipping because cgo not enabled")
4516 if runtime.GOOS != "linux" {
4517 // We are testing platform-independent code, so it's
4518 // OK to skip cases that work differently.
4519 t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS)
4524 // Don't call tg.parallel, as creating override.h and override.a may
4525 // confuse other tests.
4526 tg.tempFile("override.go", `package main
4534 tg.creatingTemp("override.a")
4535 tg.creatingTemp("override.h")
4536 tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=all=-shared=false", tg.path("override.go"))
4537 tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag")
4540 func TestCgoFlagContainsSpace(t *testing.T) {
4542 t.Skip("skipping because cgo not enabled")
4549 tg.tempFile("main.go", `package main
4550 // #cgo CFLAGS: -I"c flags"
4551 // #cgo LDFLAGS: -L"ld flags"
4555 tg.run("run", "-x", "main.go")
4556 tg.grepStderr(`"-I[^"]+c flags"`, "did not find quoted c flags")
4557 tg.grepStderrNot(`"-I[^"]+c flags".*"-I[^"]+c flags"`, "found too many quoted c flags")
4558 tg.grepStderr(`"-L[^"]+ld flags"`, "did not find quoted ld flags")
4559 tg.grepStderrNot(`"-L[^"]+c flags".*"-L[^"]+c flags"`, "found too many quoted ld flags")
4563 func TestGoTestRaceCoverModeFailures(t *testing.T) {
4565 t.Skip("skipping because race detector not supported")
4571 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4573 tg.run("test", "testrace")
4575 tg.runFail("test", "-race", "-covermode=set", "testrace")
4576 tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed")
4577 tg.grepBothNot("PASS", "something passed")
4580 // Issue 9737: verify that GOARM and GO386 affect the computed build ID.
4581 func TestBuildIDContainsArchModeEnv(t *testing.T) {
4582 if testing.Short() {
4583 t.Skip("skipping in short mode")
4587 testWith := func(before, after func()) func(*testing.T) {
4588 return func(t *testing.T) {
4591 tg.tempFile("src/mycmd/x.go", `package main
4593 tg.setenv("GOPATH", tg.path("."))
4595 tg.cd(tg.path("src/mycmd"))
4596 tg.setenv("GOOS", "linux")
4598 tg.run("install", "mycmd")
4600 tg.wantStale("mycmd", "stale dependency: runtime/internal/sys", "should be stale after environment variable change")
4604 t.Run("386", testWith(func() {
4605 tg.setenv("GOARCH", "386")
4606 tg.setenv("GO386", "387")
4608 tg.setenv("GO386", "sse2")
4611 t.Run("arm", testWith(func() {
4612 tg.setenv("GOARCH", "arm")
4613 tg.setenv("GOARM", "5")
4615 tg.setenv("GOARM", "7")
4619 func TestTestRegexps(t *testing.T) {
4622 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4623 tg.run("test", "-cpu=1", "-run=X/Y", "-bench=X/Y", "-count=2", "-v", "testregexp")
4625 for _, line := range strings.SplitAfter(tg.getStdout(), "\n") {
4626 if strings.Contains(line, "=== RUN") || strings.Contains(line, "--- BENCH") || strings.Contains(line, "LOG") {
4627 lines = append(lines, line)
4632 // TestX is run, twice
4633 // TestX/Y is run, twice
4634 // TestXX is run, twice
4636 // BenchmarkX is run but only with N=1, once
4637 // BenchmarkXX is run but only with N=1, once
4638 // BenchmarkX/Y is run in full, twice
4639 want := `=== RUN TestX
4641 x_test.go:6: LOG: X running
4642 x_test.go:8: LOG: Y running
4644 z_test.go:10: LOG: XX running
4647 x_test.go:6: LOG: X running
4648 x_test.go:8: LOG: Y running
4650 z_test.go:10: LOG: XX running
4651 --- BENCH: BenchmarkX/Y
4652 x_test.go:15: LOG: Y running N=1
4653 x_test.go:15: LOG: Y running N=100
4654 x_test.go:15: LOG: Y running N=10000
4655 x_test.go:15: LOG: Y running N=1000000
4656 x_test.go:15: LOG: Y running N=100000000
4657 x_test.go:15: LOG: Y running N=2000000000
4658 --- BENCH: BenchmarkX/Y
4659 x_test.go:15: LOG: Y running N=1
4660 x_test.go:15: LOG: Y running N=100
4661 x_test.go:15: LOG: Y running N=10000
4662 x_test.go:15: LOG: Y running N=1000000
4663 x_test.go:15: LOG: Y running N=100000000
4664 x_test.go:15: LOG: Y running N=2000000000
4665 --- BENCH: BenchmarkX
4666 x_test.go:13: LOG: X running N=1
4667 --- BENCH: BenchmarkXX
4668 z_test.go:18: LOG: XX running N=1
4671 have := strings.Join(lines, "")
4673 t.Errorf("reduced output:<<<\n%s>>> want:<<<\n%s>>>", have, want)
4677 func TestListTests(t *testing.T) {
4679 testWith := func(listName, expected string) func(*testing.T) {
4680 return func(t *testing.T) {
4683 tg.run("test", "./testdata/src/testlist/...", fmt.Sprintf("-list=%s", listName))
4684 tg.grepStdout(expected, fmt.Sprintf("-test.list=%s returned %q, expected %s", listName, tg.getStdout(), expected))
4688 t.Run("Test", testWith("Test", "TestSimple"))
4689 t.Run("Bench", testWith("Benchmark", "BenchmarkSimple"))
4690 t.Run("Example1", testWith("Example", "ExampleSimple"))
4691 t.Run("Example2", testWith("Example", "ExampleWithEmptyOutput"))
4694 func TestBuildmodePIE(t *testing.T) {
4695 if runtime.Compiler == "gccgo" {
4696 t.Skipf("skipping test because buildmode=pie is not supported on gccgo")
4699 platform := fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
4701 case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x",
4702 "android/amd64", "android/arm", "android/arm64", "android/386":
4703 case "darwin/amd64":
4705 t.Skipf("skipping test because buildmode=pie is not supported on %s", platform)
4711 tg.tempFile("main.go", `package main; func main() { print("hello") }`)
4712 src := tg.path("main.go")
4713 obj := tg.path("main")
4714 tg.run("build", "-buildmode=pie", "-o", obj, src)
4716 switch runtime.GOOS {
4717 case "linux", "android":
4718 f, err := elf.Open(obj)
4723 if f.Type != elf.ET_DYN {
4724 t.Errorf("PIE type must be ET_DYN, but %s", f.Type)
4727 f, err := macho.Open(obj)
4732 if f.Flags&macho.FlagDyldLink == 0 {
4733 t.Error("PIE must have DyldLink flag, but not")
4735 if f.Flags&macho.FlagPIE == 0 {
4736 t.Error("PIE must have PIE flag, but not")
4739 panic("unreachable")
4742 out, err := exec.Command(obj).CombinedOutput()
4747 if string(out) != "hello" {
4748 t.Errorf("got %q; want %q", out, "hello")
4752 func TestExecBuildX(t *testing.T) {
4754 t.Skip("skipping because cgo not enabled")
4757 if runtime.GOOS == "plan9" || runtime.GOOS == "windows" {
4758 t.Skipf("skipping because unix shell is not supported on %s", runtime.GOOS)
4764 tg.tempFile("main.go", `package main; import "C"; func main() { print("hello") }`)
4765 src := tg.path("main.go")
4766 obj := tg.path("main")
4767 tg.run("build", "-x", "-o", obj, src)
4768 sh := tg.path("test.sh")
4769 err := ioutil.WriteFile(sh, []byte(tg.getStderr()), 0666)
4774 out, err := exec.Command(obj).CombinedOutput()
4778 if string(out) != "hello" {
4779 t.Fatalf("got %q; want %q", out, "hello")
4782 err = os.Remove(obj)
4787 out, err = exec.Command("/usr/bin/env", "bash", "-x", sh).CombinedOutput()
4789 t.Fatalf("/bin/sh %s: %v\n%s", sh, err, out)
4791 t.Logf("shell output:\n%s", out)
4793 out, err = exec.Command(obj).CombinedOutput()
4797 if string(out) != "hello" {
4798 t.Fatalf("got %q; want %q", out, "hello")
4802 func TestParallelNumber(t *testing.T) {
4803 for _, n := range [...]string{"-1", "0"} {
4804 t.Run(n, func(t *testing.T) {
4807 tg.runFail("test", "-parallel", n, "testdata/standalone_parallel_sub_test.go")
4808 tg.grepBoth("-parallel can only be given", "go test -parallel with N<1 did not error")
4813 func TestWrongGOOSErrorBeforeLoadError(t *testing.T) {
4816 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4817 tg.setenv("GOOS", "windwos")
4818 tg.runFail("build", "exclude")
4819 tg.grepStderr("unsupported GOOS/GOARCH pair", "GOOS=windwos go build exclude did not report 'unsupported GOOS/GOARCH pair'")
4822 func TestUpxCompression(t *testing.T) {
4823 if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
4824 t.Skipf("skipping upx test on %s/%s", runtime.GOOS, runtime.GOARCH)
4827 out, err := exec.Command("upx", "--version").CombinedOutput()
4829 t.Skip("skipping because upx is not available")
4832 // upx --version prints `upx <version>` in the first line of output:
4835 re := regexp.MustCompile(`([[:digit:]]+)\.([[:digit:]]+)`)
4836 upxVersion := re.FindStringSubmatch(string(out))
4837 if len(upxVersion) != 3 {
4838 t.Errorf("bad upx version string: %s", upxVersion)
4841 major, err1 := strconv.Atoi(upxVersion[1])
4842 minor, err2 := strconv.Atoi(upxVersion[2])
4843 if err1 != nil || err2 != nil {
4844 t.Errorf("bad upx version string: %s", upxVersion[0])
4847 // Anything below 3.94 is known not to work with go binaries
4848 if (major < 3) || (major == 3 && minor < 94) {
4849 t.Skipf("skipping because upx version %v.%v is too old", major, minor)
4855 tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello upx") }`)
4856 src := tg.path("main.go")
4857 obj := tg.path("main")
4858 tg.run("build", "-o", obj, src)
4860 out, err = exec.Command("upx", obj).CombinedOutput()
4862 t.Logf("executing upx\n%s\n", out)
4863 t.Fatalf("upx failed with %v", err)
4866 out, err = exec.Command(obj).CombinedOutput()
4869 t.Fatalf("running compressed go binary failed with error %s", err)
4871 if string(out) != "hello upx" {
4872 t.Fatalf("bad output from compressed go binary:\ngot %q; want %q", out, "hello upx")
4876 func TestGOTMPDIR(t *testing.T) {
4880 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4882 tg.setenv("GOTMPDIR", tg.tempdir)
4883 tg.setenv("GOCACHE", "off")
4885 // complex/x is a trivial non-main package.
4886 tg.run("build", "-work", "-x", "complex/w")
4887 tg.grepStderr("WORK="+regexp.QuoteMeta(tg.tempdir), "did not work in $GOTMPDIR")
4890 func TestBuildCache(t *testing.T) {
4891 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
4892 t.Skip("GODEBUG gocacheverify")
4897 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4899 tg.setenv("GOCACHE", tg.tempdir)
4901 // complex/w is a trivial non-main package.
4902 // It imports nothing, so there should be no Deps.
4903 tg.run("list", "-f={{join .Deps \" \"}}", "complex/w")
4904 tg.grepStdoutNot(".+", "complex/w depends on unexpected packages")
4906 tg.run("build", "-x", "complex/w")
4907 tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler")
4909 tg.run("build", "-x", "complex/w")
4910 tg.grepStderrNot(`[\\/]compile|gccgo`, "ran compiler incorrectly")
4912 tg.run("build", "-a", "-x", "complex/w")
4913 tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler with -a")
4915 // complex is a non-trivial main package.
4916 // the link step should not be cached.
4917 tg.run("build", "-o", os.DevNull, "-x", "complex")
4918 tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
4920 tg.run("build", "-o", os.DevNull, "-x", "complex")
4921 tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
4924 func TestCacheOutput(t *testing.T) {
4925 // Test that command output is cached and replayed too.
4926 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
4927 t.Skip("GODEBUG gocacheverify")
4932 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4934 tg.setenv("GOCACHE", tg.tempdir)
4936 tg.run("build", "-gcflags=-m", "errors")
4937 stdout1 := tg.getStdout()
4938 stderr1 := tg.getStderr()
4940 tg.run("build", "-gcflags=-m", "errors")
4941 stdout2 := tg.getStdout()
4942 stderr2 := tg.getStderr()
4944 if stdout2 != stdout1 || stderr2 != stderr1 {
4945 t.Errorf("cache did not reproduce output:\n\nstdout1:\n%s\n\nstdout2:\n%s\n\nstderr1:\n%s\n\nstderr2:\n%s",
4946 stdout1, stdout2, stderr1, stderr2)
4950 func TestCacheCoverage(t *testing.T) {
4951 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
4952 t.Skip("GODEBUG gocacheverify")
4958 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4961 tg.setenv("GOCACHE", filepath.Join(tg.tempdir, "c1"))
4962 tg.run("test", "-cover", "strings")
4963 tg.run("test", "-cover", "math", "strings")
4966 func TestIssue22588(t *testing.T) {
4967 // Don't get confused by stderr coming from tools.
4972 if _, err := os.Stat("/usr/bin/time"); err != nil {
4976 tg.run("list", "-f={{.Stale}}", "runtime")
4977 tg.run("list", "-toolexec=/usr/bin/time", "-f={{.Stale}}", "runtime")
4978 tg.grepStdout("false", "incorrectly reported runtime as stale")
4981 func TestIssue22531(t *testing.T) {
4982 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
4983 t.Skip("GODEBUG gocacheverify")
4989 tg.setenv("GOPATH", tg.tempdir)
4990 tg.setenv("GOCACHE", filepath.Join(tg.tempdir, "cache"))
4991 tg.tempFile("src/m/main.go", "package main /* c1 */; func main() {}\n")
4992 tg.run("install", "-x", "m")
4993 tg.run("list", "-f", "{{.Stale}}", "m")
4994 tg.grepStdout("false", "reported m as stale after install")
4995 tg.run("tool", "buildid", filepath.Join(tg.tempdir, "bin/m"+exeSuffix))
4997 // The link action ID did not include the full main build ID,
4998 // even though the full main build ID is written into the
4999 // eventual binary. That caused the following install to
5000 // be a no-op, thinking the gofmt binary was up-to-date,
5001 // even though .Stale could see it was not.
5002 tg.tempFile("src/m/main.go", "package main /* c2 */; func main() {}\n")
5003 tg.run("install", "-x", "m")
5004 tg.run("list", "-f", "{{.Stale}}", "m")
5005 tg.grepStdout("false", "reported m as stale after reinstall")
5006 tg.run("tool", "buildid", filepath.Join(tg.tempdir, "bin/m"+exeSuffix))
5009 func TestIssue22596(t *testing.T) {
5010 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5011 t.Skip("GODEBUG gocacheverify")
5017 tg.setenv("GOCACHE", filepath.Join(tg.tempdir, "cache"))
5018 tg.tempFile("gopath1/src/p/p.go", "package p; func F(){}\n")
5019 tg.tempFile("gopath2/src/p/p.go", "package p; func F(){}\n")
5021 tg.setenv("GOPATH", filepath.Join(tg.tempdir, "gopath1"))
5022 tg.run("list", "-f={{.Target}}", "p")
5023 target1 := strings.TrimSpace(tg.getStdout())
5024 tg.run("install", "p")
5025 tg.wantNotStale("p", "", "p stale after install")
5027 tg.setenv("GOPATH", filepath.Join(tg.tempdir, "gopath2"))
5028 tg.run("list", "-f={{.Target}}", "p")
5029 target2 := strings.TrimSpace(tg.getStdout())
5030 tg.must(os.MkdirAll(filepath.Dir(target2), 0777))
5031 tg.must(copyFile(target1, target2, 0666))
5032 tg.wantStale("p", "build ID mismatch", "p not stale after copy from gopath1")
5033 tg.run("install", "p")
5034 tg.wantNotStale("p", "", "p stale after install2")
5037 func TestTestCache(t *testing.T) {
5038 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5039 t.Skip("GODEBUG gocacheverify")
5045 tg.setenv("GOPATH", tg.tempdir)
5046 tg.setenv("GOCACHE", filepath.Join(tg.tempdir, "cache"))
5048 // timeout here should not affect result being cached
5049 // or being retrieved later.
5050 tg.run("test", "-x", "-timeout=10s", "errors")
5051 tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler")
5052 tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
5053 tg.grepStderr(`errors\.test`, "did not run test")
5055 tg.run("test", "-x", "errors")
5056 tg.grepStdout(`ok \terrors\t\(cached\)`, "did not report cached result")
5057 tg.grepStderrNot(`[\\/]compile|gccgo`, "incorrectly ran compiler")
5058 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly ran linker")
5059 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5060 tg.grepStderrNot("DO NOT USE", "poisoned action status leaked")
5062 // Even very low timeouts do not disqualify cached entries.
5063 tg.run("test", "-timeout=1ns", "-x", "errors")
5064 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5066 tg.run("clean", "-testcache")
5067 tg.run("test", "-x", "errors")
5068 tg.grepStderr(`errors\.test`, "did not run test")
5070 // The -p=1 in the commands below just makes the -x output easier to read.
5072 t.Log("\n\nINITIAL\n\n")
5074 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5075 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\nvar X = 1\n")
5076 tg.tempFile("src/t/t1/t1_test.go", "package t\nimport \"testing\"\nfunc Test1(*testing.T) {}\n")
5077 tg.tempFile("src/t/t2/t2_test.go", "package t\nimport _ \"p1\"\nimport \"testing\"\nfunc Test2(*testing.T) {}\n")
5078 tg.tempFile("src/t/t3/t3_test.go", "package t\nimport \"p1\"\nimport \"testing\"\nfunc Test3(t *testing.T) {t.Log(p1.X)}\n")
5079 tg.tempFile("src/t/t4/t4_test.go", "package t\nimport \"p2\"\nimport \"testing\"\nfunc Test4(t *testing.T) {t.Log(p2.X)}")
5080 tg.run("test", "-x", "-v", "-short", "t/...")
5082 t.Log("\n\nREPEAT\n\n")
5084 tg.run("test", "-x", "-v", "-short", "t/...")
5085 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5086 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5087 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5088 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5089 tg.grepStderrNot(`[\\/]compile|gccgo`, "incorrectly ran compiler")
5090 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly ran linker")
5091 tg.grepStderrNot(`p[0-9]\.test`, "incorrectly ran test")
5093 t.Log("\n\nCOMMENT\n\n")
5095 // Changing the program text without affecting the compiled package
5096 // should result in the package being rebuilt but nothing more.
5097 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 01\n")
5098 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5099 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5100 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5101 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5102 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5103 tg.grepStderrNot(`([\\/]compile|gccgo).*t[0-9]_test\.go`, "incorrectly ran compiler")
5104 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly ran linker")
5105 tg.grepStderrNot(`t[0-9]\.test.*test\.short`, "incorrectly ran test")
5107 t.Log("\n\nCHANGE\n\n")
5109 // Changing the actual package should have limited effects.
5110 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 02\n")
5111 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5113 // p2 should have been rebuilt.
5114 tg.grepStderr(`([\\/]compile|gccgo).*p2.go`, "did not recompile p2")
5116 // t1 does not import anything, should not have been rebuilt.
5117 tg.grepStderrNot(`([\\/]compile|gccgo).*t1_test.go`, "incorrectly recompiled t1")
5118 tg.grepStderrNot(`([\\/]link|gccgo).*t1_test`, "incorrectly relinked t1_test")
5119 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t/t1")
5121 // t2 imports p1 and must be rebuilt and relinked,
5122 // but the change should not have any effect on the test binary,
5123 // so the test should not have been rerun.
5124 tg.grepStderr(`([\\/]compile|gccgo).*t2_test.go`, "did not recompile t2")
5125 tg.grepStderr(`([\\/]link|gccgo).*t2\.test`, "did not relink t2_test")
5126 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t/t2")
5128 // t3 imports p1, and changing X changes t3's test binary.
5129 tg.grepStderr(`([\\/]compile|gccgo).*t3_test.go`, "did not recompile t3")
5130 tg.grepStderr(`([\\/]link|gccgo).*t3\.test`, "did not relink t3_test")
5131 tg.grepStderr(`t3\.test.*-test.short`, "did not rerun t3_test")
5132 tg.grepStdoutNot(`ok \tt/t3\t\(cached\)`, "reported cached t3_test result")
5134 // t4 imports p2, but p2 did not change, so t4 should be relinked, not recompiled,
5136 tg.grepStderrNot(`([\\/]compile|gccgo).*t4_test.go`, "incorrectly recompiled t4")
5137 tg.grepStderr(`([\\/]link|gccgo).*t4\.test`, "did not relink t4_test")
5138 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t/t4")
5141 func TestTestVet(t *testing.T) {
5146 tg.tempFile("p1_test.go", `
5149 func Test(t *testing.T) {
5150 t.Logf("%d") // oops
5154 tg.runFail("test", filepath.Join(tg.tempdir, "p1_test.go"))
5155 tg.grepStderr(`Logf format %d`, "did not diagnose bad Logf")
5156 tg.run("test", "-vet=off", filepath.Join(tg.tempdir, "p1_test.go"))
5157 tg.grepStdout(`^ok`, "did not print test summary")
5159 tg.tempFile("p1.go", `
5163 fmt.Printf("%d") // oops
5166 tg.runFail("test", filepath.Join(tg.tempdir, "p1.go"))
5167 tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5168 tg.run("test", "-x", "-vet=shift", filepath.Join(tg.tempdir, "p1.go"))
5169 tg.grepStderr(`[\\/]vet.*-shift`, "did not run vet with -shift")
5170 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5171 tg.run("test", "-vet=off", filepath.Join(tg.tempdir, "p1.go"))
5172 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5174 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5175 tg.run("test", "vetcycle") // must not fail; #22890
5178 func TestInstallDeps(t *testing.T) {
5183 tg.setenv("GOPATH", tg.tempdir)
5185 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5186 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\n")
5187 tg.tempFile("src/main1/main.go", "package main\nimport _ \"p2\"\nfunc main() {}\n")
5189 tg.run("list", "-f={{.Target}}", "p1")
5190 p1 := strings.TrimSpace(tg.getStdout())
5191 tg.run("list", "-f={{.Target}}", "p2")
5192 p2 := strings.TrimSpace(tg.getStdout())
5193 tg.run("list", "-f={{.Target}}", "main1")
5194 main1 := strings.TrimSpace(tg.getStdout())
5196 tg.run("install", "main1")
5202 tg.run("install", "p2")
5206 // don't let install -i overwrite runtime
5207 tg.wantNotStale("runtime", "", "must be non-stale before install -i")
5209 tg.run("install", "-i", "main1")
5211 tg.must(os.Remove(p1))
5213 tg.run("install", "-i", "p2")
5217 func TestFmtLoadErrors(t *testing.T) {
5220 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5221 tg.runFail("fmt", "does-not-exist")
5222 tg.run("fmt", "-n", "exclude")
5225 func TestRelativePkgdir(t *testing.T) {
5229 tg.setenv("GOCACHE", "off")
5232 tg.run("build", "-i", "-pkgdir=.", "runtime")
5235 func TestGcflagsPatterns(t *testing.T) {
5238 tg.setenv("GOPATH", "")
5239 tg.setenv("GOCACHE", "off")
5241 tg.run("build", "-v", "-gcflags= \t\r\n -e", "fmt")
5242 tg.grepStderr("fmt", "did not rebuild fmt")
5243 tg.grepStderrNot("reflect", "incorrectly rebuilt reflect")
5245 tg.run("build", "-v", "-gcflags=-e", "fmt", "reflect")
5246 tg.grepStderr("fmt", "did not rebuild fmt")
5247 tg.grepStderr("reflect", "did not rebuild reflect")
5248 tg.grepStderrNot("runtime", "incorrectly rebuilt runtime")
5250 tg.run("build", "-x", "-v", "-gcflags= \t\r\n reflect \t\r\n = \t\r\n -N", "fmt")
5251 tg.grepStderr("fmt", "did not rebuild fmt")
5252 tg.grepStderr("reflect", "did not rebuild reflect")
5253 tg.grepStderr("compile.* -N .*-p reflect", "did not build reflect with -N flag")
5254 tg.grepStderrNot("compile.* -N .*-p fmt", "incorrectly built fmt with -N flag")
5256 tg.run("test", "-c", "-n", "-gcflags=-N", "strings")
5257 tg.grepStderr("compile.* -N .*compare_test.go", "did not build strings_test package with -N flag")
5259 tg.run("test", "-c", "-n", "-gcflags=strings=-N", "strings")
5260 tg.grepStderr("compile.* -N .*compare_test.go", "did not build strings_test package with -N flag")
5263 func TestGoTestMinusN(t *testing.T) {
5264 // Intent here is to verify that 'go test -n' works without crashing.
5265 // This reuses flag_test.go, but really any test would do.
5268 tg.run("test", "testdata/flag_test.go", "-n", "-args", "-v=7")
5271 func TestGoTestJSON(t *testing.T) {
5276 tg.setenv("GOCACHE", tg.tempdir)
5277 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5279 // It would be nice to test that the output is interlaced
5280 // but it seems to be impossible to do that in a short test
5281 // that isn't also flaky. Just check that we get JSON output.
5282 tg.run("test", "-json", "-short", "-v", "errors", "empty/pkg", "skipper")
5283 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5284 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5286 tg.grepStdout(`"Action":"output","Package":"empty/pkg","Output":".*no test files`, "did not see no test files print")
5287 tg.grepStdout(`"Action":"skip","Package":"empty/pkg"`, "did not see skip")
5289 tg.grepStdout(`"Action":"output","Package":"skipper","Test":"Test","Output":"--- SKIP:`, "did not see SKIP output")
5290 tg.grepStdout(`"Action":"skip","Package":"skipper","Test":"Test"`, "did not see skip result for Test")
5292 tg.run("test", "-json", "-bench=NONE", "-short", "-v", "errors")
5293 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5294 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5296 tg.run("test", "-o", filepath.Join(tg.tempdir, "errors.test.exe"), "-c", "errors")
5297 tg.run("tool", "test2json", "-p", "errors", filepath.Join(tg.tempdir, "errors.test.exe"), "-test.v", "-test.short")
5298 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5299 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5300 tg.grepStdout(`\{"Action":"pass","Package":"errors"\}`, "did not see final pass")
5303 func TestFailFast(t *testing.T) {
5312 {"TestFailingA", true, 1},
5313 {"TestFailing[AB]", true, 1},
5314 {"TestFailing[AB]", false, 2},
5315 // mix with non-failing tests:
5316 {"TestA|TestFailing[AB]", true, 1},
5317 {"TestA|TestFailing[AB]", false, 2},
5318 // mix with parallel tests:
5319 {"TestFailingB|TestParallelFailingA", true, 2},
5320 {"TestFailingB|TestParallelFailingA", false, 2},
5321 {"TestFailingB|TestParallelFailing[AB]", true, 3},
5322 {"TestFailingB|TestParallelFailing[AB]", false, 3},
5323 // mix with parallel sub-tests
5324 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", true, 3},
5325 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", false, 5},
5326 {"TestParallelFailingSubtestsA", true, 1},
5328 {"TestParallelFailing[AB]", false, 2},
5329 // non-parallel subtests:
5330 {"TestFailingSubtestsA", true, 1},
5331 {"TestFailingSubtestsA", false, 2},
5334 for _, tt := range tests {
5335 t.Run(tt.run, func(t *testing.T) {
5336 tg.runFail("test", "./testdata/src/failfast_test.go", "-run="+tt.run, "-failfast="+strconv.FormatBool(tt.failfast))
5338 nfail := strings.Count(tg.getStdout(), "FAIL - ")
5340 if nfail != tt.nfail {
5341 t.Errorf("go test -run=%s -failfast=%t printed %d FAILs, want %d", tt.run, tt.failfast, nfail, tt.nfail)