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.
33 canRun = true // whether we can run go or ./testgo
34 canRace = false // whether we can run the race detector
35 canCgo = false // whether we can use cgo
36 canMSan = false // whether we can run the memory sanitizer
38 exeSuffix string // ".exe" on Windows
40 skipExternal = false // skip external tests
43 func tooSlow(t *testing.T) {
45 // In -short mode; skip test, except run it on the {darwin,linux,windows}/amd64 builders.
46 if testenv.Builder() != "" && runtime.GOARCH == "amd64" && (runtime.GOOS == "linux" || runtime.GOOS == "darwin" || runtime.GOOS == "windows") {
49 t.Skip("skipping test in -short mode")
55 case "android", "js", "nacl":
58 switch runtime.GOARCH {
63 switch runtime.GOARCH {
65 // many linux/arm machines are too slow to run
66 // the full set of external tests.
68 case "mips", "mipsle", "mips64", "mips64le":
71 if testenv.Builder() != "" {
72 // On the builders, skip the cmd/go
73 // tests. They're too slow and already
74 // covered by other ports. There's
75 // nothing os/arch specific in the
81 switch runtime.GOARCH {
83 // many freebsd/arm machines are too slow to run
84 // the full set of external tests.
89 switch runtime.GOARCH {
91 // many plan9/arm machines are too slow to run
92 // the full set of external tests.
100 // testGOROOT is the GOROOT to use when running testgo, a cmd/go binary
101 // build from this process's current GOROOT, but run from a different
103 var testGOROOT string
106 var testGOCACHE string
109 var testTmpDir string
112 // testCtx is canceled when the test binary is about to time out.
114 // If https://golang.org/issue/28135 is accepted, uses of this variable in test
115 // functions should be replaced by t.Context().
116 var testCtx = context.Background()
118 // The TestMain function creates a go command for testing purposes and
119 // deletes it after the tests have been run.
120 func TestMain(m *testing.M) {
121 if os.Getenv("GO_GCFLAGS") != "" {
122 fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
123 fmt.Printf("cmd/go test is not compatible with $GO_GCFLAGS being set\n")
127 os.Unsetenv("GOROOT_FINAL")
131 timeoutFlag := flag.Lookup("test.timeout")
132 if timeoutFlag != nil {
133 // TODO(golang.org/issue/28147): The go command does not pass the
134 // test.timeout flag unless either -timeout or -test.timeout is explicitly
135 // set on the command line.
136 if d := timeoutFlag.Value.(flag.Getter).Get().(time.Duration); d != 0 {
137 aBitShorter := d * 95 / 100
138 var cancel context.CancelFunc
139 testCtx, cancel = context.WithTimeout(testCtx, aBitShorter)
144 if *proxyAddr != "" {
149 dir, err := ioutil.TempDir(os.Getenv("GOTMPDIR"), "cmd-go-test-")
155 defer removeAll(testTmpDir)
159 testBin = filepath.Join(testTmpDir, "testbin")
160 if err := os.Mkdir(testBin, 0777); err != nil {
163 testGo = filepath.Join(testBin, "go"+exeSuffix)
164 args := []string{"build", "-tags", "testgo", "-o", testGo}
166 args = append(args, "-race")
168 gotool, err := testenv.GoTool()
170 fmt.Fprintln(os.Stderr, err)
174 goEnv := func(name string) string {
175 out, err := exec.Command(gotool, "env", name).CombinedOutput()
177 fmt.Fprintf(os.Stderr, "go env %s: %v\n%s", name, err, out)
180 return strings.TrimSpace(string(out))
182 testGOROOT = goEnv("GOROOT")
184 // The whole GOROOT/pkg tree was installed using the GOHOSTOS/GOHOSTARCH
185 // toolchain (installed in GOROOT/pkg/tool/GOHOSTOS_GOHOSTARCH).
186 // The testgo.exe we are about to create will be built for GOOS/GOARCH,
187 // which means it will use the GOOS/GOARCH toolchain
188 // (installed in GOROOT/pkg/tool/GOOS_GOARCH).
189 // If these are not the same toolchain, then the entire standard library
190 // will look out of date (the compilers in those two different tool directories
191 // are built for different architectures and have different buid IDs),
192 // which will cause many tests to do unnecessary rebuilds and some
193 // tests to attempt to overwrite the installed standard library.
194 // Bail out entirely in this case.
195 hostGOOS := goEnv("GOHOSTOS")
196 hostGOARCH := goEnv("GOHOSTARCH")
197 if hostGOOS != runtime.GOOS || hostGOARCH != runtime.GOARCH {
198 fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
199 fmt.Printf("cmd/go test is not compatible with GOOS/GOARCH != GOHOSTOS/GOHOSTARCH (%s/%s != %s/%s)\n", runtime.GOOS, runtime.GOARCH, hostGOOS, hostGOARCH)
204 out, err := exec.Command(gotool, args...).CombinedOutput()
206 fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out)
210 out, err = exec.Command(gotool, "env", "CC").CombinedOutput()
212 fmt.Fprintf(os.Stderr, "could not find testing CC: %v\n%s", err, out)
215 testCC = strings.TrimSpace(string(out))
217 if out, err := exec.Command(testGo, "env", "CGO_ENABLED").Output(); err != nil {
218 fmt.Fprintf(os.Stderr, "running testgo failed: %v\n", err)
221 canCgo, err = strconv.ParseBool(strings.TrimSpace(string(out)))
223 fmt.Fprintf(os.Stderr, "can't parse go env CGO_ENABLED output: %v\n", strings.TrimSpace(string(out)))
227 out, err = exec.Command(gotool, "env", "GOCACHE").CombinedOutput()
229 fmt.Fprintf(os.Stderr, "could not find testing GOCACHE: %v\n%s", err, out)
232 testGOCACHE = strings.TrimSpace(string(out))
234 canMSan = canCgo && sys.MSanSupported(runtime.GOOS, runtime.GOARCH)
235 canRace = canCgo && sys.RaceDetectorSupported(runtime.GOOS, runtime.GOARCH)
236 // The race detector doesn't work on Alpine Linux:
237 // golang.org/issue/14481
238 // gccgo does not support the race detector.
239 if isAlpineLinux() || runtime.Compiler == "gccgo" {
243 // Don't let these environment variables confuse the test.
245 os.Unsetenv("GOPATH")
246 os.Unsetenv("GIT_ALLOW_PROTOCOL")
247 os.Setenv("HOME", "/test-go-home-does-not-exist")
248 // On some systems the default C compiler is ccache.
249 // Setting HOME to a non-existent directory will break
250 // those systems. Disable ccache and use real compiler. Issue 17668.
251 os.Setenv("CCACHE_DISABLE", "1")
252 if os.Getenv("GOCACHE") == "" {
253 os.Setenv("GOCACHE", testGOCACHE) // because $HOME is gone
258 removeAll(testTmpDir) // os.Exit won't run defer
264 func isAlpineLinux() bool {
265 if runtime.GOOS != "linux" {
268 fi, err := os.Lstat("/etc/alpine-release")
269 return err == nil && fi.Mode().IsRegular()
272 // The length of an mtime tick on this system. This is an estimate of
273 // how long we need to sleep to ensure that the mtime of two files is
275 // We used to try to be clever but that didn't always work (see golang.org/issue/12205).
276 var mtimeTick time.Duration = 1 * time.Second
278 // Manage a single run of the testgo binary.
279 type testgoData struct {
287 stdout, stderr bytes.Buffer
288 execDir string // dir for tg.run
291 // skipIfGccgo skips the test if using gccgo.
292 func skipIfGccgo(t *testing.T, msg string) {
293 if runtime.Compiler == "gccgo" {
294 t.Skipf("skipping test not supported on gccgo: %s", msg)
298 // testgo sets up for a test that runs testgo.
299 func testgo(t *testing.T) *testgoData {
301 testenv.MustHaveGoBuild(t)
304 t.Skipf("skipping external tests on %s/%s", runtime.GOOS, runtime.GOARCH)
307 return &testgoData{t: t}
310 // must gives a fatal error if err is not nil.
311 func (tg *testgoData) must(err error) {
318 // check gives a test non-fatal error if err is not nil.
319 func (tg *testgoData) check(err error) {
326 // parallel runs the test in parallel by calling t.Parallel.
327 func (tg *testgoData) parallel() {
330 tg.t.Fatal("internal testsuite error: call to parallel after run")
333 tg.t.Fatal("internal testsuite error: call to parallel after cd")
335 for _, e := range tg.env {
336 if strings.HasPrefix(e, "GOROOT=") || strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
337 val := e[strings.Index(e, "=")+1:]
338 if strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata") {
339 tg.t.Fatalf("internal testsuite error: call to parallel with testdata in environment (%s)", e)
347 // pwd returns the current directory.
348 func (tg *testgoData) pwd() string {
350 wd, err := os.Getwd()
352 tg.t.Fatalf("could not get working directory: %v", err)
357 // cd changes the current directory to the named directory. Note that
358 // using this means that the test must not be run in parallel with any
360 func (tg *testgoData) cd(dir string) {
363 tg.t.Fatal("internal testsuite error: changing directory when running in parallel")
368 abs, err := filepath.Abs(dir)
369 tg.must(os.Chdir(dir))
371 tg.setenv("PWD", abs)
375 // sleep sleeps for one tick, where a tick is a conservative estimate
376 // of how long it takes for a file modification to get a different
378 func (tg *testgoData) sleep() {
379 time.Sleep(mtimeTick)
382 // setenv sets an environment variable to use when running the test go
384 func (tg *testgoData) setenv(name, val string) {
386 if tg.inParallel && (name == "GOROOT" || name == "GOPATH" || name == "GOBIN") && (strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata")) {
387 tg.t.Fatalf("internal testsuite error: call to setenv with testdata (%s=%s) after parallel", name, val)
390 tg.env = append(tg.env, name+"="+val)
393 // unsetenv removes an environment variable.
394 func (tg *testgoData) unsetenv(name string) {
396 tg.env = append([]string(nil), os.Environ()...)
397 tg.env = append(tg.env, "GO111MODULE=off")
399 for i, v := range tg.env {
400 if strings.HasPrefix(v, name+"=") {
401 tg.env = append(tg.env[:i], tg.env[i+1:]...)
407 func (tg *testgoData) goTool() string {
411 // doRun runs the test go command, recording stdout and stderr and
412 // returning exit status.
413 func (tg *testgoData) doRun(args []string) error {
416 panic("testgoData.doRun called but canRun false")
419 for _, arg := range args {
420 if strings.HasPrefix(arg, "testdata") || strings.HasPrefix(arg, "./testdata") {
421 tg.t.Fatal("internal testsuite error: parallel run using testdata")
427 for _, v := range tg.env {
428 if strings.HasPrefix(v, "GOROOT=") {
435 tg.setenv("GOROOT", testGOROOT)
438 tg.t.Logf("running testgo %v", args)
439 cmd := exec.Command(prog, args...)
443 cmd.Stdout = &tg.stdout
444 cmd.Stderr = &tg.stderr
447 if tg.stdout.Len() > 0 {
448 tg.t.Log("standard output:")
449 tg.t.Log(tg.stdout.String())
451 if tg.stderr.Len() > 0 {
452 tg.t.Log("standard error:")
453 tg.t.Log(tg.stderr.String())
459 // run runs the test go command, and expects it to succeed.
460 func (tg *testgoData) run(args ...string) {
462 if status := tg.doRun(args); status != nil {
464 tg.t.Logf("go %v failed unexpectedly in %s: %v", args, wd, status)
469 // runFail runs the test go command, and expects it to fail.
470 func (tg *testgoData) runFail(args ...string) {
472 if status := tg.doRun(args); status == nil {
473 tg.t.Fatal("testgo succeeded unexpectedly")
475 tg.t.Log("testgo failed as expected:", status)
479 // runGit runs a git command, and expects it to succeed.
480 func (tg *testgoData) runGit(dir string, args ...string) {
482 cmd := exec.Command("git", args...)
485 cmd.Stdout = &tg.stdout
486 cmd.Stderr = &tg.stderr
490 if tg.stdout.Len() > 0 {
491 tg.t.Log("git standard output:")
492 tg.t.Log(tg.stdout.String())
494 if tg.stderr.Len() > 0 {
495 tg.t.Log("git standard error:")
496 tg.t.Log(tg.stderr.String())
499 tg.t.Logf("git %v failed unexpectedly: %v", args, status)
504 // getStdout returns standard output of the testgo run as a string.
505 func (tg *testgoData) getStdout() string {
508 tg.t.Fatal("internal testsuite error: stdout called before run")
510 return tg.stdout.String()
513 // getStderr returns standard error of the testgo run as a string.
514 func (tg *testgoData) getStderr() string {
517 tg.t.Fatal("internal testsuite error: stdout called before run")
519 return tg.stderr.String()
522 // doGrepMatch looks for a regular expression in a buffer, and returns
523 // whether it is found. The regular expression is matched against
524 // each line separately, as with the grep command.
525 func (tg *testgoData) doGrepMatch(match string, b *bytes.Buffer) bool {
528 tg.t.Fatal("internal testsuite error: grep called before run")
530 re := regexp.MustCompile(match)
531 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
539 // doGrep looks for a regular expression in a buffer and fails if it
540 // is not found. The name argument is the name of the output we are
541 // searching, "output" or "error". The msg argument is logged on
543 func (tg *testgoData) doGrep(match string, b *bytes.Buffer, name, msg string) {
545 if !tg.doGrepMatch(match, b) {
547 tg.t.Logf("pattern %v not found in standard %s", match, name)
552 // grepStdout looks for a regular expression in the test run's
553 // standard output and fails, logging msg, if it is not found.
554 func (tg *testgoData) grepStdout(match, msg string) {
556 tg.doGrep(match, &tg.stdout, "output", msg)
559 // grepStderr looks for a regular expression in the test run's
560 // standard error and fails, logging msg, if it is not found.
561 func (tg *testgoData) grepStderr(match, msg string) {
563 tg.doGrep(match, &tg.stderr, "error", msg)
566 // grepBoth looks for a regular expression in the test run's standard
567 // output or stand error and fails, logging msg, if it is not found.
568 func (tg *testgoData) grepBoth(match, msg string) {
570 if !tg.doGrepMatch(match, &tg.stdout) && !tg.doGrepMatch(match, &tg.stderr) {
572 tg.t.Logf("pattern %v not found in standard output or standard error", match)
577 // doGrepNot looks for a regular expression in a buffer and fails if
578 // it is found. The name and msg arguments are as for doGrep.
579 func (tg *testgoData) doGrepNot(match string, b *bytes.Buffer, name, msg string) {
581 if tg.doGrepMatch(match, b) {
583 tg.t.Logf("pattern %v found unexpectedly in standard %s", match, name)
588 // grepStdoutNot looks for a regular expression in the test run's
589 // standard output and fails, logging msg, if it is found.
590 func (tg *testgoData) grepStdoutNot(match, msg string) {
592 tg.doGrepNot(match, &tg.stdout, "output", msg)
595 // grepStderrNot looks for a regular expression in the test run's
596 // standard error and fails, logging msg, if it is found.
597 func (tg *testgoData) grepStderrNot(match, msg string) {
599 tg.doGrepNot(match, &tg.stderr, "error", msg)
602 // grepBothNot looks for a regular expression in the test run's
603 // standard output or stand error and fails, logging msg, if it is
605 func (tg *testgoData) grepBothNot(match, msg string) {
607 if tg.doGrepMatch(match, &tg.stdout) || tg.doGrepMatch(match, &tg.stderr) {
609 tg.t.Fatalf("pattern %v found unexpectedly in standard output or standard error", match)
613 // doGrepCount counts the number of times a regexp is seen in a buffer.
614 func (tg *testgoData) doGrepCount(match string, b *bytes.Buffer) int {
617 tg.t.Fatal("internal testsuite error: doGrepCount called before run")
619 re := regexp.MustCompile(match)
621 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
629 // grepCountBoth returns the number of times a regexp is seen in both
630 // standard output and standard error.
631 func (tg *testgoData) grepCountBoth(match string) int {
633 return tg.doGrepCount(match, &tg.stdout) + tg.doGrepCount(match, &tg.stderr)
636 // creatingTemp records that the test plans to create a temporary file
637 // or directory. If the file or directory exists already, it will be
638 // removed. When the test completes, the file or directory will be
639 // removed if it exists.
640 func (tg *testgoData) creatingTemp(path string) {
642 if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) {
643 tg.t.Fatalf("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path)
645 // If we have changed the working directory, make sure we have
646 // an absolute path, because we are going to change directory
647 // back before we remove the temporary.
648 if tg.wd != "" && !filepath.IsAbs(path) {
649 path = filepath.Join(tg.pwd(), path)
651 tg.must(os.RemoveAll(path))
652 tg.temps = append(tg.temps, path)
655 // makeTempdir makes a temporary directory for a run of testgo. If
656 // the temporary directory was already created, this does nothing.
657 func (tg *testgoData) makeTempdir() {
659 if tg.tempdir == "" {
661 tg.tempdir, err = ioutil.TempDir("", "gotest")
666 // tempFile adds a temporary file for a run of testgo.
667 func (tg *testgoData) tempFile(path, contents string) {
670 tg.must(os.MkdirAll(filepath.Join(tg.tempdir, filepath.Dir(path)), 0755))
671 bytes := []byte(contents)
672 if strings.HasSuffix(path, ".go") {
673 formatted, err := format.Source(bytes)
678 tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644))
681 // tempDir adds a temporary directory for a run of testgo.
682 func (tg *testgoData) tempDir(path string) {
685 if err := os.MkdirAll(filepath.Join(tg.tempdir, path), 0755); err != nil && !os.IsExist(err) {
690 // path returns the absolute pathname to file with the temporary
692 func (tg *testgoData) path(name string) string {
694 if tg.tempdir == "" {
695 tg.t.Fatalf("internal testsuite error: path(%q) with no tempdir", name)
700 return filepath.Join(tg.tempdir, name)
703 // mustExist fails if path does not exist.
704 func (tg *testgoData) mustExist(path string) {
706 if _, err := os.Stat(path); err != nil {
707 if os.IsNotExist(err) {
708 tg.t.Fatalf("%s does not exist but should", path)
710 tg.t.Fatalf("%s stat failed: %v", path, err)
714 // mustNotExist fails if path exists.
715 func (tg *testgoData) mustNotExist(path string) {
717 if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
718 tg.t.Fatalf("%s exists but should not (%v)", path, err)
722 // mustHaveContent succeeds if filePath is a path to a file,
723 // and that file is readable and not empty.
724 func (tg *testgoData) mustHaveContent(filePath string) {
725 tg.mustExist(filePath)
726 f, err := os.Stat(filePath)
731 tg.t.Fatalf("expected %s to have data, but is empty", filePath)
735 // wantExecutable fails with msg if path is not executable.
736 func (tg *testgoData) wantExecutable(path, msg string) {
738 if st, err := os.Stat(path); err != nil {
739 if !os.IsNotExist(err) {
744 if runtime.GOOS != "windows" && st.Mode()&0111 == 0 {
745 tg.t.Fatalf("binary %s exists but is not executable", path)
750 // wantArchive fails if path is not an archive.
751 func (tg *testgoData) wantArchive(path string) {
753 f, err := os.Open(path)
757 buf := make([]byte, 100)
760 if !bytes.HasPrefix(buf, []byte("!<arch>\n")) {
761 tg.t.Fatalf("file %s exists but is not an archive", path)
765 // isStale reports whether pkg is stale, and why
766 func (tg *testgoData) isStale(pkg string) (bool, string) {
768 tg.run("list", "-f", "{{.Stale}}:{{.StaleReason}}", pkg)
769 v := strings.TrimSpace(tg.getStdout())
770 f := strings.SplitN(v, ":", 2)
779 tg.t.Fatalf("unexpected output checking staleness of package %v: %v", pkg, v)
783 // wantStale fails with msg if pkg is not stale.
784 func (tg *testgoData) wantStale(pkg, reason, msg string) {
786 stale, why := tg.isStale(pkg)
790 // We always accept the reason as being "not installed but
791 // available in build cache", because when that is the case go
792 // list doesn't try to sort out the underlying reason why the
793 // package is not installed.
794 if reason == "" && why != "" || !strings.Contains(why, reason) && !strings.Contains(why, "not installed but available in build cache") {
795 tg.t.Errorf("wrong reason for Stale=true: %q, want %q", why, reason)
799 // wantNotStale fails with msg if pkg is stale.
800 func (tg *testgoData) wantNotStale(pkg, reason, msg string) {
802 stale, why := tg.isStale(pkg)
806 if reason == "" && why != "" || !strings.Contains(why, reason) {
807 tg.t.Errorf("wrong reason for Stale=false: %q, want %q", why, reason)
811 // If -testwork is specified, the test prints the name of the temp directory
812 // and does not remove it when done, so that a programmer can
813 // poke at the test file tree afterward.
814 var testWork = flag.Bool("testwork", false, "")
816 // cleanup cleans up a test that runs testgo.
817 func (tg *testgoData) cleanup() {
821 tg.t.Logf("ended in %s", wd)
823 if err := os.Chdir(tg.wd); err != nil {
824 // We are unlikely to be able to continue.
825 fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err)
830 tg.t.Logf("TESTWORK=%s\n", tg.path("."))
833 for _, path := range tg.temps {
834 tg.check(removeAll(path))
836 if tg.tempdir != "" {
837 tg.check(removeAll(tg.tempdir))
841 func removeAll(dir string) error {
842 // module cache has 0444 directories;
843 // make them writable in order to remove content.
844 filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
846 return nil // ignore errors walking in file system
853 return os.RemoveAll(dir)
856 // failSSH puts an ssh executable in the PATH that always fails.
857 // This is to stub out uses of ssh by go get.
858 func (tg *testgoData) failSSH() {
860 wd, err := os.Getwd()
864 fail := filepath.Join(wd, "testdata/failssh")
865 tg.setenv("PATH", fmt.Sprintf("%v%c%v", fail, filepath.ListSeparator, os.Getenv("PATH")))
868 func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) {
870 t.Skip("skipping lengthy test in short mode")
876 // Copy the runtime packages into a temporary GOROOT
877 // so that we can change files.
878 for _, copydir := range []string{
880 "src/internal/bytealg",
883 filepath.Join("pkg", runtime.GOOS+"_"+runtime.GOARCH),
884 filepath.Join("pkg/tool", runtime.GOOS+"_"+runtime.GOARCH),
887 srcdir := filepath.Join(testGOROOT, copydir)
888 tg.tempDir(filepath.Join("goroot", copydir))
889 err := filepath.Walk(srcdir,
890 func(path string, info os.FileInfo, err error) error {
897 srcrel, err := filepath.Rel(srcdir, path)
901 dest := filepath.Join("goroot", copydir, srcrel)
902 data, err := ioutil.ReadFile(path)
906 tg.tempFile(dest, string(data))
907 if err := os.Chmod(tg.path(dest), info.Mode()); err != nil {
916 tg.setenv("GOROOT", tg.path("goroot"))
918 addVar := func(name string, idx int) (restore func()) {
919 data, err := ioutil.ReadFile(name)
924 data = append(data, fmt.Sprintf("var DummyUnusedVar%d bool\n", idx)...)
925 if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil {
930 if err := ioutil.WriteFile(name, old, 0666); err != nil {
936 // Every main package depends on the "runtime".
937 tg.tempFile("d1/src/p1/p1.go", `package main; func main(){}`)
938 tg.setenv("GOPATH", tg.path("d1"))
939 // Pass -i flag to rebuild everything outdated.
940 tg.run("install", "-i", "p1")
941 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, before any changes")
943 // Changing mtime of runtime/internal/sys/sys.go
944 // should have no effect: only the content matters.
945 // In fact this should be true even outside a release branch.
946 sys := tg.path("goroot/src/runtime/internal/sys/sys.go")
948 restore := addVar(sys, 0)
950 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after updating mtime of runtime/internal/sys/sys.go")
952 // But changing content of any file should have an effect.
953 // Previously zversion.go was the only one that mattered;
954 // now they all matter, so keep using sys.go.
955 restore = addVar(sys, 1)
957 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go")
959 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after changing back to old release")
961 tg.wantStale("p1", "stale dependency: runtime", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go again")
962 tg.run("install", "-i", "p1")
963 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with new release")
965 // Restore to "old" release.
967 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after restoring sys.go")
968 tg.run("install", "-i", "p1")
969 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release")
972 func testLocalRun(tg *testgoData, exepath, local, match string) {
974 out, err := exec.Command(exepath).Output()
976 tg.t.Fatalf("error running %v: %v", exepath, err)
978 if !regexp.MustCompile(match).Match(out) {
979 tg.t.Log(string(out))
980 tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local)
984 func testLocalEasy(tg *testgoData, local string) {
986 exepath := "./easy" + exeSuffix
987 tg.creatingTemp(exepath)
988 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go"))
989 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
992 func testLocalEasySub(tg *testgoData, local string) {
994 exepath := "./easysub" + exeSuffix
995 tg.creatingTemp(exepath)
996 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go"))
997 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1000 func testLocalHard(tg *testgoData, local string) {
1002 exepath := "./hard" + exeSuffix
1003 tg.creatingTemp(exepath)
1004 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go"))
1005 testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`)
1008 func testLocalInstall(tg *testgoData, local string) {
1010 tg.runFail("install", filepath.Join("testdata", local, "easy.go"))
1013 func TestLocalImportsEasy(t *testing.T) {
1016 testLocalEasy(tg, "local")
1019 func TestLocalImportsEasySub(t *testing.T) {
1022 testLocalEasySub(tg, "local")
1025 func TestLocalImportsHard(t *testing.T) {
1028 testLocalHard(tg, "local")
1031 func TestLocalImportsGoInstallShouldFail(t *testing.T) {
1034 testLocalInstall(tg, "local")
1037 const badDirName = `#$%:, &()*;<=>?\^{}`
1039 func copyBad(tg *testgoData) {
1041 if runtime.GOOS == "windows" {
1042 tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName)
1045 tg.must(filepath.Walk("testdata/local",
1046 func(path string, info os.FileInfo, err error) error {
1054 data, err = ioutil.ReadFile(path)
1058 newpath := strings.Replace(path, "local", badDirName, 1)
1059 tg.tempFile(newpath, string(data))
1065 func TestBadImportsEasy(t *testing.T) {
1068 // TODO: tg.parallel()
1070 testLocalEasy(tg, badDirName)
1073 func TestBadImportsEasySub(t *testing.T) {
1077 testLocalEasySub(tg, badDirName)
1080 func TestBadImportsHard(t *testing.T) {
1084 testLocalHard(tg, badDirName)
1087 func TestBadImportsGoInstallShouldFail(t *testing.T) {
1091 testLocalInstall(tg, badDirName)
1094 func TestInternalPackagesInGOROOTAreRespected(t *testing.T) {
1095 skipIfGccgo(t, "gccgo does not have GOROOT")
1098 tg.runFail("build", "-v", "./testdata/testinternal")
1099 tg.grepBoth(`testinternal(\/|\\)p\.go\:3\:8\: use of internal package net/http/internal not allowed`, "wrong error message for testdata/testinternal")
1102 func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) {
1105 tg.runFail("build", "-v", "./testdata/testinternal2")
1106 tg.grepBoth(`testinternal2(\/|\\)p\.go\:3\:8\: use of internal package .*internal/w not allowed`, "wrote error message for testdata/testinternal2")
1109 func TestRunInternal(t *testing.T) {
1112 dir := filepath.Join(tg.pwd(), "testdata")
1113 tg.setenv("GOPATH", dir)
1114 tg.run("run", filepath.Join(dir, "src/run/good.go"))
1115 tg.runFail("run", filepath.Join(dir, "src/run/bad.go"))
1116 tg.grepStderr(`testdata(\/|\\)src(\/|\\)run(\/|\\)bad\.go\:3\:8\: use of internal package run/subdir/internal/private not allowed`, "unexpected error for run/bad.go")
1119 func TestRunPkg(t *testing.T) {
1122 dir := filepath.Join(tg.pwd(), "testdata")
1123 tg.setenv("GOPATH", dir)
1124 tg.run("run", "hello")
1125 tg.grepStderr("hello, world", "did not find hello, world")
1126 tg.cd(filepath.Join(dir, "src/hello"))
1128 tg.grepStderr("hello, world", "did not find hello, world")
1131 func testMove(t *testing.T, vcs, url, base, config string) {
1132 testenv.MustHaveExternalNetwork(t)
1138 tg.must(os.Mkdir(tg.path(".hg"), 0700))
1139 tg.must(ioutil.WriteFile(filepath.Join(tg.path(".hg"), "hgrc"), nil, 0600))
1140 tg.setenv("GOPATH", tg.path("."))
1141 tg.run("get", "-d", url)
1142 tg.run("get", "-d", "-u", url)
1145 // SVN doesn't believe in text files so we can't just edit the config.
1146 // Check out a different repo into the wrong place.
1147 tg.must(os.RemoveAll(tg.path("src/code.google.com/p/rsc-svn")))
1148 tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk")
1149 tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn")))
1151 path := tg.path(filepath.Join("src", config))
1152 data, err := ioutil.ReadFile(path)
1154 data = bytes.ReplaceAll(data, []byte(base), []byte(base+"XXX"))
1155 tg.must(ioutil.WriteFile(path, data, 0644))
1158 // git will ask for a username and password when we
1159 // run go get -d -f -u. An empty username and
1160 // password will work. Prevent asking by setting
1162 tg.creatingTemp("sink" + exeSuffix)
1163 tg.tempFile("src/sink/sink.go", `package main; func main() {}`)
1164 tg.run("build", "-o", "sink"+exeSuffix, "sink")
1165 tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix))
1167 tg.runFail("get", "-d", "-u", url)
1168 tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason")
1169 tg.runFail("get", "-d", "-f", "-u", url)
1170 tg.grepStderr("validating server certificate|[nN]ot [fF]ound", "go get -d -f -u "+url+" failed for wrong reason")
1173 func TestInternalPackageErrorsAreHandled(t *testing.T) {
1176 tg.run("list", "./testdata/testinternal3")
1179 func TestInternalCache(t *testing.T) {
1182 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4"))
1183 tg.runFail("build", "p")
1184 tg.grepStderr("internal", "did not fail to build p")
1187 func TestMoveGit(t *testing.T) {
1188 testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config")
1191 func TestMoveHG(t *testing.T) {
1192 testMove(t, "hg", "vcs-test.golang.org/go/custom-hg-hello", "custom-hg-hello", "vcs-test.golang.org/go/custom-hg-hello/.hg/hgrc")
1195 // TODO(rsc): Set up a test case on SourceForge (?) for svn.
1196 // func testMoveSVN(t *testing.T) {
1197 // testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-")
1200 func TestImportCommandMatch(t *testing.T) {
1203 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1204 tg.run("build", "./testdata/importcom/works.go")
1207 func TestImportCommentMismatch(t *testing.T) {
1210 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1211 tg.runFail("build", "./testdata/importcom/wrongplace.go")
1212 tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import")
1215 func TestImportCommentSyntaxError(t *testing.T) {
1218 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1219 tg.runFail("build", "./testdata/importcom/bad.go")
1220 tg.grepStderr("cannot parse import comment", "go build did not mention syntax error")
1223 func TestImportCommentConflict(t *testing.T) {
1226 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1227 tg.runFail("build", "./testdata/importcom/conflict.go")
1228 tg.grepStderr("found import comments", "go build did not mention comment conflict")
1231 func TestImportCycle(t *testing.T) {
1235 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcycle"))
1236 tg.runFail("build", "selfimport")
1238 count := tg.grepCountBoth("import cycle not allowed")
1240 t.Fatal("go build did not mention cyclical import")
1243 t.Fatal("go build mentioned import cycle more than once")
1246 // Don't hang forever.
1247 tg.run("list", "-e", "-json", "selfimport")
1250 // cmd/go: custom import path checking should not apply to Go packages without import comment.
1251 func TestIssue10952(t *testing.T) {
1252 testenv.MustHaveExternalNetwork(t)
1253 if _, err := exec.LookPath("git"); err != nil {
1254 t.Skip("skipping because git binary not found")
1261 tg.setenv("GOPATH", tg.path("."))
1262 const importPath = "github.com/zombiezen/go-get-issue-10952"
1263 tg.run("get", "-d", "-u", importPath)
1264 repoDir := tg.path("src/" + importPath)
1265 tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git")
1266 tg.run("get", "-d", "-u", importPath)
1269 func TestIssue16471(t *testing.T) {
1270 testenv.MustHaveExternalNetwork(t)
1271 if _, err := exec.LookPath("git"); err != nil {
1272 t.Skip("skipping because git binary not found")
1279 tg.setenv("GOPATH", tg.path("."))
1280 tg.must(os.MkdirAll(tg.path("src/rsc.io/go-get-issue-10952"), 0755))
1281 tg.runGit(tg.path("src/rsc.io"), "clone", "https://github.com/zombiezen/go-get-issue-10952")
1282 tg.runFail("get", "-u", "rsc.io/go-get-issue-10952")
1283 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")
1286 // Test git clone URL that uses SCP-like syntax and custom import path checking.
1287 func TestIssue11457(t *testing.T) {
1288 testenv.MustHaveExternalNetwork(t)
1289 if _, err := exec.LookPath("git"); err != nil {
1290 t.Skip("skipping because git binary not found")
1297 tg.setenv("GOPATH", tg.path("."))
1298 const importPath = "rsc.io/go-get-issue-11457"
1299 tg.run("get", "-d", "-u", importPath)
1300 repoDir := tg.path("src/" + importPath)
1301 tg.runGit(repoDir, "remote", "set-url", "origin", "git@github.com:rsc/go-get-issue-11457")
1303 // At this time, custom import path checking compares remotes verbatim (rather than
1304 // just the host and path, skipping scheme and user), so we expect go get -u to fail.
1305 // However, the goal of this test is to verify that gitRemoteRepo correctly parsed
1306 // the SCP-like syntax, and we expect it to appear in the error message.
1307 tg.runFail("get", "-d", "-u", importPath)
1308 want := " is checked out from ssh://git@github.com/rsc/go-get-issue-11457"
1309 if !strings.HasSuffix(strings.TrimSpace(tg.getStderr()), want) {
1310 t.Error("expected clone URL to appear in stderr")
1314 func TestGetGitDefaultBranch(t *testing.T) {
1315 testenv.MustHaveExternalNetwork(t)
1316 if _, err := exec.LookPath("git"); err != nil {
1317 t.Skip("skipping because git binary not found")
1324 tg.setenv("GOPATH", tg.path("."))
1326 // This repo has two branches, master and another-branch.
1327 // The another-branch is the default that you get from 'git clone'.
1328 // The go get command variants should not override this.
1329 const importPath = "github.com/rsc/go-get-default-branch"
1331 tg.run("get", "-d", importPath)
1332 repoDir := tg.path("src/" + importPath)
1333 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1334 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1336 tg.run("get", "-d", "-u", importPath)
1337 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1338 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1341 // Security issue. Don't disable. See golang.org/issue/22125.
1342 func TestAccidentalGitCheckout(t *testing.T) {
1343 testenv.MustHaveExternalNetwork(t)
1344 if _, err := exec.LookPath("git"); err != nil {
1345 t.Skip("skipping because git binary not found")
1353 tg.setenv("GOPATH", tg.path("."))
1355 tg.runFail("get", "-u", "vcs-test.golang.org/go/test1-svn-git")
1356 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1358 if _, err := os.Stat(tg.path("SrC")); err == nil {
1359 // This case only triggers on a case-insensitive file system.
1360 tg.runFail("get", "-u", "vcs-test.golang.org/go/test2-svn-git/test2main")
1361 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1365 func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) {
1368 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1369 tg.runFail("test", "syntaxerror")
1370 tg.grepStderr("x_test.go:", "did not diagnose error")
1371 tg.grepStdout("FAIL", "go test did not say FAIL")
1374 func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) {
1377 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1378 tg.runFail("list", "...")
1379 tg.grepBoth("badpkg", "go list ... failure does not mention badpkg")
1380 tg.run("list", "m...")
1383 func TestRelativeImportsGoTest(t *testing.T) {
1386 tg.run("test", "./testdata/testimport")
1389 func TestRelativeImportsGoTestDashI(t *testing.T) {
1393 // don't let test -i overwrite runtime
1394 tg.wantNotStale("runtime", "", "must be non-stale before test -i")
1396 tg.run("test", "-i", "./testdata/testimport")
1399 func TestRelativeImportsInCommandLinePackage(t *testing.T) {
1402 // TODO: tg.parallel()
1403 files, err := filepath.Glob("./testdata/testimport/*.go")
1405 tg.run(append([]string{"test"}, files...)...)
1408 func TestNonCanonicalImportPaths(t *testing.T) {
1412 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1413 tg.runFail("build", "canonical/d")
1414 tg.grepStderr("package canonical/d", "did not report canonical/d")
1415 tg.grepStderr("imports canonical/b", "did not report canonical/b")
1416 tg.grepStderr("imports canonical/a/: non-canonical", "did not report canonical/a/")
1419 func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) {
1422 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1"))
1423 tg.runFail("get", "-u", "foo")
1425 // TODO(iant): We should not have to use strconv.Quote here.
1426 // The code in vcs.go should be changed so that it is not required.
1427 quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo"))
1428 quoted = quoted[1 : len(quoted)-1]
1430 tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo")
1433 func TestInstallFailsWithNoBuildableFiles(t *testing.T) {
1436 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1437 tg.setenv("CGO_ENABLED", "0")
1438 tg.runFail("install", "cgotest")
1439 tg.grepStderr("build constraints exclude all Go files", "go install cgotest did not report 'build constraints exclude all Go files'")
1443 func TestMSanAndRaceRequireCgo(t *testing.T) {
1444 if !canMSan && !canRace {
1445 t.Skip("skipping because both msan and the race detector are not supported")
1450 tg.tempFile("triv.go", `package main; func main() {}`)
1451 tg.setenv("CGO_ENABLED", "0")
1453 tg.runFail("install", "-race", "triv.go")
1454 tg.grepStderr("-race requires cgo", "did not correctly report that -race requires cgo")
1455 tg.grepStderrNot("-msan", "reported that -msan instead of -race requires cgo")
1458 tg.runFail("install", "-msan", "triv.go")
1459 tg.grepStderr("-msan requires cgo", "did not correctly report that -msan requires cgo")
1460 tg.grepStderrNot("-race", "reported that -race instead of -msan requires cgo")
1464 func TestRelativeGOBINFail(t *testing.T) {
1467 tg.tempFile("triv.go", `package main; func main() {}`)
1468 tg.setenv("GOBIN", ".")
1470 tg.runFail("install")
1471 tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path")
1474 // Test that without $GOBIN set, binaries get installed
1475 // into the GOPATH bin directory.
1476 func TestInstallIntoGOPATH(t *testing.T) {
1479 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1480 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1481 tg.run("install", "go-cmd-test")
1482 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1486 func TestBuildOutputToDevNull(t *testing.T) {
1489 fi1, err1 := os.Lstat(os.DevNull)
1490 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1491 tg.run("build", "-o", os.DevNull, "go-cmd-test")
1492 fi2, err2 := os.Lstat(os.DevNull)
1495 t.Errorf("second stat of /dev/null failed: %v", err2)
1496 } else if !os.SameFile(fi1, fi2) {
1497 t.Errorf("/dev/null changed: now %v was %v", fi1, fi2)
1503 func TestTestOutputToDevNull(t *testing.T) {
1506 fi1, err1 := os.Lstat(os.DevNull)
1508 tg.setenv("GOPATH", tg.path("."))
1509 tg.tempFile("src/p/p.go", "package p\n")
1510 tg.tempFile("src/p/p_test.go", "package p\nimport \"testing\"\nfunc TestX(t *testing.T) {}\n")
1511 tg.run("test", "-o", os.DevNull, "-c", "p")
1512 tg.mustNotExist("p.test")
1513 fi2, err2 := os.Lstat(os.DevNull)
1516 t.Errorf("second stat of /dev/null failed: %v", err2)
1517 } else if !os.SameFile(fi1, fi2) {
1518 t.Errorf("/dev/null changed: now %v was %v", fi1, fi2)
1523 func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) {
1528 gobin := filepath.Join(tg.pwd(), "testdata", "bin")
1529 tg.creatingTemp(gobin)
1530 tg.setenv("GOBIN", gobin)
1531 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1532 tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now()))
1534 tg.run("test", "main_test")
1535 tg.run("install", "main_test")
1536 tg.wantNotStale("main_test", "", "after go install, main listed as stale")
1537 tg.run("test", "main_test")
1540 func TestPackageMainTestCompilerFlags(t *testing.T) {
1545 tg.setenv("GOPATH", tg.path("."))
1546 tg.tempFile("src/p1/p1.go", "package main\n")
1547 tg.tempFile("src/p1/p1_test.go", "package main\nimport \"testing\"\nfunc Test(t *testing.T){}\n")
1548 tg.run("test", "-c", "-n", "p1")
1549 tg.grepBothNot(`([\\/]compile|gccgo).* (-p main|-fgo-pkgpath=main).*p1\.go`, "should not have run compile -p main p1.go")
1550 tg.grepStderr(`([\\/]compile|gccgo).* (-p p1|-fgo-pkgpath=p1).*p1\.go`, "should have run compile -p p1 p1.go")
1554 func TestPackageNotStaleWithTrailingSlash(t *testing.T) {
1555 skipIfGccgo(t, "gccgo does not have GOROOT")
1559 // Make sure the packages below are not stale.
1560 tg.wantNotStale("runtime", "", "must be non-stale before test runs")
1561 tg.wantNotStale("os", "", "must be non-stale before test runs")
1562 tg.wantNotStale("io", "", "must be non-stale before test runs")
1564 goroot := runtime.GOROOT()
1565 tg.setenv("GOROOT", goroot+"/")
1567 tg.wantNotStale("runtime", "", "with trailing slash in GOROOT, runtime listed as stale")
1568 tg.wantNotStale("os", "", "with trailing slash in GOROOT, os listed as stale")
1569 tg.wantNotStale("io", "", "with trailing slash in GOROOT, io listed as stale")
1572 // With $GOBIN set, binaries get installed to $GOBIN.
1573 func TestInstallIntoGOBIN(t *testing.T) {
1576 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1577 tg.creatingTemp(gobin)
1578 tg.setenv("GOBIN", gobin)
1579 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1580 tg.run("install", "go-cmd-test")
1581 tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test")
1585 func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) {
1588 pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test")
1589 tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix))
1590 tg.setenv("GOBIN", pkg)
1591 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1594 tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory")
1597 // Without $GOBIN set, installing a program outside $GOPATH should fail
1598 // (there is nowhere to install it).
1599 func TestInstallWithoutDestinationFails(t *testing.T) {
1602 tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go")
1603 tg.grepStderr("no install location for .go files listed on command line", "wrong error")
1606 // With $GOBIN set, should install there.
1607 func TestInstallToGOBINCommandLinePackage(t *testing.T) {
1610 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1611 tg.creatingTemp(gobin)
1612 tg.setenv("GOBIN", gobin)
1613 tg.run("install", "testdata/src/go-cmd-test/helloworld.go")
1614 tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld")
1617 func TestGoGetNonPkg(t *testing.T) {
1618 testenv.MustHaveExternalNetwork(t)
1623 tg.setenv("GOPATH", tg.path("."))
1624 tg.setenv("GOBIN", tg.path("gobin"))
1625 tg.runFail("get", "-d", "golang.org/x/tools")
1626 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1627 tg.runFail("get", "-d", "-u", "golang.org/x/tools")
1628 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1629 tg.runFail("get", "-d", "golang.org/x/tools")
1630 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1633 func TestGoGetTestOnlyPkg(t *testing.T) {
1634 testenv.MustHaveExternalNetwork(t)
1638 tg.tempDir("gopath")
1639 tg.setenv("GOPATH", tg.path("gopath"))
1640 tg.run("get", "golang.org/x/tour/content...")
1641 tg.run("get", "-t", "golang.org/x/tour/content...")
1644 func TestInstalls(t *testing.T) {
1645 if testing.Short() {
1646 t.Skip("don't install into GOROOT in short mode")
1653 tg.setenv("GOPATH", tg.path("."))
1654 goroot := runtime.GOROOT()
1655 tg.setenv("GOROOT", goroot)
1657 // cmd/fix installs into tool
1658 tg.run("env", "GOOS")
1659 goos := strings.TrimSpace(tg.getStdout())
1660 tg.setenv("GOOS", goos)
1661 tg.run("env", "GOARCH")
1662 goarch := strings.TrimSpace(tg.getStdout())
1663 tg.setenv("GOARCH", goarch)
1664 fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix
1665 tg.must(os.RemoveAll(fixbin))
1666 tg.run("install", "cmd/fix")
1667 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool")
1668 tg.must(os.Remove(fixbin))
1669 tg.setenv("GOBIN", tg.path("gobin"))
1670 tg.run("install", "cmd/fix")
1671 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set")
1672 tg.unsetenv("GOBIN")
1674 // gopath program installs into GOBIN
1675 tg.tempFile("src/progname/p.go", `package main; func main() {}`)
1676 tg.setenv("GOBIN", tg.path("gobin"))
1677 tg.run("install", "progname")
1678 tg.unsetenv("GOBIN")
1679 tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname")
1681 // gopath program installs into GOPATH/bin
1682 tg.run("install", "progname")
1683 tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname")
1686 func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) {
1689 tg.setenv("GOPATH", ".")
1690 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1691 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1694 func TestRejectRelativePathsInGOPATH(t *testing.T) {
1697 sep := string(filepath.ListSeparator)
1698 tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".")
1699 tg.runFail("build", "go-cmd-test")
1700 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1703 func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) {
1706 tg.setenv("GOPATH", "testdata")
1707 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1708 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1712 func TestRejectBlankPathsInGOPATH(t *testing.T) {
1715 sep := string(filepath.ListSeparator)
1716 tg.setenv("GOPATH", " "+sep+filepath.Join(tg.pwd(), "testdata"))
1717 tg.runFail("build", "go-cmd-test")
1718 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1722 func TestIgnoreEmptyPathsInGOPATH(t *testing.T) {
1725 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1726 sep := string(filepath.ListSeparator)
1727 tg.setenv("GOPATH", ""+sep+filepath.Join(tg.pwd(), "testdata"))
1728 tg.run("install", "go-cmd-test")
1729 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1733 func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
1738 tg.run("test", "errors", "errors", "errors", "errors", "errors")
1739 if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") {
1740 t.Error("go test errors errors errors errors errors tested the same package multiple times")
1744 func TestGoListHasAConsistentOrder(t *testing.T) {
1749 tg.run("list", "std")
1750 first := tg.getStdout()
1751 tg.run("list", "std")
1752 if first != tg.getStdout() {
1753 t.Error("go list std ordering is inconsistent")
1757 func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
1762 tg.run("list", "std")
1763 tg.grepStdoutNot("cmd/", "go list std shows commands")
1766 func TestGoListCmdOnlyShowsCommands(t *testing.T) {
1767 skipIfGccgo(t, "gccgo does not have GOROOT")
1772 tg.run("list", "cmd")
1773 out := strings.TrimSpace(tg.getStdout())
1774 for _, line := range strings.Split(out, "\n") {
1775 if !strings.Contains(line, "cmd/") {
1776 t.Error("go list cmd shows non-commands")
1782 func TestGoListDedupsPackages(t *testing.T) {
1785 // TODO: tg.parallel()
1786 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1787 tg.run("list", "xtestonly", "./testdata/src/xtestonly/...")
1788 got := strings.TrimSpace(tg.getStdout())
1789 const want = "xtestonly"
1791 t.Errorf("got %q; want %q", got, want)
1795 func TestGoListDeps(t *testing.T) {
1799 tg.tempDir("src/p1/p2/p3/p4")
1800 tg.setenv("GOPATH", tg.path("."))
1801 tg.tempFile("src/p1/p.go", "package p1\nimport _ \"p1/p2\"\n")
1802 tg.tempFile("src/p1/p2/p.go", "package p2\nimport _ \"p1/p2/p3\"\n")
1803 tg.tempFile("src/p1/p2/p3/p.go", "package p3\nimport _ \"p1/p2/p3/p4\"\n")
1804 tg.tempFile("src/p1/p2/p3/p4/p.go", "package p4\n")
1805 tg.run("list", "-f", "{{.Deps}}", "p1")
1806 tg.grepStdout("p1/p2/p3/p4", "Deps(p1) does not mention p4")
1808 tg.run("list", "-deps", "p1")
1809 tg.grepStdout("p1/p2/p3/p4", "-deps p1 does not mention p4")
1811 if runtime.Compiler != "gccgo" {
1812 // Check the list is in dependency order.
1813 tg.run("list", "-deps", "math")
1814 want := "internal/cpu\nunsafe\nmath/bits\nmath\n"
1815 out := tg.stdout.String()
1816 if !strings.Contains(out, "internal/cpu") {
1817 // Some systems don't use internal/cpu.
1818 want = "unsafe\nmath/bits\nmath\n"
1820 if tg.stdout.String() != want {
1821 t.Fatalf("list -deps math: wrong order\nhave %q\nwant %q", tg.stdout.String(), want)
1826 func TestGoListTest(t *testing.T) {
1827 skipIfGccgo(t, "gccgo does not have standard packages")
1832 tg.setenv("GOCACHE", tg.tempdir)
1834 tg.run("list", "-test", "-deps", "sort")
1835 tg.grepStdout(`^sort.test$`, "missing test main")
1836 tg.grepStdout(`^sort$`, "missing real sort")
1837 tg.grepStdout(`^sort \[sort.test\]$`, "missing test copy of sort")
1838 tg.grepStdout(`^testing \[sort.test\]$`, "missing test copy of testing")
1839 tg.grepStdoutNot(`^testing$`, "unexpected real copy of testing")
1841 tg.run("list", "-test", "sort")
1842 tg.grepStdout(`^sort.test$`, "missing test main")
1843 tg.grepStdout(`^sort$`, "missing real sort")
1844 tg.grepStdout(`^sort \[sort.test\]$`, "unexpected test copy of sort")
1845 tg.grepStdoutNot(`^testing \[sort.test\]$`, "unexpected test copy of testing")
1846 tg.grepStdoutNot(`^testing$`, "unexpected real copy of testing")
1848 tg.run("list", "-test", "cmd/dist", "cmd/doc")
1849 tg.grepStdout(`^cmd/dist$`, "missing cmd/dist")
1850 tg.grepStdout(`^cmd/doc$`, "missing cmd/doc")
1851 tg.grepStdout(`^cmd/doc\.test$`, "missing cmd/doc test")
1852 tg.grepStdoutNot(`^cmd/dist\.test$`, "unexpected cmd/dist test")
1853 tg.grepStdoutNot(`^testing`, "unexpected testing")
1855 tg.run("list", "-test", "runtime/cgo")
1856 tg.grepStdout(`^runtime/cgo$`, "missing runtime/cgo")
1858 tg.run("list", "-deps", "-f", "{{if .DepOnly}}{{.ImportPath}}{{end}}", "sort")
1859 tg.grepStdout(`^reflect$`, "missing reflect")
1860 tg.grepStdoutNot(`^sort`, "unexpected sort")
1863 func TestGoListCompiledCgo(t *testing.T) {
1868 tg.setenv("GOCACHE", tg.tempdir)
1870 tg.run("list", "-f", `{{join .CgoFiles "\n"}}`, "net")
1871 if tg.stdout.String() == "" {
1872 t.Skip("net does not use cgo")
1874 if strings.Contains(tg.stdout.String(), tg.tempdir) {
1875 t.Fatalf(".CgoFiles unexpectedly mentioned cache %s", tg.tempdir)
1877 tg.run("list", "-compiled", "-f", `{{.Dir}}{{"\n"}}{{join .CompiledGoFiles "\n"}}`, "net")
1878 if !strings.Contains(tg.stdout.String(), tg.tempdir) {
1879 t.Fatalf(".CompiledGoFiles with -compiled did not mention cache %s", tg.tempdir)
1882 for _, file := range strings.Split(tg.stdout.String(), "\n") {
1890 if !strings.Contains(file, "/") && !strings.Contains(file, `\`) {
1891 file = filepath.Join(dir, file)
1893 if _, err := os.Stat(file); err != nil {
1894 t.Fatalf("cannot find .CompiledGoFiles result %s: %v", file, err)
1899 func TestGoListExport(t *testing.T) {
1900 skipIfGccgo(t, "gccgo does not have standard packages")
1905 tg.setenv("GOCACHE", tg.tempdir)
1907 tg.run("list", "-f", "{{.Export}}", "strings")
1908 if tg.stdout.String() != "" {
1909 t.Fatalf(".Export without -export unexpectedly set")
1911 tg.run("list", "-export", "-f", "{{.Export}}", "strings")
1912 file := strings.TrimSpace(tg.stdout.String())
1914 t.Fatalf(".Export with -export was empty")
1916 if _, err := os.Stat(file); err != nil {
1917 t.Fatalf("cannot find .Export result %s: %v", file, err)
1921 // Issue 4096. Validate the output of unsuccessful go install foo/quxx.
1922 func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) {
1926 tg.runFail("install", "foo/quxx")
1927 if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 {
1928 t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`)
1932 func TestGOROOTSearchFailureReporting(t *testing.T) {
1936 tg.runFail("install", "foo/quxx")
1937 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 {
1938 t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`)
1942 func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) {
1946 sep := string(filepath.ListSeparator)
1947 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1948 tg.runFail("install", "foo/quxx")
1949 if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 {
1950 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`)
1954 // Test (from $GOPATH) annotation is reported for the first GOPATH entry,
1955 func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) {
1959 sep := string(filepath.ListSeparator)
1960 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1961 tg.runFail("install", "foo/quxx")
1962 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 {
1963 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`)
1967 // but not on the second.
1968 func TestMentionGOPATHNotOnSecondEntry(t *testing.T) {
1972 sep := string(filepath.ListSeparator)
1973 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1974 tg.runFail("install", "foo/quxx")
1975 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 {
1976 t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`)
1980 func homeEnvName() string {
1981 switch runtime.GOOS {
1983 return "USERPROFILE"
1991 func tempEnvName() string {
1992 switch runtime.GOOS {
1996 return "TMPDIR" // actually plan 9 doesn't have one at all but this is fine
2002 func TestDefaultGOPATH(t *testing.T) {
2006 tg.tempDir("home/go")
2007 tg.setenv(homeEnvName(), tg.path("home"))
2009 tg.run("env", "GOPATH")
2010 tg.grepStdout(regexp.QuoteMeta(tg.path("home/go")), "want GOPATH=$HOME/go")
2012 tg.setenv("GOROOT", tg.path("home/go"))
2013 tg.run("env", "GOPATH")
2014 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go")
2016 tg.setenv("GOROOT", tg.path("home/go")+"/")
2017 tg.run("env", "GOPATH")
2018 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go/")
2021 func TestDefaultGOPATHGet(t *testing.T) {
2022 testenv.MustHaveExternalNetwork(t)
2026 tg.setenv("GOPATH", "")
2028 tg.setenv(homeEnvName(), tg.path("home"))
2030 // warn for creating directory
2031 tg.run("get", "-v", "github.com/golang/example/hello")
2032 tg.grepStderr("created GOPATH="+regexp.QuoteMeta(tg.path("home/go"))+"; see 'go help gopath'", "did not create GOPATH")
2034 // no warning if directory already exists
2035 tg.must(os.RemoveAll(tg.path("home/go")))
2036 tg.tempDir("home/go")
2037 tg.run("get", "github.com/golang/example/hello")
2038 tg.grepStderrNot(".", "expected no output on standard error")
2040 // error if $HOME/go is a file
2041 tg.must(os.RemoveAll(tg.path("home/go")))
2042 tg.tempFile("home/go", "")
2043 tg.runFail("get", "github.com/golang/example/hello")
2044 tg.grepStderr(`mkdir .*[/\\]go: .*(not a directory|cannot find the path)`, "expected error because $HOME/go is a file")
2047 func TestDefaultGOPATHPrintedSearchList(t *testing.T) {
2050 tg.setenv("GOPATH", "")
2052 tg.setenv(homeEnvName(), tg.path("home"))
2054 tg.runFail("install", "github.com/golang/example/hello")
2055 tg.grepStderr(regexp.QuoteMeta(tg.path("home/go/src/github.com/golang/example/hello"))+`.*from \$GOPATH`, "expected default GOPATH")
2058 // Issue 4186. go get cannot be used to download packages to $GOROOT.
2059 // Test that without GOPATH set, go get should fail.
2060 func TestGoGetIntoGOROOT(t *testing.T) {
2061 testenv.MustHaveExternalNetwork(t)
2068 // Fails because GOROOT=GOPATH
2069 tg.setenv("GOPATH", tg.path("."))
2070 tg.setenv("GOROOT", tg.path("."))
2071 tg.runFail("get", "-d", "github.com/golang/example/hello")
2072 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2073 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2075 // Fails because GOROOT=GOPATH after cleaning.
2076 tg.setenv("GOPATH", tg.path(".")+"/")
2077 tg.setenv("GOROOT", tg.path("."))
2078 tg.runFail("get", "-d", "github.com/golang/example/hello")
2079 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2080 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2082 tg.setenv("GOPATH", tg.path("."))
2083 tg.setenv("GOROOT", tg.path(".")+"/")
2084 tg.runFail("get", "-d", "github.com/golang/example/hello")
2085 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2086 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2088 // Fails because GOROOT=$HOME/go so default GOPATH unset.
2089 tg.tempDir("home/go")
2090 tg.setenv(homeEnvName(), tg.path("home"))
2091 tg.setenv("GOPATH", "")
2092 tg.setenv("GOROOT", tg.path("home/go"))
2093 tg.runFail("get", "-d", "github.com/golang/example/hello")
2094 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2096 tg.setenv(homeEnvName(), tg.path("home")+"/")
2097 tg.setenv("GOPATH", "")
2098 tg.setenv("GOROOT", tg.path("home/go"))
2099 tg.runFail("get", "-d", "github.com/golang/example/hello")
2100 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2102 tg.setenv(homeEnvName(), tg.path("home"))
2103 tg.setenv("GOPATH", "")
2104 tg.setenv("GOROOT", tg.path("home/go")+"/")
2105 tg.runFail("get", "-d", "github.com/golang/example/hello")
2106 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2109 func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) {
2110 skipIfGccgo(t, "gccgo does not support -ldflags -X")
2115 tg.tempFile("main.go", `package main
2120 tg.run("run", "-ldflags", `-X "main.extern=hello world"`, tg.path("main.go"))
2121 tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`)
2124 func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) {
2125 skipIfGccgo(t, "gccgo has no standard packages")
2129 // TODO: tg.parallel()
2132 tg.run("test", "-cpuprofile", "errors.prof", "errors")
2133 tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test")
2136 func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) {
2137 skipIfGccgo(t, "gccgo has no standard packages")
2141 // TODO: tg.parallel()
2144 tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2145 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test")
2148 func TestGoTestMutexprofileLeavesBinaryBehind(t *testing.T) {
2149 skipIfGccgo(t, "gccgo has no standard packages")
2153 // TODO: tg.parallel()
2156 tg.run("test", "-mutexprofile", "errors.prof", "errors")
2157 tg.wantExecutable("errors.test"+exeSuffix, "go test -mutexprofile did not create errors.test")
2160 func TestGoTestMutexprofileDashOControlsBinaryLocation(t *testing.T) {
2161 skipIfGccgo(t, "gccgo has no standard packages")
2165 // TODO: tg.parallel()
2168 tg.run("test", "-mutexprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2169 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -mutexprofile -o myerrors.test did not create myerrors.test")
2172 func TestGoBuildNonMain(t *testing.T) {
2175 // TODO: tg.parallel()
2176 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2177 tg.runFail("build", "-buildmode=exe", "-o", "not_main"+exeSuffix, "not_main")
2178 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")
2179 tg.mustNotExist("not_main" + exeSuffix)
2182 func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) {
2183 skipIfGccgo(t, "gccgo has no standard packages")
2189 tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2190 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test")
2193 func TestGoTestDashOWritesBinary(t *testing.T) {
2194 skipIfGccgo(t, "gccgo has no standard packages")
2200 tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2201 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2204 func TestGoTestDashIDashOWritesBinary(t *testing.T) {
2205 skipIfGccgo(t, "gccgo has no standard packages")
2212 // don't let test -i overwrite runtime
2213 tg.wantNotStale("runtime", "", "must be non-stale before test -i")
2215 tg.run("test", "-v", "-i", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2216 tg.grepBothNot("PASS|FAIL", "test should not have run")
2217 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2221 func TestSymlinksList(t *testing.T) {
2222 testenv.MustHaveSymlink(t)
2226 // TODO: tg.parallel()
2228 tg.must(os.Symlink(tg.path("."), tg.path("src/dir1")))
2229 tg.tempFile("src/dir1/p.go", "package p")
2230 tg.setenv("GOPATH", tg.path("."))
2231 tg.cd(tg.path("src"))
2232 tg.run("list", "-f", "{{.Root}}", "dir1")
2233 if strings.TrimSpace(tg.getStdout()) != tg.path(".") {
2234 t.Error("confused by symlinks")
2239 func TestSymlinksVendor(t *testing.T) {
2240 testenv.MustHaveSymlink(t)
2244 // TODO: tg.parallel()
2245 tg.tempDir("gopath/src/dir1/vendor/v")
2246 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}")
2247 tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v")
2248 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2249 tg.setenv("GOPATH", tg.path("gopath"))
2250 tg.cd(tg.path("symdir1"))
2251 tg.run("list", "-f", "{{.Root}}", ".")
2252 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2253 t.Error("list confused by symlinks")
2256 // All of these should succeed, not die in vendor-handling code.
2257 tg.run("run", "p.go")
2263 func TestSymlinksVendor15201(t *testing.T) {
2264 testenv.MustHaveSymlink(t)
2269 tg.tempDir("gopath/src/x/y/_vendor/src/x")
2270 tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y")))
2271 tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n")
2272 tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor")))
2273 tg.tempFile("gopath/src/x/y/z/z.go", "package z\n")
2275 tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath"))
2276 tg.cd(tg.path("gopath/src"))
2277 tg.run("list", "./...")
2280 func TestSymlinksInternal(t *testing.T) {
2281 testenv.MustHaveSymlink(t)
2285 tg.tempDir("gopath/src/dir1/internal/v")
2286 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}")
2287 tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v")
2288 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2289 tg.setenv("GOPATH", tg.path("gopath"))
2290 tg.cd(tg.path("symdir1"))
2291 tg.run("list", "-f", "{{.Root}}", ".")
2292 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2293 t.Error("list confused by symlinks")
2296 // All of these should succeed, not die in internal-handling code.
2297 tg.run("run", "p.go")
2303 func TestInstallWithTags(t *testing.T) {
2309 tg.tempFile("src/example/a/main.go", `package main
2311 tg.tempFile("src/example/b/main.go", `// +build mytag
2315 tg.setenv("GOPATH", tg.path("."))
2316 tg.run("install", "-tags", "mytag", "example/a", "example/b")
2317 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries")
2318 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries")
2319 tg.must(os.Remove(tg.path("bin/a" + exeSuffix)))
2320 tg.must(os.Remove(tg.path("bin/b" + exeSuffix)))
2321 tg.run("install", "-tags", "mytag", "example/...")
2322 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries")
2323 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries")
2324 tg.run("list", "-tags", "mytag", "example/b...")
2325 if strings.TrimSpace(tg.getStdout()) != "example/b" {
2326 t.Error("go list example/b did not find example/b")
2331 func TestCaseCollisions(t *testing.T) {
2335 tg.tempDir("src/example/a/pkg")
2336 tg.tempDir("src/example/a/Pkg")
2337 tg.tempDir("src/example/b")
2338 tg.setenv("GOPATH", tg.path("."))
2339 tg.tempFile("src/example/a/a.go", `package p
2344 tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`)
2345 tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`)
2346 tg.run("list", "-json", "example/a")
2347 tg.grepStdout("case-insensitive import collision", "go list -json example/a did not report import collision")
2348 tg.runFail("build", "example/a")
2349 tg.grepStderr("case-insensitive import collision", "go build example/a did not report import collision")
2350 tg.tempFile("src/example/b/file.go", `package b`)
2351 tg.tempFile("src/example/b/FILE.go", `package b`)
2352 f, err := os.Open(tg.path("src/example/b"))
2354 names, err := f.Readdirnames(0)
2357 args := []string{"list"}
2358 if len(names) == 2 {
2359 // case-sensitive file system, let directory read find both files
2360 args = append(args, "example/b")
2362 // case-insensitive file system, list files explicitly on command line
2363 args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go"))
2366 tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision")
2368 tg.runFail("list", "example/a/pkg", "example/a/Pkg")
2369 tg.grepStderr("case-insensitive import collision", "go list example/a/pkg example/a/Pkg did not report import collision")
2370 tg.run("list", "-json", "-e", "example/a/pkg", "example/a/Pkg")
2371 tg.grepStdout("case-insensitive import collision", "go list -json -e example/a/pkg example/a/Pkg did not report import collision")
2372 tg.runFail("build", "example/a/pkg", "example/a/Pkg")
2373 tg.grepStderr("case-insensitive import collision", "go build example/a/pkg example/a/Pkg did not report import collision")
2376 // Issue 17451, 17662.
2377 func TestSymlinkWarning(t *testing.T) {
2382 tg.setenv("GOPATH", tg.path("."))
2384 tg.tempDir("src/example/xx")
2386 tg.tempFile("yy/zz/zz.go", "package zz\n")
2387 if err := os.Symlink(tg.path("yy"), tg.path("src/example/xx/yy")); err != nil {
2388 t.Skipf("symlink failed: %v", err)
2390 tg.run("list", "example/xx/z...")
2391 tg.grepStdoutNot(".", "list should not have matched anything")
2392 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2393 tg.grepStderrNot("symlink", "list should not have reported symlink")
2395 tg.run("list", "example/xx/...")
2396 tg.grepStdoutNot(".", "list should not have matched anything")
2397 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2398 tg.grepStderr("ignoring symlink", "list should have reported symlink")
2402 func TestGoGetDashTIssue8181(t *testing.T) {
2403 testenv.MustHaveExternalNetwork(t)
2409 tg.setenv("GOPATH", tg.path("."))
2410 tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b")
2411 tg.run("list", "...")
2412 tg.grepStdout("x/build/gerrit", "missing expected x/build/gerrit")
2415 func TestIssue11307(t *testing.T) {
2416 // go get -u was not working except in checkout directory
2417 testenv.MustHaveExternalNetwork(t)
2423 tg.setenv("GOPATH", tg.path("."))
2424 tg.run("get", "github.com/rsc/go-get-issue-11307")
2425 tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing
2428 func TestShadowingLogic(t *testing.T) {
2429 skipIfGccgo(t, "gccgo has no standard packages")
2433 sep := string(filepath.ListSeparator)
2434 tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2"))
2436 // The math in root1 is not "math" because the standard math is.
2437 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math")
2438 pwdForwardSlash := strings.ReplaceAll(pwd, string(os.PathSeparator), "/")
2439 if !strings.HasPrefix(pwdForwardSlash, "/") {
2440 pwdForwardSlash = "/" + pwdForwardSlash
2442 // The output will have makeImportValid applies, but we only
2443 // bother to deal with characters we might reasonably see.
2444 for _, r := range " :" {
2445 pwdForwardSlash = strings.ReplaceAll(pwdForwardSlash, string(r), "_")
2447 want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")"
2448 if strings.TrimSpace(tg.getStdout()) != want {
2449 t.Error("shadowed math is not shadowed; looking for", want)
2452 // The foo in root1 is "foo".
2453 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo")
2454 if strings.TrimSpace(tg.getStdout()) != "(foo) ()" {
2455 t.Error("unshadowed foo is shadowed")
2458 // The foo in root2 is not "foo" because the foo in root1 got there first.
2459 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo")
2460 want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")"
2461 if strings.TrimSpace(tg.getStdout()) != want {
2462 t.Error("shadowed foo is not shadowed; looking for", want)
2465 // The error for go install should mention the conflicting directory.
2466 tg.runFail("install", "./testdata/shadow/root2/src/foo")
2467 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")
2468 if strings.TrimSpace(tg.getStderr()) != want {
2469 t.Error("wrong shadowed install error; looking for", want)
2473 // Only succeeds if source order is preserved.
2474 func TestSourceFileNameOrderPreserved(t *testing.T) {
2477 tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go")
2480 // Check that coverage analysis works at all.
2481 // Don't worry about the exact numbers but require not 0.0%.
2482 func checkCoverage(tg *testgoData, data string) {
2484 if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) {
2485 tg.t.Error("some coverage results are 0.0%")
2489 func TestCoverageRuns(t *testing.T) {
2490 skipIfGccgo(t, "gccgo has no cover tool")
2494 tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp")
2495 data := tg.getStdout() + tg.getStderr()
2496 tg.run("test", "-short", "-cover", "strings", "math", "regexp")
2497 data += tg.getStdout() + tg.getStderr()
2498 checkCoverage(tg, data)
2501 func TestCoverageDotImport(t *testing.T) {
2502 skipIfGccgo(t, "gccgo has no cover tool")
2506 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2507 tg.run("test", "-coverpkg=coverdot1,coverdot2", "coverdot2")
2508 data := tg.getStdout() + tg.getStderr()
2509 checkCoverage(tg, data)
2512 // Check that coverage analysis uses set mode.
2513 // Also check that coverage profiles merge correctly.
2514 func TestCoverageUsesSetMode(t *testing.T) {
2515 skipIfGccgo(t, "gccgo has no cover tool")
2519 tg.creatingTemp("testdata/cover.out")
2520 tg.run("test", "-short", "-cover", "encoding/binary", "errors", "-coverprofile=testdata/cover.out")
2521 data := tg.getStdout() + tg.getStderr()
2522 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2525 if !bytes.Contains(out, []byte("mode: set")) {
2526 t.Error("missing mode: set")
2528 if !bytes.Contains(out, []byte("errors.go")) {
2529 t.Error("missing errors.go")
2531 if !bytes.Contains(out, []byte("binary.go")) {
2532 t.Error("missing binary.go")
2534 if bytes.Count(out, []byte("mode: set")) != 1 {
2535 t.Error("too many mode: set")
2538 checkCoverage(tg, data)
2541 func TestCoverageUsesAtomicModeForRace(t *testing.T) {
2544 t.Skip("skipping because race detector not supported")
2546 skipIfGccgo(t, "gccgo has no cover tool")
2550 tg.creatingTemp("testdata/cover.out")
2551 tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
2552 data := tg.getStdout() + tg.getStderr()
2553 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2556 if !bytes.Contains(out, []byte("mode: atomic")) {
2557 t.Error("missing mode: atomic")
2560 checkCoverage(tg, data)
2563 func TestCoverageSyncAtomicImport(t *testing.T) {
2564 skipIfGccgo(t, "gccgo has no cover tool")
2569 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2570 tg.run("test", "-short", "-cover", "-covermode=atomic", "-coverpkg=coverdep/p1", "coverdep")
2573 func TestCoverageDepLoop(t *testing.T) {
2578 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2579 // coverdep2/p1's xtest imports coverdep2/p2 which imports coverdep2/p1.
2580 // Make sure that coverage on coverdep2/p2 recompiles coverdep2/p2.
2581 tg.run("test", "-short", "-cover", "coverdep2/p1")
2582 tg.grepStdout("coverage: 100.0% of statements", "expected 100.0% coverage")
2585 func TestCoverageImportMainLoop(t *testing.T) {
2586 skipIfGccgo(t, "gccgo has no cover tool")
2589 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2590 tg.runFail("test", "importmain/test")
2591 tg.grepStderr("not an importable package", "did not detect import main")
2592 tg.runFail("test", "-cover", "importmain/test")
2593 tg.grepStderr("not an importable package", "did not detect import main")
2596 func TestCoveragePattern(t *testing.T) {
2597 skipIfGccgo(t, "gccgo has no cover tool")
2603 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2605 // If coverpkg=sleepy... expands by package loading
2606 // (as opposed to pattern matching on deps)
2607 // then it will try to load sleepybad, which does not compile,
2608 // and the test command will fail.
2609 tg.run("test", "-coverprofile="+tg.path("cover.out"), "-coverpkg=sleepy...", "-run=^$", "sleepy1")
2612 func TestCoverageErrorLine(t *testing.T) {
2613 skipIfGccgo(t, "gccgo has no cover tool")
2619 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2620 tg.setenv("GOTMPDIR", tg.tempdir)
2622 tg.runFail("test", "coverbad")
2623 tg.grepStderr(`coverbad[\\/]p\.go:4`, "did not find coverbad/p.go:4")
2625 tg.grepStderr(`coverbad[\\/]p1\.go:6`, "did not find coverbad/p1.go:6")
2627 tg.grepStderrNot(regexp.QuoteMeta(tg.tempdir), "found temporary directory in error")
2628 stderr := tg.getStderr()
2630 tg.runFail("test", "-cover", "coverbad")
2631 stderr2 := tg.getStderr()
2633 // It's OK that stderr2 drops the character position in the error,
2634 // because of the //line directive (see golang.org/issue/22662).
2635 stderr = strings.ReplaceAll(stderr, "p.go:4:2:", "p.go:4:")
2636 if stderr != stderr2 {
2637 t.Logf("test -cover changed error messages:\nbefore:\n%s\n\nafter:\n%s", stderr, stderr2)
2638 t.Skip("golang.org/issue/22660")
2643 func TestTestBuildFailureOutput(t *testing.T) {
2649 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2651 // Doesn't build, -x output should not claim to run test.
2652 tg.runFail("test", "-x", "coverbad")
2653 tg.grepStderrNot(`[\\/]coverbad\.test( |$)`, "claimed to run test")
2656 func TestCoverageFunc(t *testing.T) {
2657 skipIfGccgo(t, "gccgo has no cover tool")
2663 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2665 tg.run("test", "-outputdir="+tg.tempdir, "-coverprofile=cover.out", "coverasm")
2666 tg.run("tool", "cover", "-func="+tg.path("cover.out"))
2667 tg.grepStdout(`\tg\t*100.0%`, "did not find g 100% covered")
2668 tg.grepStdoutNot(`\tf\t*[0-9]`, "reported coverage for assembly function f")
2672 func TestCoverageDashC(t *testing.T) {
2673 skipIfGccgo(t, "gccgo has no cover tool")
2678 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2679 tg.run("test", "-c", "-o", tg.path("coverdep"), "-coverprofile="+tg.path("no/such/dir/cover.out"), "coverdep")
2680 tg.wantExecutable(tg.path("coverdep"), "go -test -c -coverprofile did not create executable")
2683 func TestPluginNonMain(t *testing.T) {
2684 wd, err := os.Getwd()
2689 pkg := filepath.Join(wd, "testdata", "testdep", "p2")
2694 tg.runFail("build", "-buildmode=plugin", pkg)
2697 func TestTestEmpty(t *testing.T) {
2699 t.Skip("no race detector")
2703 testdata := filepath.Join(wd, "testdata")
2704 for _, dir := range []string{"pkg", "test", "xtest", "pkgtest", "pkgxtest", "pkgtestxtest", "testxtest"} {
2705 t.Run(dir, func(t *testing.T) {
2708 tg.setenv("GOPATH", testdata)
2709 tg.cd(filepath.Join(testdata, "src/empty/"+dir))
2710 tg.run("test", "-cover", "-coverpkg=.", "-race")
2712 if testing.Short() {
2718 func TestNoGoError(t *testing.T) {
2720 testdata := filepath.Join(wd, "testdata")
2721 for _, dir := range []string{"empty/test", "empty/xtest", "empty/testxtest", "exclude", "exclude/ignore", "exclude/empty"} {
2722 t.Run(dir, func(t *testing.T) {
2725 tg.setenv("GOPATH", testdata)
2726 tg.cd(filepath.Join(testdata, "src"))
2727 tg.runFail("build", "./"+dir)
2729 if strings.Contains(dir, "test") {
2730 want = "no non-test Go files in "
2731 } else if dir == "exclude" {
2732 want = "build constraints exclude all Go files in "
2734 want = "no Go files in "
2736 tg.grepStderr(want, "wrong reason for failure")
2741 func TestTestRaceInstall(t *testing.T) {
2743 t.Skip("no race detector")
2749 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2752 pkgdir := tg.path("pkg")
2753 tg.run("install", "-race", "-pkgdir="+pkgdir, "std")
2754 tg.run("test", "-race", "-pkgdir="+pkgdir, "-i", "-v", "empty/pkg")
2755 if tg.getStderr() != "" {
2756 t.Error("go test -i -race: rebuilds cached packages")
2760 func TestBuildDryRunWithCgo(t *testing.T) {
2762 t.Skip("skipping because cgo not enabled")
2767 tg.tempFile("foo.go", `package main
2777 tg.run("build", "-n", tg.path("foo.go"))
2778 tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file")
2781 func TestCoverageWithCgo(t *testing.T) {
2782 skipIfGccgo(t, "gccgo has no cover tool")
2785 t.Skip("skipping because cgo not enabled")
2788 for _, dir := range []string{"cgocover", "cgocover2", "cgocover3", "cgocover4"} {
2789 t.Run(dir, func(t *testing.T) {
2793 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2794 tg.run("test", "-short", "-cover", dir)
2795 data := tg.getStdout() + tg.getStderr()
2796 checkCoverage(tg, data)
2801 func TestCgoAsmError(t *testing.T) {
2803 t.Skip("skipping because cgo not enabled")
2809 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2810 tg.runFail("build", "cgoasm")
2811 tg.grepBoth("package using cgo has Go assembly file", "did not detect Go assembly file")
2814 func TestCgoDependsOnSyscall(t *testing.T) {
2815 if testing.Short() {
2816 t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode")
2819 t.Skip("skipping because cgo not enabled")
2822 t.Skip("skipping because race detector not supported")
2827 files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race"))
2829 for _, file := range files {
2830 tg.check(os.RemoveAll(file))
2832 tg.tempFile("src/foo/foo.go", `
2834 //#include <stdio.h>
2836 tg.setenv("GOPATH", tg.path("."))
2837 tg.run("build", "-race", "foo")
2840 func TestCgoShowsFullPathNames(t *testing.T) {
2842 t.Skip("skipping because cgo not enabled")
2848 tg.tempFile("src/x/y/dirname/foo.go", `
2852 tg.setenv("GOPATH", tg.path("."))
2853 tg.runFail("build", "x/y/dirname")
2854 tg.grepBoth("x/y/dirname", "error did not use full path")
2857 func TestCgoHandlesWlORIGIN(t *testing.T) {
2860 t.Skip("skipping because cgo not enabled")
2866 tg.tempFile("src/origin/origin.go", `package origin
2867 // #cgo !darwin LDFLAGS: -Wl,-rpath,$ORIGIN
2870 func f() { C.f() }`)
2871 tg.setenv("GOPATH", tg.path("."))
2872 tg.run("build", "origin")
2875 func TestCgoPkgConfig(t *testing.T) {
2878 t.Skip("skipping because cgo not enabled")
2884 tg.run("env", "PKG_CONFIG")
2885 pkgConfig := strings.TrimSpace(tg.getStdout())
2886 if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil {
2887 t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out)
2890 // OpenBSD's pkg-config is strict about whitespace and only
2891 // supports backslash-escaped whitespace. It does not support
2892 // quotes, which the normal freedesktop.org pkg-config does
2893 // support. See https://man.openbsd.org/pkg-config.1
2894 tg.tempFile("foo.pc", `
2896 Description: The foo library
2898 Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world
2900 tg.tempFile("foo.go", `package main
2903 #cgo pkg-config: foo
2905 return DEFINED_FROM_PKG_CONFIG;
2912 if C.value() != 42 {
2913 println("value() =", C.value(), "wanted 42")
2918 tg.setenv("PKG_CONFIG_PATH", tg.path("."))
2919 tg.run("run", tg.path("foo.go"))
2922 // "go test -c -test.bench=XXX errors" should not hang.
2923 // "go test -c" should also produce reproducible binaries.
2924 // "go test -c" should also appear to write a new binary every time,
2925 // even if it's really just updating the mtime on an existing up-to-date binary.
2926 func TestIssue6480(t *testing.T) {
2927 skipIfGccgo(t, "gccgo has no standard packages")
2931 // TODO: tg.parallel()
2934 tg.run("test", "-c", "-test.bench=XXX", "errors")
2935 tg.run("test", "-c", "-o", "errors2.test", "errors")
2937 data1, err := ioutil.ReadFile("errors.test" + exeSuffix)
2939 data2, err := ioutil.ReadFile("errors2.test") // no exeSuffix because -o above doesn't have it
2941 if !bytes.Equal(data1, data2) {
2942 t.Fatalf("go test -c errors produced different binaries when run twice")
2946 tg.run("test", "-x", "-c", "-test.bench=XXX", "errors")
2947 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
2948 info, err := os.Stat("errors.test" + exeSuffix)
2952 start = truncateLike(start, info.ModTime())
2953 if info.ModTime().Before(start) {
2954 t.Fatalf("mtime of errors.test predates test -c command (%v < %v)", info.ModTime(), start)
2958 tg.run("test", "-x", "-c", "-o", "errors2.test", "errors")
2959 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
2960 info, err = os.Stat("errors2.test")
2964 start = truncateLike(start, info.ModTime())
2965 if info.ModTime().Before(start) {
2966 t.Fatalf("mtime of errors2.test predates test -c command (%v < %v)", info.ModTime(), start)
2970 // truncateLike returns the result of truncating t to the apparent precision of p.
2971 func truncateLike(t, p time.Time) time.Time {
2972 nano := p.UnixNano()
2973 d := 1 * time.Nanosecond
2974 for nano%int64(d) == 0 && d < 1*time.Second {
2977 for nano%int64(d) == 0 && d < 2*time.Second {
2980 return t.Truncate(d)
2983 // cmd/cgo: undefined reference when linking a C-library using gccgo
2984 func TestIssue7573(t *testing.T) {
2986 t.Skip("skipping because cgo not enabled")
2988 if _, err := exec.LookPath("gccgo"); err != nil {
2989 t.Skip("skipping because no gccgo compiler found")
2995 tg.tempFile("src/cgoref/cgoref.go", `
2997 // #cgo LDFLAGS: -L alibpath -lalib
3001 func main() { C.f() }`)
3002 tg.setenv("GOPATH", tg.path("."))
3003 tg.run("build", "-n", "-compiler", "gccgo", "cgoref")
3004 tg.grepStderr(`gccgo.*\-L [^ ]*alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`)
3007 func TestListTemplateContextFunction(t *testing.T) {
3009 for _, tt := range []struct {
3013 {"GOARCH", runtime.GOARCH},
3014 {"GOOS", runtime.GOOS},
3015 {"GOROOT", filepath.Clean(runtime.GOROOT())},
3016 {"GOPATH", os.Getenv("GOPATH")},
3018 {"UseAllFiles", ""},
3021 {"ReleaseTags", ""},
3022 {"InstallSuffix", ""},
3025 t.Run(tt.v, func(t *testing.T) {
3029 tmpl := "{{context." + tt.v + "}}"
3030 tg.run("list", "-f", tmpl)
3034 if got := strings.TrimSpace(tg.getStdout()); got != tt.want {
3035 t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want)
3041 // cmd/go: "go test" should fail if package does not build
3042 func TestIssue7108(t *testing.T) {
3045 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3046 tg.runFail("test", "notest")
3049 // cmd/go: go test -a foo does not rebuild regexp.
3050 func TestIssue6844(t *testing.T) {
3051 if testing.Short() {
3052 t.Skip("don't rebuild the standard library in short mode")
3057 tg.creatingTemp("deps.test" + exeSuffix)
3058 tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go")
3059 tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp")
3062 func TestBuildDashIInstallsDependencies(t *testing.T) {
3068 tg.tempFile("src/x/y/foo/foo.go", `package foo
3070 tg.tempFile("src/x/y/bar/bar.go", `package bar
3072 func F() { foo.F() }`)
3073 tg.setenv("GOPATH", tg.path("."))
3075 // don't let build -i overwrite runtime
3076 tg.wantNotStale("runtime", "", "must be non-stale before build -i")
3078 checkbar := func(desc string) {
3079 tg.run("build", "-v", "-i", "x/y/bar")
3080 tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo")
3081 tg.run("build", "-v", "-i", "x/y/bar")
3082 tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo")
3086 tg.creatingTemp("bar" + exeSuffix)
3088 tg.tempFile("src/x/y/foo/foo.go", `package foo
3090 tg.tempFile("src/x/y/bar/bar.go", `package main
3092 func main() { foo.F() }`)
3096 func TestGoBuildTestOnly(t *testing.T) {
3100 tg.setenv("GOPATH", tg.path("."))
3101 tg.tempFile("src/testonly/t_test.go", `package testonly`)
3102 tg.tempFile("src/testonly2/t.go", `package testonly2`)
3103 tg.cd(tg.path("src"))
3105 // Named explicitly, test-only packages should be reported as unbuildable/uninstallable,
3106 // even if there is a wildcard also matching.
3107 tg.runFail("build", "testonly", "testonly...")
3108 tg.grepStderr("no non-test Go files in", "go build ./xtestonly produced unexpected error")
3109 tg.runFail("install", "./testonly")
3110 tg.grepStderr("no non-test Go files in", "go install ./testonly produced unexpected error")
3112 // Named through a wildcards, the test-only packages should be silently ignored.
3113 tg.run("build", "testonly...")
3114 tg.run("install", "./testonly...")
3117 func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) {
3120 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3121 tg.runFail("test", "-c", "testcycle/p3")
3122 tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error")
3124 tg.runFail("test", "-c", "testcycle/q1")
3125 tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error")
3128 func TestGoTestFooTestWorks(t *testing.T) {
3131 tg.run("test", "testdata/standalone_test.go")
3135 func TestGoTestMainWithWrongSignature(t *testing.T) {
3138 tg.runFail("test", "testdata/standalone_main_wrong_test.go")
3139 tg.grepStderr(`wrong signature for TestMain, must be: func TestMain\(m \*testing.M\)`, "detected wrong error message")
3142 func TestGoTestMainAsNormalTest(t *testing.T) {
3145 tg.run("test", "testdata/standalone_main_normal_test.go")
3146 tg.grepBoth(okPattern, "go test did not say ok")
3149 func TestGoTestMainTwice(t *testing.T) {
3150 if testing.Short() {
3151 t.Skip("Skipping in short mode")
3156 tg.setenv("GOCACHE", tg.tempdir)
3157 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3158 tg.run("test", "-v", "multimain")
3159 if strings.Count(tg.getStdout(), "notwithstanding") != 2 {
3160 t.Fatal("tests did not run twice")
3164 func TestGoTestFlagsAfterPackage(t *testing.T) {
3168 tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags.
3169 tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags.
3172 func TestGoTestXtestonlyWorks(t *testing.T) {
3175 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3176 tg.run("clean", "-i", "xtestonly")
3177 tg.run("test", "xtestonly")
3180 func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) {
3183 tg.run("test", "-v", "./testdata/norunexample")
3184 tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built")
3187 func TestGoGenerateHandlesSimpleCommand(t *testing.T) {
3188 if runtime.GOOS == "windows" {
3189 t.Skip("skipping because windows has no echo command")
3194 tg.run("generate", "./testdata/generate/test1.go")
3195 tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output")
3198 func TestGoGenerateHandlesCommandAlias(t *testing.T) {
3199 if runtime.GOOS == "windows" {
3200 t.Skip("skipping because windows has no echo command")
3205 tg.run("generate", "./testdata/generate/test2.go")
3206 tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output")
3209 func TestGoGenerateVariableSubstitution(t *testing.T) {
3210 if runtime.GOOS == "windows" {
3211 t.Skip("skipping because windows has no echo command")
3216 tg.run("generate", "./testdata/generate/test3.go")
3217 tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output")
3220 func TestGoGenerateRunFlag(t *testing.T) {
3221 if runtime.GOOS == "windows" {
3222 t.Skip("skipping because windows has no echo command")
3227 tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go")
3228 tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes")
3229 tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no")
3232 func TestGoGenerateEnv(t *testing.T) {
3233 switch runtime.GOOS {
3234 case "plan9", "windows":
3235 t.Skipf("skipping because %s does not have the env command", runtime.GOOS)
3240 tg.tempFile("env.go", "package main\n\n//go:generate env")
3241 tg.run("generate", tg.path("env.go"))
3242 for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} {
3243 tg.grepStdout("^"+v+"=", "go generate environment missing "+v)
3247 func TestGoGenerateXTestPkgName(t *testing.T) {
3248 if runtime.GOOS == "windows" {
3249 t.Skip("skipping because windows has no echo command")
3255 tg.tempFile("env_test.go", "package main_test\n\n//go:generate echo $GOPACKAGE")
3256 tg.run("generate", tg.path("env_test.go"))
3258 if got := strings.TrimSpace(tg.getStdout()); got != want {
3259 t.Errorf("go generate in XTest file got package name %q; want %q", got, want)
3263 func TestGoGenerateBadImports(t *testing.T) {
3264 if runtime.GOOS == "windows" {
3265 t.Skip("skipping because windows has no echo command")
3268 // This package has an invalid import causing an import cycle,
3269 // but go generate is supposed to still run.
3272 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3273 tg.run("generate", "gencycle")
3274 tg.grepStdout("hello world", "go generate gencycle did not run generator")
3277 func TestGoGetCustomDomainWildcard(t *testing.T) {
3278 testenv.MustHaveExternalNetwork(t)
3283 tg.setenv("GOPATH", tg.path("."))
3284 tg.run("get", "-u", "rsc.io/pdf/...")
3285 tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd")
3288 func TestGoGetInternalWildcard(t *testing.T) {
3289 testenv.MustHaveExternalNetwork(t)
3294 tg.setenv("GOPATH", tg.path("."))
3295 // used to fail with errors about internal packages
3296 tg.run("get", "github.com/rsc/go-get-issue-11960/...")
3299 func TestGoVetWithExternalTests(t *testing.T) {
3303 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3304 tg.runFail("vet", "vetpkg")
3305 tg.grepBoth("Printf", "go vet vetpkg did not find missing argument for Printf")
3308 func TestGoVetWithTags(t *testing.T) {
3312 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3313 tg.runFail("vet", "-tags", "tagtest", "vetpkg")
3314 tg.grepBoth(`c\.go.*Printf`, "go vet vetpkg did not run scan tagged file")
3317 func TestGoVetWithFlagsOn(t *testing.T) {
3321 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3322 tg.runFail("vet", "-printf", "vetpkg")
3323 tg.grepBoth("Printf", "go vet -printf vetpkg did not find missing argument for Printf")
3326 func TestGoVetWithFlagsOff(t *testing.T) {
3330 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3331 tg.run("vet", "-printf=false", "vetpkg")
3335 func TestGoVetWithOnlyTestFiles(t *testing.T) {
3339 tg.tempFile("src/p/p_test.go", "package p; import \"testing\"; func TestMe(*testing.T) {}")
3340 tg.setenv("GOPATH", tg.path("."))
3345 func TestVetWithOnlyCgoFiles(t *testing.T) {
3347 t.Skip("skipping because cgo not enabled")
3353 tg.tempFile("src/p/p.go", "package p; import \"C\"; func F() {}")
3354 tg.setenv("GOPATH", tg.path("."))
3358 // Issue 9767, 19769.
3359 func TestGoGetDotSlashDownload(t *testing.T) {
3360 testenv.MustHaveExternalNetwork(t)
3364 tg.tempDir("src/rsc.io")
3365 tg.setenv("GOPATH", tg.path("."))
3366 tg.cd(tg.path("src/rsc.io"))
3367 tg.run("get", "./pprof_mac_fix")
3370 // Issue 13037: Was not parsing <meta> tags in 404 served over HTTPS
3371 func TestGoGetHTTPS404(t *testing.T) {
3372 testenv.MustHaveExternalNetwork(t)
3373 switch runtime.GOOS {
3374 case "darwin", "linux", "freebsd":
3376 t.Skipf("test case does not work on %s", runtime.GOOS)
3382 tg.setenv("GOPATH", tg.path("."))
3383 tg.run("get", "bazil.org/fuse/fs/fstestutil")
3386 // Test that you cannot import a main package.
3387 // See golang.org/issue/4210 and golang.org/issue/17475.
3388 func TestImportMain(t *testing.T) {
3395 // Importing package main from that package main's test should work.
3396 tg.tempFile("src/x/main.go", `package main
3399 tg.tempFile("src/x/main_test.go", `package main_test
3403 func TestFoo(t *testing.T) {}
3405 tg.setenv("GOPATH", tg.path("."))
3406 tg.creatingTemp("x" + exeSuffix)
3407 tg.run("build", "x")
3410 // Importing package main from another package should fail.
3411 tg.tempFile("src/p1/p.go", `package p1
3415 tg.runFail("build", "p1")
3416 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3418 // ... even in that package's test.
3419 tg.tempFile("src/p2/p.go", `package p2
3421 tg.tempFile("src/p2/p_test.go", `package p2
3425 func TestFoo(t *testing.T) {}
3427 tg.run("build", "p2")
3428 tg.runFail("test", "p2")
3429 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3431 // ... even if that package's test is an xtest.
3432 tg.tempFile("src/p3/p.go", `package p
3434 tg.tempFile("src/p3/p_test.go", `package p_test
3438 func TestFoo(t *testing.T) {}
3440 tg.run("build", "p3")
3441 tg.runFail("test", "p3")
3442 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3444 // ... even if that package is a package main
3445 tg.tempFile("src/p4/p.go", `package main
3448 tg.tempFile("src/p4/p_test.go", `package main
3452 func TestFoo(t *testing.T) {}
3454 tg.creatingTemp("p4" + exeSuffix)
3455 tg.run("build", "p4")
3456 tg.runFail("test", "p4")
3457 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3459 // ... even if that package is a package main using an xtest.
3460 tg.tempFile("src/p5/p.go", `package main
3463 tg.tempFile("src/p5/p_test.go", `package main_test
3467 func TestFoo(t *testing.T) {}
3469 tg.creatingTemp("p5" + exeSuffix)
3470 tg.run("build", "p5")
3471 tg.runFail("test", "p5")
3472 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3475 // Test that you cannot use a local import in a package
3476 // accessed by a non-local import (found in a GOPATH/GOROOT).
3477 // See golang.org/issue/17475.
3478 func TestImportLocal(t *testing.T) {
3485 tg.tempFile("src/dir/x/x.go", `package x
3488 tg.setenv("GOPATH", tg.path("."))
3489 tg.run("build", "dir/x")
3491 // Ordinary import should work.
3492 tg.tempFile("src/dir/p0/p.go", `package p0
3496 tg.run("build", "dir/p0")
3498 // Relative import should not.
3499 tg.tempFile("src/dir/p1/p.go", `package p1
3503 tg.runFail("build", "dir/p1")
3504 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3506 // ... even in a test.
3507 tg.tempFile("src/dir/p2/p.go", `package p2
3509 tg.tempFile("src/dir/p2/p_test.go", `package p2
3513 func TestFoo(t *testing.T) {}
3515 tg.run("build", "dir/p2")
3516 tg.runFail("test", "dir/p2")
3517 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3519 // ... even in an xtest.
3520 tg.tempFile("src/dir/p2/p_test.go", `package p2_test
3524 func TestFoo(t *testing.T) {}
3526 tg.run("build", "dir/p2")
3527 tg.runFail("test", "dir/p2")
3528 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3530 // Relative import starting with ./ should not work either.
3531 tg.tempFile("src/dir/d.go", `package dir
3535 tg.runFail("build", "dir")
3536 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3538 // ... even in a test.
3539 tg.tempFile("src/dir/d.go", `package dir
3541 tg.tempFile("src/dir/d_test.go", `package dir
3545 func TestFoo(t *testing.T) {}
3547 tg.run("build", "dir")
3548 tg.runFail("test", "dir")
3549 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3551 // ... even in an xtest.
3552 tg.tempFile("src/dir/d_test.go", `package dir_test
3556 func TestFoo(t *testing.T) {}
3558 tg.run("build", "dir")
3559 tg.runFail("test", "dir")
3560 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3562 // Relative import plain ".." should not work.
3563 tg.tempFile("src/dir/x/y/y.go", `package dir
3567 tg.runFail("build", "dir/x/y")
3568 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3570 // ... even in a test.
3571 tg.tempFile("src/dir/x/y/y.go", `package y
3573 tg.tempFile("src/dir/x/y/y_test.go", `package y
3577 func TestFoo(t *testing.T) {}
3579 tg.run("build", "dir/x/y")
3580 tg.runFail("test", "dir/x/y")
3581 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3583 // ... even in an x test.
3584 tg.tempFile("src/dir/x/y/y_test.go", `package y_test
3588 func TestFoo(t *testing.T) {}
3590 tg.run("build", "dir/x/y")
3591 tg.runFail("test", "dir/x/y")
3592 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3594 // Relative import "." should not work.
3595 tg.tempFile("src/dir/x/xx.go", `package x
3599 tg.runFail("build", "dir/x")
3600 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3602 // ... even in a test.
3603 tg.tempFile("src/dir/x/xx.go", `package x
3605 tg.tempFile("src/dir/x/xx_test.go", `package x
3609 func TestFoo(t *testing.T) {}
3611 tg.run("build", "dir/x")
3612 tg.runFail("test", "dir/x")
3613 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3615 // ... even in an xtest.
3616 tg.tempFile("src/dir/x/xx.go", `package x
3618 tg.tempFile("src/dir/x/xx_test.go", `package x_test
3622 func TestFoo(t *testing.T) {}
3624 tg.run("build", "dir/x")
3625 tg.runFail("test", "dir/x")
3626 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3629 func TestGoGetInsecure(t *testing.T) {
3630 test := func(t *testing.T, modules bool) {
3631 testenv.MustHaveExternalNetwork(t)
3639 tg.setenv("GOPATH", tg.path("gp"))
3640 tg.tempFile("go.mod", "module m")
3642 tg.setenv("GO111MODULE", "on")
3644 tg.setenv("GOPATH", tg.path("."))
3645 tg.setenv("GO111MODULE", "off")
3648 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3650 // Try go get -d of HTTP-only repo (should fail).
3651 tg.runFail("get", "-d", repo)
3653 // Try again with -insecure (should succeed).
3654 tg.run("get", "-d", "-insecure", repo)
3656 // Try updating without -insecure (should fail).
3657 tg.runFail("get", "-d", "-u", "-f", repo)
3660 tg.run("list", "-m", "...")
3661 tg.grepStdout("insecure.go-get-issue", "should find insecure module")
3665 t.Run("gopath", func(t *testing.T) { test(t, false) })
3666 t.Run("modules", func(t *testing.T) { test(t, true) })
3669 func TestGoGetUpdateInsecure(t *testing.T) {
3670 testenv.MustHaveExternalNetwork(t)
3675 tg.setenv("GOPATH", tg.path("."))
3677 const repo = "github.com/golang/example"
3679 // Clone the repo via HTTP manually.
3680 cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
3681 if out, err := cmd.CombinedOutput(); err != nil {
3682 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3685 // Update without -insecure should fail.
3686 // Update with -insecure should succeed.
3687 // We need -f to ignore import comments.
3688 const pkg = repo + "/hello"
3689 tg.runFail("get", "-d", "-u", "-f", pkg)
3690 tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
3693 func TestGoGetUpdateUnknownProtocol(t *testing.T) {
3694 testenv.MustHaveExternalNetwork(t)
3699 tg.setenv("GOPATH", tg.path("."))
3701 const repo = "github.com/golang/example"
3703 // Clone the repo via HTTPS manually.
3704 repoDir := tg.path("src/" + repo)
3705 cmd := exec.Command("git", "clone", "-q", "https://"+repo, repoDir)
3706 if out, err := cmd.CombinedOutput(); err != nil {
3707 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3710 // Configure the repo to use a protocol unknown to cmd/go
3711 // that still actually works.
3712 cmd = exec.Command("git", "remote", "set-url", "origin", "xyz://"+repo)
3714 if out, err := cmd.CombinedOutput(); err != nil {
3715 t.Fatalf("git remote set-url: %v\n%s", err, out)
3717 cmd = exec.Command("git", "config", "--local", "url.https://github.com/.insteadOf", "xyz://github.com/")
3719 if out, err := cmd.CombinedOutput(); err != nil {
3720 t.Fatalf("git config: %v\n%s", err, out)
3723 // We need -f to ignore import comments.
3724 tg.run("get", "-d", "-u", "-f", repo+"/hello")
3727 func TestGoGetInsecureCustomDomain(t *testing.T) {
3728 testenv.MustHaveExternalNetwork(t)
3733 tg.setenv("GOPATH", tg.path("."))
3735 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3736 tg.runFail("get", "-d", repo)
3737 tg.run("get", "-d", "-insecure", repo)
3740 func TestGoRunDirs(t *testing.T) {
3743 tg.cd("testdata/rundir")
3744 tg.runFail("run", "x.go", "sub/sub.go")
3745 tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
3746 tg.runFail("run", "sub/sub.go", "x.go")
3747 tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
3750 func TestGoInstallPkgdir(t *testing.T) {
3751 skipIfGccgo(t, "gccgo has no standard packages")
3759 tg.run("install", "-pkgdir", pkg, "sync")
3760 tg.mustExist(filepath.Join(pkg, "sync.a"))
3761 tg.mustNotExist(filepath.Join(pkg, "sync/atomic.a"))
3762 tg.run("install", "-i", "-pkgdir", pkg, "sync")
3763 tg.mustExist(filepath.Join(pkg, "sync.a"))
3764 tg.mustExist(filepath.Join(pkg, "sync/atomic.a"))
3767 func TestGoTestRaceInstallCgo(t *testing.T) {
3769 t.Skip("skipping because race detector not supported")
3772 // golang.org/issue/10500.
3773 // This used to install a race-enabled cgo.
3776 tg.run("tool", "-n", "cgo")
3777 cgo := strings.TrimSpace(tg.stdout.String())
3778 old, err := os.Stat(cgo)
3780 tg.run("test", "-race", "-i", "runtime/race")
3781 new, err := os.Stat(cgo)
3783 if !new.ModTime().Equal(old.ModTime()) {
3784 t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
3788 func TestGoTestRaceFailures(t *testing.T) {
3792 t.Skip("skipping because race detector not supported")
3798 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3800 tg.run("test", "testrace")
3802 tg.runFail("test", "-race", "testrace")
3803 tg.grepStdout("FAIL: TestRace", "TestRace did not fail")
3804 tg.grepBothNot("PASS", "something passed")
3806 tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".")
3807 tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail")
3808 tg.grepBothNot("PASS", "something passed")
3811 func TestGoTestImportErrorStack(t *testing.T) {
3812 const out = `package testdep/p1 (test)
3814 imports testdep/p3: build constraints exclude all Go files `
3818 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3819 tg.runFail("test", "testdep/p1")
3820 if !strings.Contains(tg.stderr.String(), out) {
3821 t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String())
3825 func TestGoGetUpdate(t *testing.T) {
3826 // golang.org/issue/9224.
3827 // The recursive updating was trying to walk to
3828 // former dependencies, not current ones.
3830 testenv.MustHaveExternalNetwork(t)
3835 tg.setenv("GOPATH", tg.path("."))
3838 tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
3839 cmd := exec.Command("git", "reset", "--hard", "HEAD~")
3840 cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
3841 out, err := cmd.CombinedOutput()
3843 t.Fatalf("git: %v\n%s", err, out)
3848 tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3850 // Again with -d -u.
3852 tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3856 func TestGoGetRace(t *testing.T) {
3857 testenv.MustHaveExternalNetwork(t)
3859 t.Skip("skipping because race detector not supported")
3865 tg.setenv("GOPATH", tg.path("."))
3866 tg.run("get", "-race", "github.com/rsc/go-get-issue-9224-cmd")
3869 func TestGoGetDomainRoot(t *testing.T) {
3870 // golang.org/issue/9357.
3871 // go get foo.io (not foo.io/subdir) was not working consistently.
3873 testenv.MustHaveExternalNetwork(t)
3878 tg.setenv("GOPATH", tg.path("."))
3880 // go-get-issue-9357.appspot.com is running
3881 // the code at github.com/rsc/go-get-issue-9357,
3882 // a trivial Go on App Engine app that serves a
3883 // <meta> tag for the domain root.
3884 tg.run("get", "-d", "go-get-issue-9357.appspot.com")
3885 tg.run("get", "go-get-issue-9357.appspot.com")
3886 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3888 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3889 tg.run("get", "go-get-issue-9357.appspot.com")
3891 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3892 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3895 func TestGoInstallShadowedGOPATH(t *testing.T) {
3896 // golang.org/issue/3652.
3897 // go get foo.io (not foo.io/subdir) was not working consistently.
3899 testenv.MustHaveExternalNetwork(t)
3904 tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
3906 tg.tempDir("gopath1/src/test")
3907 tg.tempDir("gopath2/src/test")
3908 tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
3910 tg.cd(tg.path("gopath2/src/test"))
3911 tg.runFail("install")
3912 tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
3915 func TestGoBuildGOPATHOrder(t *testing.T) {
3916 // golang.org/issue/14176#issuecomment-179895769
3917 // golang.org/issue/14192
3918 // -I arguments to compiler could end up not in GOPATH order,
3919 // leading to unexpected import resolution in the compiler.
3920 // This is still not a complete fix (see golang.org/issue/14271 and next test)
3921 // but it is clearly OK and enough to fix both of the two reported
3922 // instances of the underlying problem. It will have to do for now.
3927 tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2"))
3929 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3930 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3931 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3932 tg.tempFile("p1/src/bar/bar.go", `
3938 tg.run("install", "-x", "bar")
3941 func TestGoBuildGOPATHOrderBroken(t *testing.T) {
3942 // This test is known not to work.
3943 // See golang.org/issue/14271.
3944 t.Skip("golang.org/issue/14271")
3950 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3951 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3952 tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n")
3953 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3954 tg.tempFile("p1/src/bar/bar.go", `
3960 colon := string(filepath.ListSeparator)
3961 tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2"))
3962 tg.run("install", "-x", "bar")
3964 tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1"))
3965 tg.run("install", "-x", "bar")
3968 func TestIssue11709(t *testing.T) {
3971 tg.tempFile("run.go", `
3975 if os.Getenv("TERM") != "" {
3980 tg.run("run", tg.path("run.go"))
3983 func TestIssue12096(t *testing.T) {
3986 tg.tempFile("test_test.go", `
3988 import ("os"; "testing")
3989 func TestEnv(t *testing.T) {
3990 if os.Getenv("TERM") != "" {
3991 t.Fatal("TERM is set")
3995 tg.run("test", tg.path("test_test.go"))
3998 func TestGoBuildOutput(t *testing.T) {
3999 skipIfGccgo(t, "gccgo has no standard packages")
4007 nonExeSuffix := ".exe"
4008 if exeSuffix == ".exe" {
4012 tg.tempFile("x.go", "package main\nfunc main(){}\n")
4013 tg.run("build", "x.go")
4014 tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
4015 tg.must(os.Remove(tg.path("x" + exeSuffix)))
4016 tg.mustNotExist("x" + nonExeSuffix)
4018 tg.run("build", "-o", "myprog", "x.go")
4019 tg.mustNotExist("x")
4020 tg.mustNotExist("x.exe")
4021 tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
4022 tg.mustNotExist("myprog.exe")
4024 tg.tempFile("p.go", "package p\n")
4025 tg.run("build", "p.go")
4026 tg.mustNotExist("p")
4027 tg.mustNotExist("p.a")
4028 tg.mustNotExist("p.o")
4029 tg.mustNotExist("p.exe")
4031 tg.run("build", "-o", "p.a", "p.go")
4032 tg.wantArchive("p.a")
4034 tg.run("build", "cmd/gofmt")
4035 tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
4036 tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
4037 tg.mustNotExist("gofmt" + nonExeSuffix)
4039 tg.run("build", "-o", "mygofmt", "cmd/gofmt")
4040 tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
4041 tg.mustNotExist("mygofmt.exe")
4042 tg.mustNotExist("gofmt")
4043 tg.mustNotExist("gofmt.exe")
4045 tg.run("build", "sync/atomic")
4046 tg.mustNotExist("atomic")
4047 tg.mustNotExist("atomic.exe")
4049 tg.run("build", "-o", "myatomic.a", "sync/atomic")
4050 tg.wantArchive("myatomic.a")
4051 tg.mustNotExist("atomic")
4052 tg.mustNotExist("atomic.a")
4053 tg.mustNotExist("atomic.exe")
4055 tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
4056 tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
4059 func TestGoBuildARM(t *testing.T) {
4060 if testing.Short() {
4061 t.Skip("skipping cross-compile in short mode")
4070 tg.setenv("GOARCH", "arm")
4071 tg.setenv("GOOS", "linux")
4072 tg.setenv("GOARM", "5")
4073 tg.tempFile("hello.go", `package main
4075 tg.run("build", "hello.go")
4076 tg.grepStderrNot("unable to find math.a", "did not build math.a correctly")
4080 func TestParallelTest(t *testing.T) {
4086 const testSrc = `package package_test
4090 func TestTest(t *testing.T) {
4092 tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
4093 tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
4094 tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
4095 tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
4096 tg.setenv("GOPATH", tg.path("."))
4097 tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
4100 func TestCgoConsistentResults(t *testing.T) {
4103 t.Skip("skipping because cgo not enabled")
4105 switch runtime.GOOS {
4107 testenv.SkipFlaky(t, 13247)
4114 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4115 exe1 := tg.path("cgotest1" + exeSuffix)
4116 exe2 := tg.path("cgotest2" + exeSuffix)
4117 tg.run("build", "-o", exe1, "cgotest")
4118 tg.run("build", "-x", "-o", exe2, "cgotest")
4119 b1, err := ioutil.ReadFile(exe1)
4121 b2, err := ioutil.ReadFile(exe2)
4124 if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) {
4125 t.Skip("skipping because C compiler does not support -fdebug-prefix-map")
4127 if !bytes.Equal(b1, b2) {
4128 t.Error("building cgotest twice did not produce the same output")
4132 // Issue 14444: go get -u .../ duplicate loads errors
4133 func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) {
4134 testenv.MustHaveExternalNetwork(t)
4139 tg.setenv("GOPATH", tg.path("."))
4140 tg.run("get", "-u", ".../")
4141 tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache")
4144 // Issue 17119 more duplicate load errors
4145 func TestIssue17119(t *testing.T) {
4146 testenv.MustHaveExternalNetwork(t)
4151 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4152 tg.runFail("build", "dupload")
4153 tg.grepBothNot("duplicate load|internal error", "internal error")
4156 func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) {
4159 // TODO: tg.parallel()
4160 tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal")
4161 tg.grepBothNot("^ok", "test passed unexpectedly")
4162 tg.grepBoth("FAIL.*benchfatal", "test did not run everything")
4165 func TestBinaryOnlyPackages(t *testing.T) {
4172 tg.setenv("GOPATH", tg.path("."))
4174 tg.tempFile("src/p1/p1.go", `//go:binary-only-package
4178 tg.wantStale("p1", "missing or invalid binary-only package", "p1 is binary-only but has no binary, should be stale")
4179 tg.runFail("install", "p1")
4180 tg.grepStderr("missing or invalid binary-only package", "did not report attempt to compile binary-only package")
4182 tg.tempFile("src/p1/p1.go", `
4185 func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } }
4187 tg.run("install", "p1")
4188 os.Remove(tg.path("src/p1/p1.go"))
4189 tg.mustNotExist(tg.path("src/p1/p1.go"))
4191 tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great
4195 func F() { p1.F(true) }
4197 tg.runFail("install", "p2")
4198 tg.grepStderr("no Go files", "did not complain about missing sources")
4200 tg.tempFile("src/p1/missing.go", `//go:binary-only-package
4206 tg.wantNotStale("p1", "binary-only package", "should NOT want to rebuild p1 (first)")
4207 tg.run("install", "-x", "p1") // no-op, up to date
4208 tg.grepBothNot(`[\\/]compile`, "should not have run compiler")
4209 tg.run("install", "p2") // does not rebuild p1 (or else p2 will fail)
4210 tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
4212 // changes to the non-source-code do not matter,
4213 // and only one file needs the special comment.
4214 tg.tempFile("src/p1/missing2.go", `
4218 tg.wantNotStale("p1", "binary-only package", "should NOT want to rebuild p1 (second)")
4219 tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
4221 tg.tempFile("src/p3/p3.go", `
4232 tg.run("install", "p3")
4234 tg.run("run", tg.path("src/p3/p3.go"))
4235 tg.grepStdout("hello from p1", "did not see message from p1")
4237 tg.tempFile("src/p4/p4.go", `package main`)
4238 // The odd string split below avoids vet complaining about
4239 // a // +build line appearing too late in this source file.
4240 tg.tempFile("src/p4/p4not.go", `//go:binary-only-package
4246 tg.run("list", "-f", "{{.BinaryOnly}}", "p4")
4247 tg.grepStdout("false", "did not see BinaryOnly=false for p4")
4250 // Issue 16050 and 21884.
4251 func TestLinkSysoFiles(t *testing.T) {
4252 if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
4253 t.Skip("not linux/amd64")
4259 tg.tempDir("src/syso")
4260 tg.tempFile("src/syso/a.syso", ``)
4261 tg.tempFile("src/syso/b.go", `package syso`)
4262 tg.setenv("GOPATH", tg.path("."))
4264 // We should see the .syso file regardless of the setting of
4267 tg.setenv("CGO_ENABLED", "1")
4268 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4269 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1")
4271 tg.setenv("CGO_ENABLED", "0")
4272 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4273 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0")
4275 tg.setenv("CGO_ENABLED", "1")
4276 tg.run("list", "-msan", "-f", "{{.SysoFiles}}", "syso")
4277 tg.grepStdoutNot("a.syso", "unexpected syso file with -msan")
4281 func TestGenerateUsesBuildContext(t *testing.T) {
4282 if runtime.GOOS == "windows" {
4283 t.Skip("this test won't run under Windows")
4289 tg.tempDir("src/gen")
4290 tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n")
4291 tg.setenv("GOPATH", tg.path("."))
4293 tg.setenv("GOOS", "linux")
4294 tg.setenv("GOARCH", "amd64")
4295 tg.run("generate", "gen")
4296 tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination")
4298 tg.setenv("GOOS", "darwin")
4299 tg.setenv("GOARCH", "386")
4300 tg.run("generate", "gen")
4301 tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination")
4304 // Issue 14450: go get -u .../ tried to import not downloaded package
4305 func TestGoGetUpdateWithWildcard(t *testing.T) {
4306 testenv.MustHaveExternalNetwork(t)
4312 tg.setenv("GOPATH", tg.path("."))
4313 const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a"
4314 tg.run("get", aPkgImportPath)
4315 tg.runFail("get", "-u", ".../")
4316 tg.grepStderr("cannot find package.*d-dependency/e", "should have detected e missing")
4318 // Even though get -u failed, the source for others should be downloaded.
4319 var expectedPkgPaths = []string{
4320 "src/github.com/tmwh/go-get-issue-14450/b",
4321 "src/github.com/tmwh/go-get-issue-14450-b-dependency/c",
4322 "src/github.com/tmwh/go-get-issue-14450-b-dependency/d",
4325 for _, importPath := range expectedPkgPaths {
4326 _, err := os.Stat(tg.path(importPath))
4329 const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e"
4330 tg.mustNotExist(tg.path(notExpectedPkgPath))
4333 func TestGoEnv(t *testing.T) {
4337 tg.setenv("GOOS", "freebsd") // to avoid invalid pair errors
4338 tg.setenv("GOARCH", "arm")
4339 tg.run("env", "GOARCH")
4340 tg.grepStdout("^arm$", "GOARCH not honored")
4342 tg.run("env", "GCCGO")
4343 tg.grepStdout(".", "GCCGO unexpectedly empty")
4345 tg.run("env", "CGO_CFLAGS")
4346 tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty")
4348 tg.setenv("CGO_CFLAGS", "-foobar")
4349 tg.run("env", "CGO_CFLAGS")
4350 tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored")
4352 tg.setenv("CC", "gcc -fmust -fgo -ffaster")
4354 tg.grepStdout("gcc", "CC not found")
4355 tg.run("env", "GOGCCFLAGS")
4356 tg.grepStdout("-ffaster", "CC arguments not found")
4360 noMatchesPattern = `(?m)^ok.*\[no tests to run\]`
4361 okPattern = `(?m)^ok`
4364 func TestMatchesNoTests(t *testing.T) {
4367 // TODO: tg.parallel()
4368 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go")
4369 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4372 func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) {
4376 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4377 tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror")
4378 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4379 tg.grepBoth("FAIL", "go test did not say FAIL")
4382 func TestMatchesNoBenchmarksIsOK(t *testing.T) {
4385 // TODO: tg.parallel()
4386 tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go")
4387 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4388 tg.grepBoth(okPattern, "go test did not say ok")
4391 func TestMatchesOnlyExampleIsOK(t *testing.T) {
4394 // TODO: tg.parallel()
4395 tg.run("test", "-run", "Example", "testdata/example1_test.go")
4396 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4397 tg.grepBoth(okPattern, "go test did not say ok")
4400 func TestMatchesOnlyBenchmarkIsOK(t *testing.T) {
4403 // TODO: tg.parallel()
4404 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4405 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4406 tg.grepBoth(okPattern, "go test did not say ok")
4409 func TestBenchmarkLabels(t *testing.T) {
4412 // TODO: tg.parallel()
4413 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4414 tg.run("test", "-run", "^$", "-bench", ".", "bench")
4415 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4416 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4417 tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench")
4418 tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times")
4421 func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) {
4424 // TODO: tg.parallel()
4425 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4426 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4427 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4428 tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:")
4431 func TestMatchesOnlyTestIsOK(t *testing.T) {
4434 // TODO: tg.parallel()
4435 tg.run("test", "-run", "Test", "testdata/standalone_test.go")
4436 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4437 tg.grepBoth(okPattern, "go test did not say ok")
4440 func TestMatchesNoTestsWithSubtests(t *testing.T) {
4443 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go")
4444 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4447 func TestMatchesNoSubtestsMatch(t *testing.T) {
4450 tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go")
4451 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4454 func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) {
4457 tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go")
4458 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4459 tg.grepBoth("FAIL", "go test did not say FAIL")
4462 func TestMatchesOnlySubtestIsOK(t *testing.T) {
4465 tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go")
4466 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4467 tg.grepBoth(okPattern, "go test did not say ok")
4470 func TestMatchesNoSubtestsParallel(t *testing.T) {
4473 tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go")
4474 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4477 func TestMatchesOnlySubtestParallelIsOK(t *testing.T) {
4480 tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go")
4481 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4482 tg.grepBoth(okPattern, "go test did not say ok")
4486 func TestBenchTimeout(t *testing.T) {
4490 tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go")
4494 func TestWriteProfilesOnTimeout(t *testing.T) {
4498 tg.tempDir("profiling")
4499 tg.tempFile("profiling/timeouttest_test.go", `package timeouttest_test
4502 func TestSleep(t *testing.T) { time.Sleep(time.Second) }`)
4503 tg.cd(tg.path("profiling"))
4506 "-cpuprofile", tg.path("profiling/cpu.pprof"), "-memprofile", tg.path("profiling/mem.pprof"),
4508 tg.mustHaveContent(tg.path("profiling/cpu.pprof"))
4509 tg.mustHaveContent(tg.path("profiling/mem.pprof"))
4512 func TestLinkXImportPathEscape(t *testing.T) {
4513 // golang.org/issue/16710
4514 skipIfGccgo(t, "gccgo does not support -ldflags -X")
4518 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4519 exe := "./linkx" + exeSuffix
4520 tg.creatingTemp(exe)
4521 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main")
4522 out, err := exec.Command(exe).CombinedOutput()
4526 if string(out) != "linkXworked\n" {
4527 tg.t.Log(string(out))
4528 tg.t.Fatal(`incorrect output: expected "linkXworked\n"`)
4533 func TestLdBindNow(t *testing.T) {
4537 tg.setenv("LD_BIND_NOW", "1")
4542 // This is really a cmd/asm issue but this is a convenient place to test it.
4543 func TestConcurrentAsm(t *testing.T) {
4544 skipIfGccgo(t, "gccgo does not use cmd/asm")
4548 asm := `DATA ·constants<>+0x0(SB)/8,$0
4549 GLOBL ·constants<>(SB),8,$8
4551 tg.tempFile("go/src/p/a.s", asm)
4552 tg.tempFile("go/src/p/b.s", asm)
4553 tg.tempFile("go/src/p/p.go", `package p`)
4554 tg.setenv("GOPATH", tg.path("go"))
4555 tg.run("build", "p")
4559 func TestDotDotDotOutsideGOPATH(t *testing.T) {
4563 tg.tempFile("pkgs/a.go", `package x`)
4564 tg.tempFile("pkgs/a_test.go", `package x_test
4566 func TestX(t *testing.T) {}`)
4568 tg.tempFile("pkgs/a/a.go", `package a`)
4569 tg.tempFile("pkgs/a/a_test.go", `package a_test
4571 func TestA(t *testing.T) {}`)
4573 tg.cd(tg.path("pkgs"))
4574 tg.run("build", "./...")
4575 tg.run("test", "./...")
4576 tg.run("list", "./...")
4577 tg.grepStdout("pkgs$", "expected package not listed")
4578 tg.grepStdout("pkgs/a", "expected package not listed")
4582 func TestFFLAGS(t *testing.T) {
4584 t.Skip("skipping because cgo not enabled")
4591 tg.tempFile("p/src/p/main.go", `package main
4592 // #cgo FFLAGS: -no-such-fortran-flag
4596 tg.tempFile("p/src/p/a.f", `! comment`)
4597 tg.setenv("GOPATH", tg.path("p"))
4599 // This should normally fail because we are passing an unknown flag,
4600 // but issue #19080 points to Fortran compilers that succeed anyhow.
4601 // To work either way we call doRun directly rather than run or runFail.
4602 tg.doRun([]string{"build", "-x", "p"})
4604 tg.grepStderr("no-such-fortran-flag", `missing expected "-no-such-fortran-flag"`)
4608 // This is really a cmd/link issue but this is a convenient place to test it.
4609 func TestDuplicateGlobalAsmSymbols(t *testing.T) {
4610 skipIfGccgo(t, "gccgo does not use cmd/asm")
4612 if runtime.GOARCH != "386" && runtime.GOARCH != "amd64" {
4613 t.Skipf("skipping test on %s", runtime.GOARCH)
4616 t.Skip("skipping because cgo not enabled")
4624 #include "textflag.h"
4626 DATA sym<>+0x0(SB)/8,$0
4627 GLOBL sym<>(SB),(NOPTR+RODATA),$8
4629 TEXT ·Data(SB),NOSPLIT,$0
4634 tg.tempFile("go/src/a/a.s", asm)
4635 tg.tempFile("go/src/a/a.go", `package a; func Data() uint8`)
4636 tg.tempFile("go/src/b/b.s", asm)
4637 tg.tempFile("go/src/b/b.go", `package b; func Data() uint8`)
4638 tg.tempFile("go/src/p/p.go", `
4644 _ = a.Data() + b.Data()
4647 tg.setenv("GOPATH", tg.path("go"))
4648 exe := tg.path("p.exe")
4649 tg.creatingTemp(exe)
4650 tg.run("build", "-o", exe, "p")
4653 func TestBuildTagsNoComma(t *testing.T) {
4654 skipIfGccgo(t, "gccgo has no standard packages")
4658 tg.setenv("GOPATH", tg.path("go"))
4659 tg.run("build", "-tags", "tag1 tag2", "math")
4660 tg.runFail("build", "-tags", "tag1,tag2", "math")
4661 tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
4664 func copyFile(src, dst string, perm os.FileMode) error {
4665 sf, err := os.Open(src)
4671 df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
4676 _, err = io.Copy(df, sf)
4684 func TestExecutableGOROOT(t *testing.T) {
4685 skipIfGccgo(t, "gccgo has no GOROOT")
4686 if runtime.GOOS == "openbsd" {
4687 t.Skipf("test case does not work on %s, missing os.Executable", runtime.GOOS)
4690 // Env with no GOROOT.
4692 for _, e := range os.Environ() {
4693 if !strings.HasPrefix(e, "GOROOT=") {
4694 env = append(env, e)
4698 check := func(t *testing.T, exe, want string) {
4699 cmd := exec.Command(exe, "env", "GOROOT")
4701 out, err := cmd.CombinedOutput()
4703 t.Fatalf("%s env GOROOT: %v, %s", exe, err, out)
4705 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4709 want, err = filepath.EvalSymlinks(want)
4713 if !strings.EqualFold(goroot, want) {
4714 t.Errorf("go env GOROOT:\nhave %s\nwant %s", goroot, want)
4716 t.Logf("go env GOROOT: %s", goroot)
4720 // Note: Must not call tg methods inside subtests: tg is attached to outer t.
4725 tg.tempDir("new/bin")
4726 newGoTool := tg.path("new/bin/go" + exeSuffix)
4727 tg.must(copyFile(tg.goTool(), newGoTool, 0775))
4728 newRoot := tg.path("new")
4730 t.Run("RelocatedExe", func(t *testing.T) {
4731 // Should fall back to default location in binary,
4732 // which is the GOROOT we used when building testgo.exe.
4733 check(t, newGoTool, testGOROOT)
4736 // If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT,
4737 // so it should find the new tree.
4738 tg.tempDir("new/pkg/tool")
4739 t.Run("RelocatedTree", func(t *testing.T) {
4740 check(t, newGoTool, newRoot)
4743 tg.tempDir("other/bin")
4744 symGoTool := tg.path("other/bin/go" + exeSuffix)
4746 // Symlink into go tree should still find go tree.
4747 t.Run("SymlinkedExe", func(t *testing.T) {
4748 testenv.MustHaveSymlink(t)
4749 if err := os.Symlink(newGoTool, symGoTool); err != nil {
4752 check(t, symGoTool, newRoot)
4755 tg.must(os.RemoveAll(tg.path("new/pkg")))
4757 // Binaries built in the new tree should report the
4758 // new tree when they call runtime.GOROOT.
4759 t.Run("RuntimeGoroot", func(t *testing.T) {
4760 // Build a working GOROOT the easy way, with symlinks.
4761 testenv.MustHaveSymlink(t)
4762 if err := os.Symlink(filepath.Join(testGOROOT, "src"), tg.path("new/src")); err != nil {
4765 if err := os.Symlink(filepath.Join(testGOROOT, "pkg"), tg.path("new/pkg")); err != nil {
4769 cmd := exec.Command(newGoTool, "run", "testdata/print_goroot.go")
4771 out, err := cmd.CombinedOutput()
4773 t.Fatalf("%s run testdata/print_goroot.go: %v, %s", newGoTool, err, out)
4775 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4779 want, err := filepath.EvalSymlinks(tg.path("new"))
4783 if !strings.EqualFold(goroot, want) {
4784 t.Errorf("go run testdata/print_goroot.go:\nhave %s\nwant %s", goroot, want)
4786 t.Logf("go run testdata/print_goroot.go: %s", goroot)
4791 func TestNeedVersion(t *testing.T) {
4792 skipIfGccgo(t, "gccgo does not use cmd/compile")
4796 tg.tempFile("goversion.go", `package main; func main() {}`)
4797 path := tg.path("goversion.go")
4798 tg.setenv("TESTGO_VERSION", "go1.testgo")
4799 tg.runFail("run", path)
4800 tg.grepStderr("compile", "does not match go tool version")
4803 // Test that user can override default code generation flags.
4804 func TestUserOverrideFlags(t *testing.T) {
4805 skipIfGccgo(t, "gccgo does not use -gcflags")
4807 t.Skip("skipping because cgo not enabled")
4809 if runtime.GOOS != "linux" {
4810 // We are testing platform-independent code, so it's
4811 // OK to skip cases that work differently.
4812 t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS)
4817 // Don't call tg.parallel, as creating override.h and override.a may
4818 // confuse other tests.
4819 tg.tempFile("override.go", `package main
4827 tg.creatingTemp("override.a")
4828 tg.creatingTemp("override.h")
4829 tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=all=-shared=false", tg.path("override.go"))
4830 tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag")
4833 func TestCgoFlagContainsSpace(t *testing.T) {
4836 t.Skip("skipping because cgo not enabled")
4843 tg.tempFile("main.go", `package main
4844 // #cgo CFLAGS: -I"c flags"
4845 // #cgo LDFLAGS: -L"ld flags"
4849 tg.run("run", "-x", "main.go")
4850 tg.grepStderr(`"-I[^"]+c flags"`, "did not find quoted c flags")
4851 tg.grepStderrNot(`"-I[^"]+c flags".*"-I[^"]+c flags"`, "found too many quoted c flags")
4852 tg.grepStderr(`"-L[^"]+ld flags"`, "did not find quoted ld flags")
4853 tg.grepStderrNot(`"-L[^"]+c flags".*"-L[^"]+c flags"`, "found too many quoted ld flags")
4857 func TestGoTestRaceCoverModeFailures(t *testing.T) {
4860 t.Skip("skipping because race detector not supported")
4866 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4868 tg.run("test", "testrace")
4870 tg.runFail("test", "-race", "-covermode=set", "testrace")
4871 tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed")
4872 tg.grepBothNot("PASS", "something passed")
4875 // Issue 9737: verify that GOARM and GO386 affect the computed build ID.
4876 func TestBuildIDContainsArchModeEnv(t *testing.T) {
4877 if testing.Short() {
4878 t.Skip("skipping in short mode")
4882 testWith := func(before, after func()) func(*testing.T) {
4883 return func(t *testing.T) {
4886 tg.tempFile("src/mycmd/x.go", `package main
4888 tg.setenv("GOPATH", tg.path("."))
4890 tg.cd(tg.path("src/mycmd"))
4891 tg.setenv("GOOS", "linux")
4893 tg.run("install", "mycmd")
4895 tg.wantStale("mycmd", "stale dependency", "should be stale after environment variable change")
4899 t.Run("386", testWith(func() {
4900 tg.setenv("GOARCH", "386")
4901 tg.setenv("GO386", "387")
4903 tg.setenv("GO386", "sse2")
4906 t.Run("arm", testWith(func() {
4907 tg.setenv("GOARCH", "arm")
4908 tg.setenv("GOARM", "5")
4910 tg.setenv("GOARM", "7")
4914 func TestTestRegexps(t *testing.T) {
4917 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4918 tg.run("test", "-cpu=1", "-run=X/Y", "-bench=X/Y", "-count=2", "-v", "testregexp")
4920 for _, line := range strings.SplitAfter(tg.getStdout(), "\n") {
4921 if strings.Contains(line, "=== RUN") || strings.Contains(line, "--- BENCH") || strings.Contains(line, "LOG") {
4922 lines = append(lines, line)
4927 // TestX is run, twice
4928 // TestX/Y is run, twice
4929 // TestXX is run, twice
4931 // BenchmarkX is run but only with N=1, once
4932 // BenchmarkXX is run but only with N=1, once
4933 // BenchmarkX/Y is run in full, twice
4934 want := `=== RUN TestX
4936 x_test.go:6: LOG: X running
4937 x_test.go:8: LOG: Y running
4939 z_test.go:10: LOG: XX running
4942 x_test.go:6: LOG: X running
4943 x_test.go:8: LOG: Y running
4945 z_test.go:10: LOG: XX running
4946 --- BENCH: BenchmarkX/Y
4947 x_test.go:15: LOG: Y running N=1
4948 x_test.go:15: LOG: Y running N=100
4949 x_test.go:15: LOG: Y running N=10000
4950 x_test.go:15: LOG: Y running N=1000000
4951 x_test.go:15: LOG: Y running N=100000000
4952 x_test.go:15: LOG: Y running N=2000000000
4953 --- BENCH: BenchmarkX/Y
4954 x_test.go:15: LOG: Y running N=1
4955 x_test.go:15: LOG: Y running N=100
4956 x_test.go:15: LOG: Y running N=10000
4957 x_test.go:15: LOG: Y running N=1000000
4958 x_test.go:15: LOG: Y running N=100000000
4959 x_test.go:15: LOG: Y running N=2000000000
4960 --- BENCH: BenchmarkX
4961 x_test.go:13: LOG: X running N=1
4962 --- BENCH: BenchmarkXX
4963 z_test.go:18: LOG: XX running N=1
4966 have := strings.Join(lines, "")
4968 t.Errorf("reduced output:<<<\n%s>>> want:<<<\n%s>>>", have, want)
4972 func TestListTests(t *testing.T) {
4975 testWith := func(listName, expected string) func(*testing.T) {
4976 return func(t *testing.T) {
4979 tg.run("test", "./testdata/src/testlist/...", fmt.Sprintf("-list=%s", listName))
4980 tg.grepStdout(expected, fmt.Sprintf("-test.list=%s returned %q, expected %s", listName, tg.getStdout(), expected))
4984 t.Run("Test", testWith("Test", "TestSimple"))
4985 t.Run("Bench", testWith("Benchmark", "BenchmarkSimple"))
4986 t.Run("Example1", testWith("Example", "ExampleSimple"))
4987 t.Run("Example2", testWith("Example", "ExampleWithEmptyOutput"))
4990 func TestBuildmodePIE(t *testing.T) {
4991 if testing.Short() && testenv.Builder() == "" {
4992 t.Skipf("skipping in -short mode on non-builder")
4995 platform := fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
4997 case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x",
4998 "android/amd64", "android/arm", "android/arm64", "android/386",
5000 case "darwin/amd64":
5002 t.Skipf("skipping test because buildmode=pie is not supported on %s", platform)
5008 tg.tempFile("main.go", `package main; func main() { print("hello") }`)
5009 src := tg.path("main.go")
5010 obj := tg.path("main")
5011 tg.run("build", "-buildmode=pie", "-o", obj, src)
5013 switch runtime.GOOS {
5014 case "linux", "android", "freebsd":
5015 f, err := elf.Open(obj)
5020 if f.Type != elf.ET_DYN {
5021 t.Errorf("PIE type must be ET_DYN, but %s", f.Type)
5024 f, err := macho.Open(obj)
5029 if f.Flags&macho.FlagDyldLink == 0 {
5030 t.Error("PIE must have DyldLink flag, but not")
5032 if f.Flags&macho.FlagPIE == 0 {
5033 t.Error("PIE must have PIE flag, but not")
5036 panic("unreachable")
5039 out, err := exec.Command(obj).CombinedOutput()
5044 if string(out) != "hello" {
5045 t.Errorf("got %q; want %q", out, "hello")
5049 func TestExecBuildX(t *testing.T) {
5052 t.Skip("skipping because cgo not enabled")
5055 if runtime.GOOS == "plan9" || runtime.GOOS == "windows" {
5056 t.Skipf("skipping because unix shell is not supported on %s", runtime.GOOS)
5063 tg.setenv("GOCACHE", tg.path("cache"))
5065 tg.tempFile("main.go", `package main; import "C"; func main() { print("hello") }`)
5066 src := tg.path("main.go")
5067 obj := tg.path("main")
5068 tg.run("build", "-x", "-o", obj, src)
5069 sh := tg.path("test.sh")
5070 err := ioutil.WriteFile(sh, []byte("set -e\n"+tg.getStderr()), 0666)
5075 out, err := exec.Command(obj).CombinedOutput()
5079 if string(out) != "hello" {
5080 t.Fatalf("got %q; want %q", out, "hello")
5083 err = os.Remove(obj)
5088 out, err = exec.Command("/usr/bin/env", "bash", "-x", sh).CombinedOutput()
5090 t.Fatalf("/bin/sh %s: %v\n%s", sh, err, out)
5092 t.Logf("shell output:\n%s", out)
5094 out, err = exec.Command(obj).CombinedOutput()
5098 if string(out) != "hello" {
5099 t.Fatalf("got %q; want %q", out, "hello")
5103 func TestParallelNumber(t *testing.T) {
5105 for _, n := range [...]string{"-1", "0"} {
5106 t.Run(n, func(t *testing.T) {
5109 tg.runFail("test", "-parallel", n, "testdata/standalone_parallel_sub_test.go")
5110 tg.grepBoth("-parallel can only be given", "go test -parallel with N<1 did not error")
5115 func TestWrongGOOSErrorBeforeLoadError(t *testing.T) {
5116 skipIfGccgo(t, "gccgo assumes cross-compilation is always possible")
5119 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5120 tg.setenv("GOOS", "windwos")
5121 tg.runFail("build", "exclude")
5122 tg.grepStderr("unsupported GOOS/GOARCH pair", "GOOS=windwos go build exclude did not report 'unsupported GOOS/GOARCH pair'")
5125 func TestUpxCompression(t *testing.T) {
5126 if runtime.GOOS != "linux" ||
5127 (runtime.GOARCH != "amd64" && runtime.GOARCH != "386") {
5128 t.Skipf("skipping upx test on %s/%s", runtime.GOOS, runtime.GOARCH)
5131 out, err := exec.Command("upx", "--version").CombinedOutput()
5133 t.Skip("skipping because upx is not available")
5136 // upx --version prints `upx <version>` in the first line of output:
5139 re := regexp.MustCompile(`([[:digit:]]+)\.([[:digit:]]+)`)
5140 upxVersion := re.FindStringSubmatch(string(out))
5141 if len(upxVersion) != 3 {
5142 t.Errorf("bad upx version string: %s", upxVersion)
5145 major, err1 := strconv.Atoi(upxVersion[1])
5146 minor, err2 := strconv.Atoi(upxVersion[2])
5147 if err1 != nil || err2 != nil {
5148 t.Errorf("bad upx version string: %s", upxVersion[0])
5151 // Anything below 3.94 is known not to work with go binaries
5152 if (major < 3) || (major == 3 && minor < 94) {
5153 t.Skipf("skipping because upx version %v.%v is too old", major, minor)
5159 tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello upx") }`)
5160 src := tg.path("main.go")
5161 obj := tg.path("main")
5162 tg.run("build", "-o", obj, src)
5164 out, err = exec.Command("upx", obj).CombinedOutput()
5166 t.Logf("executing upx\n%s\n", out)
5167 t.Fatalf("upx failed with %v", err)
5170 out, err = exec.Command(obj).CombinedOutput()
5173 t.Fatalf("running compressed go binary failed with error %s", err)
5175 if string(out) != "hello upx" {
5176 t.Fatalf("bad output from compressed go binary:\ngot %q; want %q", out, "hello upx")
5180 // Test that Go binaries can be run under QEMU in user-emulation mode
5181 // (See issue #13024).
5182 func TestQEMUUserMode(t *testing.T) {
5183 if testing.Short() && testenv.Builder() == "" {
5184 t.Skipf("skipping in -short mode on non-builder")
5187 testArchs := []struct {
5191 {"arm64", "aarch64"},
5196 tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello qemu-user") }`)
5198 src, obj := tg.path("main.go"), tg.path("main")
5200 for _, arch := range testArchs {
5201 out, err := exec.Command("qemu-"+arch.qemu, "--version").CombinedOutput()
5203 t.Logf("Skipping %s test (qemu-%s not available)", arch.g, arch.qemu)
5207 tg.setenv("GOARCH", arch.g)
5208 tg.run("build", "-o", obj, src)
5210 out, err = exec.Command("qemu-"+arch.qemu, obj).CombinedOutput()
5212 t.Logf("qemu-%s output:\n%s\n", arch.qemu, out)
5213 t.Errorf("qemu-%s failed with %v", arch.qemu, err)
5216 if want := "hello qemu-user"; string(out) != want {
5217 t.Errorf("bad output from qemu-%s:\ngot %s; want %s", arch.qemu, out, want)
5223 func TestCacheListStale(t *testing.T) {
5225 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5226 t.Skip("GODEBUG gocacheverify")
5232 tg.setenv("GOCACHE", tg.path("cache"))
5233 tg.tempFile("gopath/src/p/p.go", "package p; import _ \"q\"; func F(){}\n")
5234 tg.tempFile("gopath/src/q/q.go", "package q; func F(){}\n")
5235 tg.tempFile("gopath/src/m/m.go", "package main; import _ \"q\"; func main(){}\n")
5237 tg.setenv("GOPATH", tg.path("gopath"))
5238 tg.run("install", "p", "m")
5239 tg.run("list", "-f={{.ImportPath}} {{.Stale}}", "m", "q", "p")
5240 tg.grepStdout("^m false", "m should not be stale")
5241 tg.grepStdout("^q true", "q should be stale")
5242 tg.grepStdout("^p false", "p should not be stale")
5245 func TestCacheCoverage(t *testing.T) {
5248 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5249 t.Skip("GODEBUG gocacheverify")
5255 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5258 tg.setenv("GOCACHE", tg.path("c1"))
5259 tg.run("test", "-cover", "-short", "strings")
5260 tg.run("test", "-cover", "-short", "math", "strings")
5263 func TestCacheVet(t *testing.T) {
5264 skipIfGccgo(t, "gccgo has no standard packages")
5269 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5270 t.Skip("GODEBUG gocacheverify")
5272 if os.Getenv("GOCACHE") == "off" {
5275 tg.setenv("GOCACHE", tg.path("cache"))
5278 // Check that second vet reuses cgo-derived inputs.
5279 // The first command could be build instead of vet,
5280 // except that if the cache is empty and there's a net.a
5281 // in GOROOT/pkg, the build will not bother to regenerate
5282 // and cache the cgo outputs, whereas vet always will.
5283 tg.run("vet", "os/user")
5284 tg.run("vet", "-x", "os/user")
5285 tg.grepStderrNot(`^(clang|gcc)`, "should not have run compiler")
5286 tg.grepStderrNot(`[\\/]cgo `, "should not have run cgo")
5289 func TestIssue22588(t *testing.T) {
5290 // Don't get confused by stderr coming from tools.
5295 if _, err := os.Stat("/usr/bin/time"); err != nil {
5299 tg.run("list", "-f={{.Stale}}", "runtime")
5300 tg.run("list", "-toolexec=/usr/bin/time", "-f={{.Stale}}", "runtime")
5301 tg.grepStdout("false", "incorrectly reported runtime as stale")
5304 func TestIssue22531(t *testing.T) {
5306 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5307 t.Skip("GODEBUG gocacheverify")
5313 tg.setenv("GOPATH", tg.tempdir)
5314 tg.setenv("GOCACHE", tg.path("cache"))
5315 tg.tempFile("src/m/main.go", "package main /* c1 */; func main() {}\n")
5316 tg.run("install", "-x", "m")
5317 tg.run("list", "-f", "{{.Stale}}", "m")
5318 tg.grepStdout("false", "reported m as stale after install")
5319 tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5321 // The link action ID did not include the full main build ID,
5322 // even though the full main build ID is written into the
5323 // eventual binary. That caused the following install to
5324 // be a no-op, thinking the gofmt binary was up-to-date,
5325 // even though .Stale could see it was not.
5326 tg.tempFile("src/m/main.go", "package main /* c2 */; func main() {}\n")
5327 tg.run("install", "-x", "m")
5328 tg.run("list", "-f", "{{.Stale}}", "m")
5329 tg.grepStdout("false", "reported m as stale after reinstall")
5330 tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5333 func TestIssue22596(t *testing.T) {
5335 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5336 t.Skip("GODEBUG gocacheverify")
5342 tg.setenv("GOCACHE", tg.path("cache"))
5343 tg.tempFile("gopath1/src/p/p.go", "package p; func F(){}\n")
5344 tg.tempFile("gopath2/src/p/p.go", "package p; func F(){}\n")
5346 tg.setenv("GOPATH", tg.path("gopath1"))
5347 tg.run("list", "-f={{.Target}}", "p")
5348 target1 := strings.TrimSpace(tg.getStdout())
5349 tg.run("install", "p")
5350 tg.wantNotStale("p", "", "p stale after install")
5352 tg.setenv("GOPATH", tg.path("gopath2"))
5353 tg.run("list", "-f={{.Target}}", "p")
5354 target2 := strings.TrimSpace(tg.getStdout())
5355 tg.must(os.MkdirAll(filepath.Dir(target2), 0777))
5356 tg.must(copyFile(target1, target2, 0666))
5357 tg.wantStale("p", "build ID mismatch", "p not stale after copy from gopath1")
5358 tg.run("install", "p")
5359 tg.wantNotStale("p", "", "p stale after install2")
5362 func TestTestCache(t *testing.T) {
5365 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5366 t.Skip("GODEBUG gocacheverify")
5372 tg.setenv("GOPATH", tg.tempdir)
5373 tg.setenv("GOCACHE", tg.path("cache"))
5375 if runtime.Compiler != "gccgo" {
5376 // timeout here should not affect result being cached
5377 // or being retrieved later.
5378 tg.run("test", "-x", "-timeout=10s", "errors")
5379 tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler")
5380 tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
5381 tg.grepStderr(`errors\.test`, "did not run test")
5383 tg.run("test", "-x", "errors")
5384 tg.grepStdout(`ok \terrors\t\(cached\)`, "did not report cached result")
5385 tg.grepStderrNot(`[\\/]compile|gccgo`, "incorrectly ran compiler")
5386 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly ran linker")
5387 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5388 tg.grepStderrNot("DO NOT USE", "poisoned action status leaked")
5390 // Even very low timeouts do not disqualify cached entries.
5391 tg.run("test", "-timeout=1ns", "-x", "errors")
5392 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5394 tg.run("clean", "-testcache")
5395 tg.run("test", "-x", "errors")
5396 tg.grepStderr(`errors\.test`, "did not run test")
5399 // The -p=1 in the commands below just makes the -x output easier to read.
5401 t.Log("\n\nINITIAL\n\n")
5403 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5404 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\nvar X = 1\n")
5405 tg.tempFile("src/t/t1/t1_test.go", "package t\nimport \"testing\"\nfunc Test1(*testing.T) {}\n")
5406 tg.tempFile("src/t/t2/t2_test.go", "package t\nimport _ \"p1\"\nimport \"testing\"\nfunc Test2(*testing.T) {}\n")
5407 tg.tempFile("src/t/t3/t3_test.go", "package t\nimport \"p1\"\nimport \"testing\"\nfunc Test3(t *testing.T) {t.Log(p1.X)}\n")
5408 tg.tempFile("src/t/t4/t4_test.go", "package t\nimport \"p2\"\nimport \"testing\"\nfunc Test4(t *testing.T) {t.Log(p2.X)}")
5409 tg.run("test", "-x", "-v", "-short", "t/...")
5411 t.Log("\n\nREPEAT\n\n")
5413 tg.run("test", "-x", "-v", "-short", "t/...")
5414 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5415 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5416 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5417 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5418 tg.grepStderrNot(`[\\/](compile|gccgo) `, "incorrectly ran compiler")
5419 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5420 tg.grepStderrNot(`p[0-9]\.test`, "incorrectly ran test")
5422 t.Log("\n\nCOMMENT\n\n")
5424 // Changing the program text without affecting the compiled package
5425 // should result in the package being rebuilt but nothing more.
5426 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 01\n")
5427 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5428 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5429 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5430 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5431 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5432 tg.grepStderrNot(`([\\/](compile|gccgo) ).*t[0-9]_test\.go`, "incorrectly ran compiler")
5433 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5434 tg.grepStderrNot(`t[0-9]\.test.*test\.short`, "incorrectly ran test")
5436 t.Log("\n\nCHANGE\n\n")
5438 // Changing the actual package should have limited effects.
5439 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 02\n")
5440 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5442 // p2 should have been rebuilt.
5443 tg.grepStderr(`([\\/]compile|gccgo).*p2.go`, "did not recompile p2")
5445 // t1 does not import anything, should not have been rebuilt.
5446 tg.grepStderrNot(`([\\/]compile|gccgo).*t1_test.go`, "incorrectly recompiled t1")
5447 tg.grepStderrNot(`([\\/]link|gccgo).*t1_test`, "incorrectly relinked t1_test")
5448 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t/t1")
5450 // t2 imports p1 and must be rebuilt and relinked,
5451 // but the change should not have any effect on the test binary,
5452 // so the test should not have been rerun.
5453 tg.grepStderr(`([\\/]compile|gccgo).*t2_test.go`, "did not recompile t2")
5454 tg.grepStderr(`([\\/]link|gccgo).*t2\.test`, "did not relink t2_test")
5455 // This check does not currently work with gccgo, as garbage
5456 // collection of unused variables is not turned on by default.
5457 if runtime.Compiler != "gccgo" {
5458 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t/t2")
5461 // t3 imports p1, and changing X changes t3's test binary.
5462 tg.grepStderr(`([\\/]compile|gccgo).*t3_test.go`, "did not recompile t3")
5463 tg.grepStderr(`([\\/]link|gccgo).*t3\.test`, "did not relink t3_test")
5464 tg.grepStderr(`t3\.test.*-test.short`, "did not rerun t3_test")
5465 tg.grepStdoutNot(`ok \tt/t3\t\(cached\)`, "reported cached t3_test result")
5467 // t4 imports p2, but p2 did not change, so t4 should be relinked, not recompiled,
5469 tg.grepStderrNot(`([\\/]compile|gccgo).*t4_test.go`, "incorrectly recompiled t4")
5470 tg.grepStderr(`([\\/]link|gccgo).*t4\.test`, "did not relink t4_test")
5471 // This check does not currently work with gccgo, as garbage
5472 // collection of unused variables is not turned on by default.
5473 if runtime.Compiler != "gccgo" {
5474 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t/t4")
5478 func TestTestCacheInputs(t *testing.T) {
5481 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5482 t.Skip("GODEBUG gocacheverify")
5488 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5489 tg.setenv("GOCACHE", tg.path("cache"))
5491 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5492 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"))
5493 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("x"), 0644))
5494 old := time.Now().Add(-1 * time.Minute)
5495 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5496 info, err := os.Stat(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5500 t.Logf("file.txt: old=%v, info.ModTime=%v", old, info.ModTime()) // help debug when Chtimes lies about succeeding
5501 tg.setenv("TESTKEY", "x")
5503 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), []byte("#!/bin/sh\nexit 0\n"), 0755))
5504 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old, old))
5506 tg.run("test", "testcache")
5507 tg.run("test", "testcache")
5508 tg.grepStdout(`\(cached\)`, "did not cache")
5510 tg.setenv("TESTKEY", "y")
5511 tg.run("test", "testcache")
5512 tg.grepStdoutNot(`\(cached\)`, "did not notice env var change")
5513 tg.run("test", "testcache")
5514 tg.grepStdout(`\(cached\)`, "did not cache")
5516 tg.run("test", "testcache", "-run=FileSize")
5517 tg.run("test", "testcache", "-run=FileSize")
5518 tg.grepStdout(`\(cached\)`, "did not cache")
5519 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxx"), 0644))
5520 tg.run("test", "testcache", "-run=FileSize")
5521 tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5522 tg.run("test", "testcache", "-run=FileSize")
5523 tg.grepStdout(`\(cached\)`, "did not cache")
5525 tg.run("test", "testcache", "-run=Chdir")
5526 tg.run("test", "testcache", "-run=Chdir")
5527 tg.grepStdout(`\(cached\)`, "did not cache")
5528 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxxxx"), 0644))
5529 tg.run("test", "testcache", "-run=Chdir")
5530 tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5531 tg.run("test", "testcache", "-run=Chdir")
5532 tg.grepStdout(`\(cached\)`, "did not cache")
5534 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5535 tg.run("test", "testcache", "-run=FileContent")
5536 tg.run("test", "testcache", "-run=FileContent")
5537 tg.grepStdout(`\(cached\)`, "did not cache")
5538 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("yyy"), 0644))
5539 old2 := old.Add(10 * time.Second)
5540 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old2, old2))
5541 tg.run("test", "testcache", "-run=FileContent")
5542 tg.grepStdoutNot(`\(cached\)`, "did not notice file content change")
5543 tg.run("test", "testcache", "-run=FileContent")
5544 tg.grepStdout(`\(cached\)`, "did not cache")
5546 tg.run("test", "testcache", "-run=DirList")
5547 tg.run("test", "testcache", "-run=DirList")
5548 tg.grepStdout(`\(cached\)`, "did not cache")
5549 tg.must(os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt")))
5550 tg.run("test", "testcache", "-run=DirList")
5551 tg.grepStdoutNot(`\(cached\)`, "did not notice directory change")
5552 tg.run("test", "testcache", "-run=DirList")
5553 tg.grepStdout(`\(cached\)`, "did not cache")
5555 tg.tempFile("file.txt", "")
5556 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"), []byte(`package testcache
5563 func TestExternalFile(t *testing.T) {
5564 os.Open(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5565 _, err := os.Stat(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5571 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"))
5572 tg.run("test", "testcache", "-run=ExternalFile")
5573 tg.run("test", "testcache", "-run=ExternalFile")
5574 tg.grepStdout(`\(cached\)`, "did not cache")
5575 tg.must(os.Remove(filepath.Join(tg.tempdir, "file.txt")))
5576 tg.run("test", "testcache", "-run=ExternalFile")
5577 tg.grepStdout(`\(cached\)`, "did not cache")
5579 switch runtime.GOOS {
5580 case "nacl", "plan9", "windows":
5583 tg.run("test", "testcache", "-run=Exec")
5584 tg.run("test", "testcache", "-run=Exec")
5585 tg.grepStdout(`\(cached\)`, "did not cache")
5586 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old2, old2))
5587 tg.run("test", "testcache", "-run=Exec")
5588 tg.grepStdoutNot(`\(cached\)`, "did not notice script change")
5589 tg.run("test", "testcache", "-run=Exec")
5590 tg.grepStdout(`\(cached\)`, "did not cache")
5594 func TestTestVet(t *testing.T) {
5600 tg.tempFile("p1_test.go", `
5603 func Test(t *testing.T) {
5604 t.Logf("%d") // oops
5608 tg.runFail("test", tg.path("p1_test.go"))
5609 tg.grepStderr(`Logf format %d`, "did not diagnose bad Logf")
5610 tg.run("test", "-vet=off", tg.path("p1_test.go"))
5611 tg.grepStdout(`^ok`, "did not print test summary")
5613 tg.tempFile("p1.go", `
5617 fmt.Printf("%d") // oops
5620 tg.runFail("test", tg.path("p1.go"))
5621 tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5622 tg.run("test", "-x", "-vet=shift", tg.path("p1.go"))
5623 tg.grepStderr(`[\\/]vet.*-shift`, "did not run vet with -shift")
5624 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5625 tg.run("test", "-vet=off", tg.path("p1.go"))
5626 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5628 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5629 tg.run("test", "vetcycle") // must not fail; #22890
5631 tg.runFail("test", "vetfail/...")
5632 tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5633 tg.grepStdout(`ok\s+vetfail/p2`, "did not run vetfail/p2")
5635 // Use -a so that we need to recompute the vet-specific export data for
5637 tg.run("test", "-a", "vetfail/p2")
5638 tg.grepStderrNot(`invalid.*constraint`, "did diagnose bad build constraint in vetxonly mode")
5641 func TestTestSkipVetAfterFailedBuild(t *testing.T) {
5646 tg.tempFile("x_test.go", `package x
5652 tg.runFail("test", tg.path("x_test.go"))
5653 tg.grepStderrNot(`vet`, "vet should be skipped after the failed build")
5656 func TestTestVetRebuild(t *testing.T) {
5661 // golang.org/issue/23701.
5662 // b_test imports b with augmented method from export_test.go.
5663 // b_test also imports a, which imports b.
5664 // Must not accidentally see un-augmented b propagate through a to b_test.
5665 tg.tempFile("src/a/a.go", `package a
5668 func (*Type) M() b.T {return 0}
5670 tg.tempFile("src/b/b.go", `package b
5672 type I interface {M() T}
5674 tg.tempFile("src/b/export_test.go", `package b
5675 func (*T) Method() *T { return nil }
5677 tg.tempFile("src/b/b_test.go", `package b_test
5683 func TestBroken(t *testing.T) {
5690 tg.setenv("GOPATH", tg.path("."))
5695 func TestInstallDeps(t *testing.T) {
5701 tg.setenv("GOPATH", tg.tempdir)
5703 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5704 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\n")
5705 tg.tempFile("src/main1/main.go", "package main\nimport _ \"p2\"\nfunc main() {}\n")
5707 tg.run("list", "-f={{.Target}}", "p1")
5708 p1 := strings.TrimSpace(tg.getStdout())
5709 tg.run("list", "-f={{.Target}}", "p2")
5710 p2 := strings.TrimSpace(tg.getStdout())
5711 tg.run("list", "-f={{.Target}}", "main1")
5712 main1 := strings.TrimSpace(tg.getStdout())
5714 tg.run("install", "main1")
5720 tg.run("install", "p2")
5724 // don't let install -i overwrite runtime
5725 tg.wantNotStale("runtime", "", "must be non-stale before install -i")
5727 tg.run("install", "-i", "main1")
5729 tg.must(os.Remove(p1))
5731 tg.run("install", "-i", "p2")
5735 func TestFmtLoadErrors(t *testing.T) {
5738 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5739 tg.runFail("fmt", "does-not-exist")
5740 tg.run("fmt", "-n", "exclude")
5743 func TestGoTestMinusN(t *testing.T) {
5744 // Intent here is to verify that 'go test -n' works without crashing.
5745 // This reuses flag_test.go, but really any test would do.
5748 tg.run("test", "testdata/flag_test.go", "-n", "-args", "-v=7")
5751 func TestGoTestJSON(t *testing.T) {
5752 skipIfGccgo(t, "gccgo does not have standard packages")
5759 tg.setenv("GOCACHE", tg.tempdir)
5760 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5762 // It would be nice to test that the output is interlaced
5763 // but it seems to be impossible to do that in a short test
5764 // that isn't also flaky. Just check that we get JSON output.
5765 tg.run("test", "-json", "-short", "-v", "errors", "empty/pkg", "skipper")
5766 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5767 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5769 tg.grepStdout(`"Action":"output","Package":"empty/pkg","Output":".*no test files`, "did not see no test files print")
5770 tg.grepStdout(`"Action":"skip","Package":"empty/pkg"`, "did not see skip")
5772 tg.grepStdout(`"Action":"output","Package":"skipper","Test":"Test","Output":"--- SKIP:`, "did not see SKIP output")
5773 tg.grepStdout(`"Action":"skip","Package":"skipper","Test":"Test"`, "did not see skip result for Test")
5775 tg.run("test", "-json", "-short", "-v", "errors")
5776 tg.grepStdout(`"Action":"output","Package":"errors","Output":".*\(cached\)`, "did not see no cached output")
5778 tg.run("test", "-json", "-bench=NONE", "-short", "-v", "errors")
5779 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5780 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5782 tg.run("test", "-o", tg.path("errors.test.exe"), "-c", "errors")
5783 tg.run("tool", "test2json", "-p", "errors", tg.path("errors.test.exe"), "-test.v", "-test.short")
5784 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5785 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5786 tg.grepStdout(`\{"Action":"pass","Package":"errors"\}`, "did not see final pass")
5789 func TestFailFast(t *testing.T) {
5799 {"TestFailingA", true, 1},
5800 {"TestFailing[AB]", true, 1},
5801 {"TestFailing[AB]", false, 2},
5802 // mix with non-failing tests:
5803 {"TestA|TestFailing[AB]", true, 1},
5804 {"TestA|TestFailing[AB]", false, 2},
5805 // mix with parallel tests:
5806 {"TestFailingB|TestParallelFailingA", true, 2},
5807 {"TestFailingB|TestParallelFailingA", false, 2},
5808 {"TestFailingB|TestParallelFailing[AB]", true, 3},
5809 {"TestFailingB|TestParallelFailing[AB]", false, 3},
5810 // mix with parallel sub-tests
5811 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", true, 3},
5812 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", false, 5},
5813 {"TestParallelFailingSubtestsA", true, 1},
5815 {"TestParallelFailing[AB]", false, 2},
5816 // non-parallel subtests:
5817 {"TestFailingSubtestsA", true, 1},
5818 {"TestFailingSubtestsA", false, 2},
5820 {"TestFatal[CD]", true, 1},
5821 {"TestFatal[CD]", false, 2},
5824 for _, tt := range tests {
5825 t.Run(tt.run, func(t *testing.T) {
5826 tg.runFail("test", "./testdata/src/failfast_test.go", "-run="+tt.run, "-failfast="+strconv.FormatBool(tt.failfast))
5828 nfail := strings.Count(tg.getStdout(), "FAIL - ")
5830 if nfail != tt.nfail {
5831 t.Errorf("go test -run=%s -failfast=%t printed %d FAILs, want %d", tt.run, tt.failfast, nfail, tt.nfail)
5838 func TestImportPath(t *testing.T) {
5844 tg.tempFile("src/a/a.go", `
5858 tg.tempFile("src/a/a_test.go", `
5866 func TestV(t *testing.T) {
5872 tg.tempFile("src/a/p-1.0/p.go", `
5880 tg.setenv("GOPATH", tg.path("."))
5881 tg.run("build", "-o", tg.path("a.exe"), "a")
5885 func TestBadCommandLines(t *testing.T) {
5889 tg.tempFile("src/x/x.go", "package x\n")
5890 tg.setenv("GOPATH", tg.path("."))
5892 tg.run("build", "x")
5894 tg.tempFile("src/x/@y.go", "package x\n")
5895 tg.runFail("build", "x")
5896 tg.grepStderr("invalid input file name \"@y.go\"", "did not reject @y.go")
5897 tg.must(os.Remove(tg.path("src/x/@y.go")))
5899 tg.tempFile("src/x/-y.go", "package x\n")
5900 tg.runFail("build", "x")
5901 tg.grepStderr("invalid input file name \"-y.go\"", "did not reject -y.go")
5902 tg.must(os.Remove(tg.path("src/x/-y.go")))
5904 if runtime.Compiler == "gccgo" {
5905 tg.runFail("build", "-gccgoflags=all=@x", "x")
5907 tg.runFail("build", "-gcflags=all=@x", "x")
5909 tg.grepStderr("invalid command-line argument @x in command", "did not reject @x during exec")
5911 tg.tempFile("src/@x/x.go", "package x\n")
5912 tg.setenv("GOPATH", tg.path("."))
5913 tg.runFail("build", "@x")
5914 tg.grepStderr("invalid input directory name \"@x\"|cannot use path@version syntax", "did not reject @x directory")
5916 tg.tempFile("src/@x/y/y.go", "package y\n")
5917 tg.setenv("GOPATH", tg.path("."))
5918 tg.runFail("build", "@x/y")
5919 tg.grepStderr("invalid import path \"@x/y\"|cannot use path@version syntax", "did not reject @x/y import path")
5921 tg.tempFile("src/-x/x.go", "package x\n")
5922 tg.setenv("GOPATH", tg.path("."))
5923 tg.runFail("build", "--", "-x")
5924 tg.grepStderr("invalid input directory name \"-x\"", "did not reject -x directory")
5926 tg.tempFile("src/-x/y/y.go", "package y\n")
5927 tg.setenv("GOPATH", tg.path("."))
5928 tg.runFail("build", "--", "-x/y")
5929 tg.grepStderr("invalid import path \"-x/y\"", "did not reject -x/y import path")
5932 func TestBadCgoDirectives(t *testing.T) {
5939 tg.tempFile("src/x/x.go", "package x\n")
5940 tg.setenv("GOPATH", tg.path("."))
5942 if runtime.Compiler == "gc" {
5943 tg.tempFile("src/x/x.go", `package x
5945 //go:cgo_ldflag "-fplugin=foo.so"
5949 tg.runFail("build", "x")
5950 tg.grepStderr("//go:cgo_ldflag .* only allowed in cgo-generated code", "did not reject //go:cgo_ldflag directive")
5953 tg.must(os.Remove(tg.path("src/x/x.go")))
5954 tg.runFail("build", "x")
5955 tg.grepStderr("no Go files", "did not report missing source code")
5956 tg.tempFile("src/x/_cgo_yy.go", `package x
5958 //go:cgo_ldflag "-fplugin=foo.so"
5962 tg.runFail("build", "x")
5963 tg.grepStderr("no Go files", "did not report missing source code") // _* files are ignored...
5965 if runtime.Compiler == "gc" {
5966 tg.runFail("build", tg.path("src/x/_cgo_yy.go")) // ... but if forced, the comment is rejected
5967 // Actually, today there is a separate issue that _ files named
5968 // on the command-line are ignored. Once that is fixed,
5969 // we want to see the cgo_ldflag error.
5970 tg.grepStderr("//go:cgo_ldflag only allowed in cgo-generated code|no Go files", "did not reject //go:cgo_ldflag directive")
5973 tg.must(os.Remove(tg.path("src/x/_cgo_yy.go")))
5975 tg.tempFile("src/x/x.go", "package x\n")
5976 tg.tempFile("src/x/y.go", `package x
5977 // #cgo CFLAGS: -fplugin=foo.so
5980 tg.runFail("build", "x")
5981 tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
5983 tg.tempFile("src/x/y.go", `package x
5984 // #cgo CFLAGS: -Ibar -fplugin=foo.so
5987 tg.runFail("build", "x")
5988 tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
5990 tg.tempFile("src/x/y.go", `package x
5991 // #cgo pkg-config: -foo
5994 tg.runFail("build", "x")
5995 tg.grepStderr("invalid pkg-config package name: -foo", "did not reject pkg-config: -foo")
5997 tg.tempFile("src/x/y.go", `package x
5998 // #cgo pkg-config: @foo
6001 tg.runFail("build", "x")
6002 tg.grepStderr("invalid pkg-config package name: @foo", "did not reject pkg-config: -foo")
6004 tg.tempFile("src/x/y.go", `package x
6005 // #cgo CFLAGS: @foo
6008 tg.runFail("build", "x")
6009 tg.grepStderr("invalid flag in #cgo CFLAGS: @foo", "did not reject @foo flag")
6011 tg.tempFile("src/x/y.go", `package x
6015 tg.runFail("build", "x")
6016 tg.grepStderr("invalid flag in #cgo CFLAGS: -D without argument", "did not reject trailing -I flag")
6018 // Note that -I @foo is allowed because we rewrite it into -I /path/to/src/@foo
6019 // before the check is applied. There's no such rewrite for -D.
6021 tg.tempFile("src/x/y.go", `package x
6022 // #cgo CFLAGS: -D @foo
6025 tg.runFail("build", "x")
6026 tg.grepStderr("invalid flag in #cgo CFLAGS: -D @foo", "did not reject -D @foo flag")
6028 tg.tempFile("src/x/y.go", `package x
6029 // #cgo CFLAGS: -D@foo
6032 tg.runFail("build", "x")
6033 tg.grepStderr("invalid flag in #cgo CFLAGS: -D@foo", "did not reject -D@foo flag")
6035 tg.setenv("CGO_CFLAGS", "-D@foo")
6036 tg.tempFile("src/x/y.go", `package x
6039 tg.run("build", "-n", "x")
6040 tg.grepStderr("-D@foo", "did not find -D@foo in commands")
6043 func TestTwoPkgConfigs(t *testing.T) {
6047 if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
6048 t.Skipf("no shell scripts on %s", runtime.GOOS)
6053 tg.tempFile("src/x/a.go", `package x
6054 // #cgo pkg-config: --static a
6057 tg.tempFile("src/x/b.go", `package x
6058 // #cgo pkg-config: --static a
6061 tg.tempFile("pkg-config.sh", `#!/bin/sh
6062 echo $* >>`+tg.path("pkg-config.out"))
6063 tg.must(os.Chmod(tg.path("pkg-config.sh"), 0755))
6064 tg.setenv("GOPATH", tg.path("."))
6065 tg.setenv("PKG_CONFIG", tg.path("pkg-config.sh"))
6066 tg.run("build", "x")
6067 out, err := ioutil.ReadFile(tg.path("pkg-config.out"))
6069 out = bytes.TrimSpace(out)
6070 want := "--cflags --static --static -- a a\n--libs --static --static -- a a"
6071 if !bytes.Equal(out, []byte(want)) {
6072 t.Errorf("got %q want %q", out, want)
6076 func TestCgoCache(t *testing.T) {
6083 tg.tempFile("src/x/a.go", `package main
6090 func main() { fmt.Println(C.val) }
6092 tg.setenv("GOPATH", tg.path("."))
6093 exe := tg.path("x.exe")
6094 tg.run("build", "-o", exe, "x")
6095 tg.setenv("CGO_LDFLAGS", "-lnosuchlibraryexists")
6096 tg.runFail("build", "-o", exe, "x")
6097 tg.grepStderr(`nosuchlibraryexists`, "did not run linker with changed CGO_LDFLAGS")
6101 func TestFilepathUnderCwdFormat(t *testing.T) {
6104 tg.run("test", "-x", "-cover", "log")
6105 tg.grepStderrNot(`\.log\.cover\.go`, "-x output should contain correctly formatted filepath under cwd")
6109 func TestDontReportRemoveOfEmptyDir(t *testing.T) {
6113 tg.tempFile("src/a/a.go", `package a`)
6114 tg.setenv("GOPATH", tg.path("."))
6115 tg.run("install", "-x", "a")
6116 tg.run("install", "-x", "a")
6117 // The second install should have printed only a WORK= line,
6119 if bytes.Count(tg.stdout.Bytes(), []byte{'\n'})+bytes.Count(tg.stderr.Bytes(), []byte{'\n'}) > 1 {
6120 t.Error("unnecessary output when installing installed package")
6125 func TestLinkerTmpDirIsDeleted(t *testing.T) {
6126 skipIfGccgo(t, "gccgo does not use cmd/link")
6128 t.Skip("skipping because cgo not enabled")
6134 tg.tempFile("a.go", `package main; import "C"; func main() {}`)
6135 tg.run("build", "-ldflags", "-v", "-o", os.DevNull, tg.path("a.go"))
6136 // Find line that has "host link:" in linker output.
6137 stderr := tg.getStderr()
6138 var hostLinkLine string
6139 for _, line := range strings.Split(stderr, "\n") {
6140 if !strings.Contains(line, "host link:") {
6146 if hostLinkLine == "" {
6147 t.Fatal(`fail to find with "host link:" string in linker output`)
6149 // Find parameter, like "/tmp/go-link-408556474/go.o" inside of
6150 // "host link:" line, and extract temp directory /tmp/go-link-408556474
6152 tmpdir := hostLinkLine
6153 i := strings.Index(tmpdir, `go.o"`)
6155 t.Fatalf(`fail to find "go.o" in "host link:" line %q`, hostLinkLine)
6157 tmpdir = tmpdir[:i-1]
6158 i = strings.LastIndex(tmpdir, `"`)
6160 t.Fatalf(`fail to find " in "host link:" line %q`, hostLinkLine)
6162 tmpdir = tmpdir[i+1:]
6163 // Verify that temp directory has been removed.
6164 _, err := os.Stat(tmpdir)
6166 t.Fatalf("temp directory %q has not been removed", tmpdir)
6168 if !os.IsNotExist(err) {
6169 t.Fatalf("Stat(%q) returns unexpected error: %v", tmpdir, err)
6173 func testCDAndGOPATHAreDifferent(tg *testgoData, cd, gopath string) {
6174 skipIfGccgo(tg.t, "gccgo does not support -ldflags -X")
6175 tg.setenv("GOPATH", gopath)
6178 exe := tg.path("dir/a.exe")
6182 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked")
6183 out, err := exec.Command(exe).CombinedOutput()
6187 if string(out) != "linkXworked\n" {
6188 tg.t.Errorf(`incorrect output with GOPATH=%q and CD=%q: expected "linkXworked\n", but have %q`, gopath, cd, string(out))
6192 func TestCDAndGOPATHAreDifferent(t *testing.T) {
6196 gopath := filepath.Join(tg.pwd(), "testdata")
6197 cd := filepath.Join(gopath, "src/my.pkg/main")
6199 testCDAndGOPATHAreDifferent(tg, cd, gopath)
6200 if runtime.GOOS == "windows" {
6201 testCDAndGOPATHAreDifferent(tg, cd, strings.ReplaceAll(gopath, `\`, `/`))
6202 testCDAndGOPATHAreDifferent(tg, cd, strings.ToUpper(gopath))
6203 testCDAndGOPATHAreDifferent(tg, cd, strings.ToLower(gopath))
6208 func TestGoTestWithoutTests(t *testing.T) {
6212 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
6213 tg.run("test", "testnorun")
6214 tg.grepStdout(`testnorun\t\[no test files\]`, "do not want test to run")
6218 func TestGoBuildDashODevNull(t *testing.T) {
6222 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
6223 tg.run("build", "-o", os.DevNull, filepath.Join(tg.pwd(), "testdata", "src", "hello", "hello.go"))
6224 tg.mustNotExist("hello")
6225 tg.mustNotExist("hello.exe")
6229 func TestCoverpkgTestOnly(t *testing.T) {
6230 skipIfGccgo(t, "gccgo has no cover tool")
6234 tg.tempFile("src/a/a.go", `package a
6238 tg.tempFile("src/atest/a_test.go", `
6240 import ( "a"; "testing" )
6241 func TestF(t *testing.T) { a.F(2) }
6243 tg.setenv("GOPATH", tg.path("."))
6244 tg.run("test", "-coverpkg=a", "atest")
6245 tg.grepStderrNot("no packages being tested depend on matches", "bad match message")
6246 tg.grepStdout("coverage: 100", "no coverage")