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.
30 "cmd/go/internal/cache"
32 "cmd/go/internal/robustio"
37 canRun = true // whether we can run go or ./testgo
38 canRace = false // whether we can run the race detector
39 canCgo = false // whether we can use cgo
40 canMSan = false // whether we can run the memory sanitizer
42 exeSuffix string // ".exe" on Windows
44 skipExternal = false // skip external tests
47 func tooSlow(t *testing.T) {
49 // In -short mode; skip test, except run it on the {darwin,linux,windows}/amd64 builders.
50 if testenv.Builder() != "" && runtime.GOARCH == "amd64" && (runtime.GOOS == "linux" || runtime.GOOS == "darwin" || runtime.GOOS == "windows") {
53 t.Skip("skipping test in -short mode")
62 switch runtime.GOARCH {
67 switch runtime.GOARCH {
69 // many linux/arm machines are too slow to run
70 // the full set of external tests.
72 case "mips", "mipsle", "mips64", "mips64le":
75 if testenv.Builder() != "" {
76 // On the builders, skip the cmd/go
77 // tests. They're too slow and already
78 // covered by other ports. There's
79 // nothing os/arch specific in the
85 switch runtime.GOARCH {
87 // many freebsd/arm machines are too slow to run
88 // the full set of external tests.
93 switch runtime.GOARCH {
95 // many plan9/arm machines are too slow to run
96 // the full set of external tests.
104 // testGOROOT is the GOROOT to use when running testgo, a cmd/go binary
105 // build from this process's current GOROOT, but run from a different
107 var testGOROOT string
110 var testGOCACHE string
113 var testTmpDir string
116 // testCtx is canceled when the test binary is about to time out.
118 // If https://golang.org/issue/28135 is accepted, uses of this variable in test
119 // functions should be replaced by t.Context().
120 var testCtx = context.Background()
122 // The TestMain function creates a go command for testing purposes and
123 // deletes it after the tests have been run.
124 func TestMain(m *testing.M) {
125 // $GO_GCFLAGS a compiler debug flag known to cmd/dist, make.bash, etc.
126 // It is not a standard go command flag; use os.Getenv, not cfg.Getenv.
127 if os.Getenv("GO_GCFLAGS") != "" {
128 fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
129 fmt.Printf("cmd/go test is not compatible with $GO_GCFLAGS being set\n")
133 os.Unsetenv("GOROOT_FINAL")
137 timeoutFlag := flag.Lookup("test.timeout")
138 if timeoutFlag != nil {
139 // TODO(golang.org/issue/28147): The go command does not pass the
140 // test.timeout flag unless either -timeout or -test.timeout is explicitly
141 // set on the command line.
142 if d := timeoutFlag.Value.(flag.Getter).Get().(time.Duration); d != 0 {
143 aBitShorter := d * 95 / 100
144 var cancel context.CancelFunc
145 testCtx, cancel = context.WithTimeout(testCtx, aBitShorter)
150 if *proxyAddr != "" {
155 // Run with a temporary TMPDIR to check that the tests don't
156 // leave anything behind.
157 topTmpdir, err := ioutil.TempDir("", "cmd-go-test-")
162 defer removeAll(topTmpdir)
164 os.Setenv(tempEnvName(), topTmpdir)
166 dir, err := ioutil.TempDir(topTmpdir, "tmpdir")
172 defer removeAll(testTmpDir)
175 testGOCACHE = cache.DefaultDir()
177 testBin = filepath.Join(testTmpDir, "testbin")
178 if err := os.Mkdir(testBin, 0777); err != nil {
181 testGo = filepath.Join(testBin, "go"+exeSuffix)
182 args := []string{"build", "-tags", "testgo", "-o", testGo}
184 args = append(args, "-race")
186 gotool, err := testenv.GoTool()
188 fmt.Fprintln(os.Stderr, err)
192 goEnv := func(name string) string {
193 out, err := exec.Command(gotool, "env", name).CombinedOutput()
195 fmt.Fprintf(os.Stderr, "go env %s: %v\n%s", name, err, out)
198 return strings.TrimSpace(string(out))
200 testGOROOT = goEnv("GOROOT")
202 // The whole GOROOT/pkg tree was installed using the GOHOSTOS/GOHOSTARCH
203 // toolchain (installed in GOROOT/pkg/tool/GOHOSTOS_GOHOSTARCH).
204 // The testgo.exe we are about to create will be built for GOOS/GOARCH,
205 // which means it will use the GOOS/GOARCH toolchain
206 // (installed in GOROOT/pkg/tool/GOOS_GOARCH).
207 // If these are not the same toolchain, then the entire standard library
208 // will look out of date (the compilers in those two different tool directories
209 // are built for different architectures and have different build IDs),
210 // which will cause many tests to do unnecessary rebuilds and some
211 // tests to attempt to overwrite the installed standard library.
212 // Bail out entirely in this case.
213 hostGOOS := goEnv("GOHOSTOS")
214 hostGOARCH := goEnv("GOHOSTARCH")
215 if hostGOOS != runtime.GOOS || hostGOARCH != runtime.GOARCH {
216 fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
217 fmt.Printf("cmd/go test is not compatible with GOOS/GOARCH != GOHOSTOS/GOHOSTARCH (%s/%s != %s/%s)\n", runtime.GOOS, runtime.GOARCH, hostGOOS, hostGOARCH)
222 buildCmd := exec.Command(gotool, args...)
223 buildCmd.Env = append(os.Environ(), "GOFLAGS=-mod=vendor")
224 out, err := buildCmd.CombinedOutput()
226 fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out)
230 out, err = exec.Command(gotool, "env", "CC").CombinedOutput()
232 fmt.Fprintf(os.Stderr, "could not find testing CC: %v\n%s", err, out)
235 testCC = strings.TrimSpace(string(out))
237 if out, err := exec.Command(testGo, "env", "CGO_ENABLED").Output(); err != nil {
238 fmt.Fprintf(os.Stderr, "running testgo failed: %v\n", err)
241 canCgo, err = strconv.ParseBool(strings.TrimSpace(string(out)))
243 fmt.Fprintf(os.Stderr, "can't parse go env CGO_ENABLED output: %v\n", strings.TrimSpace(string(out)))
247 out, err = exec.Command(gotool, "env", "GOCACHE").CombinedOutput()
249 fmt.Fprintf(os.Stderr, "could not find testing GOCACHE: %v\n%s", err, out)
252 testGOCACHE = strings.TrimSpace(string(out))
254 canMSan = canCgo && sys.MSanSupported(runtime.GOOS, runtime.GOARCH)
255 canRace = canCgo && sys.RaceDetectorSupported(runtime.GOOS, runtime.GOARCH)
256 // The race detector doesn't work on Alpine Linux:
257 // golang.org/issue/14481
258 // gccgo does not support the race detector.
259 if isAlpineLinux() || runtime.Compiler == "gccgo" {
263 // Don't let these environment variables confuse the test.
264 os.Setenv("GOENV", "off")
266 os.Unsetenv("GOPATH")
267 os.Unsetenv("GIT_ALLOW_PROTOCOL")
268 os.Setenv("HOME", "/test-go-home-does-not-exist")
269 // On some systems the default C compiler is ccache.
270 // Setting HOME to a non-existent directory will break
271 // those systems. Disable ccache and use real compiler. Issue 17668.
272 os.Setenv("CCACHE_DISABLE", "1")
273 if cfg.Getenv("GOCACHE") == "" {
274 os.Setenv("GOCACHE", testGOCACHE) // because $HOME is gone
279 removeAll(testTmpDir) // os.Exit won't run defer
283 // There shouldn't be anything left in topTmpdir.
284 dirf, err := os.Open(topTmpdir)
288 names, err := dirf.Readdirnames(0)
293 log.Fatalf("unexpected files left in tmpdir: %v", names)
302 func isAlpineLinux() bool {
303 if runtime.GOOS != "linux" {
306 fi, err := os.Lstat("/etc/alpine-release")
307 return err == nil && fi.Mode().IsRegular()
310 // The length of an mtime tick on this system. This is an estimate of
311 // how long we need to sleep to ensure that the mtime of two files is
313 // We used to try to be clever but that didn't always work (see golang.org/issue/12205).
314 var mtimeTick time.Duration = 1 * time.Second
316 // Manage a single run of the testgo binary.
317 type testgoData struct {
325 stdout, stderr bytes.Buffer
326 execDir string // dir for tg.run
329 // skipIfGccgo skips the test if using gccgo.
330 func skipIfGccgo(t *testing.T, msg string) {
331 if runtime.Compiler == "gccgo" {
332 t.Skipf("skipping test not supported on gccgo: %s", msg)
336 // testgo sets up for a test that runs testgo.
337 func testgo(t *testing.T) *testgoData {
339 testenv.MustHaveGoBuild(t)
342 t.Skipf("skipping external tests on %s/%s", runtime.GOOS, runtime.GOARCH)
345 return &testgoData{t: t}
348 // must gives a fatal error if err is not nil.
349 func (tg *testgoData) must(err error) {
356 // check gives a test non-fatal error if err is not nil.
357 func (tg *testgoData) check(err error) {
364 // parallel runs the test in parallel by calling t.Parallel.
365 func (tg *testgoData) parallel() {
368 tg.t.Fatal("internal testsuite error: call to parallel after run")
371 tg.t.Fatal("internal testsuite error: call to parallel after cd")
373 for _, e := range tg.env {
374 if strings.HasPrefix(e, "GOROOT=") || strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
375 val := e[strings.Index(e, "=")+1:]
376 if strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata") {
377 tg.t.Fatalf("internal testsuite error: call to parallel with testdata in environment (%s)", e)
385 // pwd returns the current directory.
386 func (tg *testgoData) pwd() string {
388 wd, err := os.Getwd()
390 tg.t.Fatalf("could not get working directory: %v", err)
395 // cd changes the current directory to the named directory. Note that
396 // using this means that the test must not be run in parallel with any
398 func (tg *testgoData) cd(dir string) {
401 tg.t.Fatal("internal testsuite error: changing directory when running in parallel")
406 abs, err := filepath.Abs(dir)
407 tg.must(os.Chdir(dir))
409 tg.setenv("PWD", abs)
413 // sleep sleeps for one tick, where a tick is a conservative estimate
414 // of how long it takes for a file modification to get a different
416 func (tg *testgoData) sleep() {
417 time.Sleep(mtimeTick)
420 // setenv sets an environment variable to use when running the test go
422 func (tg *testgoData) setenv(name, val string) {
424 if tg.inParallel && (name == "GOROOT" || name == "GOPATH" || name == "GOBIN") && (strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata")) {
425 tg.t.Fatalf("internal testsuite error: call to setenv with testdata (%s=%s) after parallel", name, val)
428 tg.env = append(tg.env, name+"="+val)
431 // unsetenv removes an environment variable.
432 func (tg *testgoData) unsetenv(name string) {
434 tg.env = append([]string(nil), os.Environ()...)
435 tg.env = append(tg.env, "GO111MODULE=off")
437 for i, v := range tg.env {
438 if strings.HasPrefix(v, name+"=") {
439 tg.env = append(tg.env[:i], tg.env[i+1:]...)
445 func (tg *testgoData) goTool() string {
449 // doRun runs the test go command, recording stdout and stderr and
450 // returning exit status.
451 func (tg *testgoData) doRun(args []string) error {
454 panic("testgoData.doRun called but canRun false")
457 for _, arg := range args {
458 if strings.HasPrefix(arg, "testdata") || strings.HasPrefix(arg, "./testdata") {
459 tg.t.Fatal("internal testsuite error: parallel run using testdata")
465 for _, v := range tg.env {
466 if strings.HasPrefix(v, "GOROOT=") {
473 tg.setenv("GOROOT", testGOROOT)
476 tg.t.Logf("running testgo %v", args)
477 cmd := exec.Command(prog, args...)
481 cmd.Stdout = &tg.stdout
482 cmd.Stderr = &tg.stderr
485 if tg.stdout.Len() > 0 {
486 tg.t.Log("standard output:")
487 tg.t.Log(tg.stdout.String())
489 if tg.stderr.Len() > 0 {
490 tg.t.Log("standard error:")
491 tg.t.Log(tg.stderr.String())
497 // run runs the test go command, and expects it to succeed.
498 func (tg *testgoData) run(args ...string) {
500 if status := tg.doRun(args); status != nil {
502 tg.t.Logf("go %v failed unexpectedly in %s: %v", args, wd, status)
507 // runFail runs the test go command, and expects it to fail.
508 func (tg *testgoData) runFail(args ...string) {
510 if status := tg.doRun(args); status == nil {
511 tg.t.Fatal("testgo succeeded unexpectedly")
513 tg.t.Log("testgo failed as expected:", status)
517 // runGit runs a git command, and expects it to succeed.
518 func (tg *testgoData) runGit(dir string, args ...string) {
520 cmd := exec.Command("git", args...)
523 cmd.Stdout = &tg.stdout
524 cmd.Stderr = &tg.stderr
528 if tg.stdout.Len() > 0 {
529 tg.t.Log("git standard output:")
530 tg.t.Log(tg.stdout.String())
532 if tg.stderr.Len() > 0 {
533 tg.t.Log("git standard error:")
534 tg.t.Log(tg.stderr.String())
537 tg.t.Logf("git %v failed unexpectedly: %v", args, status)
542 // getStdout returns standard output of the testgo run as a string.
543 func (tg *testgoData) getStdout() string {
546 tg.t.Fatal("internal testsuite error: stdout called before run")
548 return tg.stdout.String()
551 // getStderr returns standard error of the testgo run as a string.
552 func (tg *testgoData) getStderr() string {
555 tg.t.Fatal("internal testsuite error: stdout called before run")
557 return tg.stderr.String()
560 // doGrepMatch looks for a regular expression in a buffer, and returns
561 // whether it is found. The regular expression is matched against
562 // each line separately, as with the grep command.
563 func (tg *testgoData) doGrepMatch(match string, b *bytes.Buffer) bool {
566 tg.t.Fatal("internal testsuite error: grep called before run")
568 re := regexp.MustCompile(match)
569 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
577 // doGrep looks for a regular expression in a buffer and fails if it
578 // is not found. The name argument is the name of the output we are
579 // searching, "output" or "error". The msg argument is logged on
581 func (tg *testgoData) doGrep(match string, b *bytes.Buffer, name, msg string) {
583 if !tg.doGrepMatch(match, b) {
585 tg.t.Logf("pattern %v not found in standard %s", match, name)
590 // grepStdout looks for a regular expression in the test run's
591 // standard output and fails, logging msg, if it is not found.
592 func (tg *testgoData) grepStdout(match, msg string) {
594 tg.doGrep(match, &tg.stdout, "output", msg)
597 // grepStderr looks for a regular expression in the test run's
598 // standard error and fails, logging msg, if it is not found.
599 func (tg *testgoData) grepStderr(match, msg string) {
601 tg.doGrep(match, &tg.stderr, "error", msg)
604 // grepBoth looks for a regular expression in the test run's standard
605 // output or stand error and fails, logging msg, if it is not found.
606 func (tg *testgoData) grepBoth(match, msg string) {
608 if !tg.doGrepMatch(match, &tg.stdout) && !tg.doGrepMatch(match, &tg.stderr) {
610 tg.t.Logf("pattern %v not found in standard output or standard error", match)
615 // doGrepNot looks for a regular expression in a buffer and fails if
616 // it is found. The name and msg arguments are as for doGrep.
617 func (tg *testgoData) doGrepNot(match string, b *bytes.Buffer, name, msg string) {
619 if tg.doGrepMatch(match, b) {
621 tg.t.Logf("pattern %v found unexpectedly in standard %s", match, name)
626 // grepStdoutNot looks for a regular expression in the test run's
627 // standard output and fails, logging msg, if it is found.
628 func (tg *testgoData) grepStdoutNot(match, msg string) {
630 tg.doGrepNot(match, &tg.stdout, "output", msg)
633 // grepStderrNot looks for a regular expression in the test run's
634 // standard error and fails, logging msg, if it is found.
635 func (tg *testgoData) grepStderrNot(match, msg string) {
637 tg.doGrepNot(match, &tg.stderr, "error", msg)
640 // grepBothNot looks for a regular expression in the test run's
641 // standard output or stand error and fails, logging msg, if it is
643 func (tg *testgoData) grepBothNot(match, msg string) {
645 if tg.doGrepMatch(match, &tg.stdout) || tg.doGrepMatch(match, &tg.stderr) {
647 tg.t.Fatalf("pattern %v found unexpectedly in standard output or standard error", match)
651 // doGrepCount counts the number of times a regexp is seen in a buffer.
652 func (tg *testgoData) doGrepCount(match string, b *bytes.Buffer) int {
655 tg.t.Fatal("internal testsuite error: doGrepCount called before run")
657 re := regexp.MustCompile(match)
659 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
667 // grepCountBoth returns the number of times a regexp is seen in both
668 // standard output and standard error.
669 func (tg *testgoData) grepCountBoth(match string) int {
671 return tg.doGrepCount(match, &tg.stdout) + tg.doGrepCount(match, &tg.stderr)
674 // creatingTemp records that the test plans to create a temporary file
675 // or directory. If the file or directory exists already, it will be
676 // removed. When the test completes, the file or directory will be
677 // removed if it exists.
678 func (tg *testgoData) creatingTemp(path string) {
680 if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) {
681 tg.t.Fatalf("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path)
683 // If we have changed the working directory, make sure we have
684 // an absolute path, because we are going to change directory
685 // back before we remove the temporary.
686 if tg.wd != "" && !filepath.IsAbs(path) {
687 path = filepath.Join(tg.pwd(), path)
689 tg.must(robustio.RemoveAll(path))
690 tg.temps = append(tg.temps, path)
693 // makeTempdir makes a temporary directory for a run of testgo. If
694 // the temporary directory was already created, this does nothing.
695 func (tg *testgoData) makeTempdir() {
697 if tg.tempdir == "" {
699 tg.tempdir, err = ioutil.TempDir("", "gotest")
704 // tempFile adds a temporary file for a run of testgo.
705 func (tg *testgoData) tempFile(path, contents string) {
708 tg.must(os.MkdirAll(filepath.Join(tg.tempdir, filepath.Dir(path)), 0755))
709 bytes := []byte(contents)
710 if strings.HasSuffix(path, ".go") {
711 formatted, err := format.Source(bytes)
716 tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644))
719 // tempDir adds a temporary directory for a run of testgo.
720 func (tg *testgoData) tempDir(path string) {
723 if err := os.MkdirAll(filepath.Join(tg.tempdir, path), 0755); err != nil && !os.IsExist(err) {
728 // path returns the absolute pathname to file with the temporary
730 func (tg *testgoData) path(name string) string {
732 if tg.tempdir == "" {
733 tg.t.Fatalf("internal testsuite error: path(%q) with no tempdir", name)
738 return filepath.Join(tg.tempdir, name)
741 // mustExist fails if path does not exist.
742 func (tg *testgoData) mustExist(path string) {
744 if _, err := os.Stat(path); err != nil {
745 if os.IsNotExist(err) {
746 tg.t.Fatalf("%s does not exist but should", path)
748 tg.t.Fatalf("%s stat failed: %v", path, err)
752 // mustNotExist fails if path exists.
753 func (tg *testgoData) mustNotExist(path string) {
755 if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
756 tg.t.Fatalf("%s exists but should not (%v)", path, err)
760 // mustHaveContent succeeds if filePath is a path to a file,
761 // and that file is readable and not empty.
762 func (tg *testgoData) mustHaveContent(filePath string) {
763 tg.mustExist(filePath)
764 f, err := os.Stat(filePath)
769 tg.t.Fatalf("expected %s to have data, but is empty", filePath)
773 // wantExecutable fails with msg if path is not executable.
774 func (tg *testgoData) wantExecutable(path, msg string) {
776 if st, err := os.Stat(path); err != nil {
777 if !os.IsNotExist(err) {
782 if runtime.GOOS != "windows" && st.Mode()&0111 == 0 {
783 tg.t.Fatalf("binary %s exists but is not executable", path)
788 // wantArchive fails if path is not an archive.
789 func (tg *testgoData) wantArchive(path string) {
791 f, err := os.Open(path)
795 buf := make([]byte, 100)
798 if !bytes.HasPrefix(buf, []byte("!<arch>\n")) {
799 tg.t.Fatalf("file %s exists but is not an archive", path)
803 // isStale reports whether pkg is stale, and why
804 func (tg *testgoData) isStale(pkg string) (bool, string) {
806 tg.run("list", "-f", "{{.Stale}}:{{.StaleReason}}", pkg)
807 v := strings.TrimSpace(tg.getStdout())
808 f := strings.SplitN(v, ":", 2)
817 tg.t.Fatalf("unexpected output checking staleness of package %v: %v", pkg, v)
821 // wantStale fails with msg if pkg is not stale.
822 func (tg *testgoData) wantStale(pkg, reason, msg string) {
824 stale, why := tg.isStale(pkg)
828 // We always accept the reason as being "not installed but
829 // available in build cache", because when that is the case go
830 // list doesn't try to sort out the underlying reason why the
831 // package is not installed.
832 if reason == "" && why != "" || !strings.Contains(why, reason) && !strings.Contains(why, "not installed but available in build cache") {
833 tg.t.Errorf("wrong reason for Stale=true: %q, want %q", why, reason)
837 // wantNotStale fails with msg if pkg is stale.
838 func (tg *testgoData) wantNotStale(pkg, reason, msg string) {
840 stale, why := tg.isStale(pkg)
844 if reason == "" && why != "" || !strings.Contains(why, reason) {
845 tg.t.Errorf("wrong reason for Stale=false: %q, want %q", why, reason)
849 // If -testwork is specified, the test prints the name of the temp directory
850 // and does not remove it when done, so that a programmer can
851 // poke at the test file tree afterward.
852 var testWork = flag.Bool("testwork", false, "")
854 // cleanup cleans up a test that runs testgo.
855 func (tg *testgoData) cleanup() {
859 tg.t.Logf("ended in %s", wd)
861 if err := os.Chdir(tg.wd); err != nil {
862 // We are unlikely to be able to continue.
863 fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err)
868 tg.t.Logf("TESTWORK=%s\n", tg.path("."))
871 for _, path := range tg.temps {
872 tg.check(removeAll(path))
874 if tg.tempdir != "" {
875 tg.check(removeAll(tg.tempdir))
879 func removeAll(dir string) error {
880 // module cache has 0444 directories;
881 // make them writable in order to remove content.
882 filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
884 return nil // ignore errors walking in file system
891 return robustio.RemoveAll(dir)
894 // failSSH puts an ssh executable in the PATH that always fails.
895 // This is to stub out uses of ssh by go get.
896 func (tg *testgoData) failSSH() {
898 wd, err := os.Getwd()
902 fail := filepath.Join(wd, "testdata/failssh")
903 tg.setenv("PATH", fmt.Sprintf("%v%c%v", fail, filepath.ListSeparator, os.Getenv("PATH")))
906 func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) {
908 t.Skip("skipping lengthy test in short mode")
914 // Copy the runtime packages into a temporary GOROOT
915 // so that we can change files.
916 for _, copydir := range []string{
918 "src/internal/bytealg",
922 filepath.Join("pkg", runtime.GOOS+"_"+runtime.GOARCH),
923 filepath.Join("pkg/tool", runtime.GOOS+"_"+runtime.GOARCH),
926 srcdir := filepath.Join(testGOROOT, copydir)
927 tg.tempDir(filepath.Join("goroot", copydir))
928 err := filepath.Walk(srcdir,
929 func(path string, info os.FileInfo, err error) error {
936 srcrel, err := filepath.Rel(srcdir, path)
940 dest := filepath.Join("goroot", copydir, srcrel)
941 data, err := ioutil.ReadFile(path)
945 tg.tempFile(dest, string(data))
946 if err := os.Chmod(tg.path(dest), info.Mode()); err != nil {
955 tg.setenv("GOROOT", tg.path("goroot"))
957 addVar := func(name string, idx int) (restore func()) {
958 data, err := ioutil.ReadFile(name)
963 data = append(data, fmt.Sprintf("var DummyUnusedVar%d bool\n", idx)...)
964 if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil {
969 if err := ioutil.WriteFile(name, old, 0666); err != nil {
975 // Every main package depends on the "runtime".
976 tg.tempFile("d1/src/p1/p1.go", `package main; func main(){}`)
977 tg.setenv("GOPATH", tg.path("d1"))
978 // Pass -i flag to rebuild everything outdated.
979 tg.run("install", "-i", "p1")
980 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, before any changes")
982 // Changing mtime of runtime/internal/sys/sys.go
983 // should have no effect: only the content matters.
984 // In fact this should be true even outside a release branch.
985 sys := tg.path("goroot/src/runtime/internal/sys/sys.go")
987 restore := addVar(sys, 0)
989 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after updating mtime of runtime/internal/sys/sys.go")
991 // But changing content of any file should have an effect.
992 // Previously zversion.go was the only one that mattered;
993 // now they all matter, so keep using sys.go.
994 restore = addVar(sys, 1)
996 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go")
998 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after changing back to old release")
1000 tg.wantStale("p1", "stale dependency: runtime", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go again")
1001 tg.run("install", "-i", "p1")
1002 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with new release")
1004 // Restore to "old" release.
1006 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after restoring sys.go")
1007 tg.run("install", "-i", "p1")
1008 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release")
1011 func testLocalRun(tg *testgoData, exepath, local, match string) {
1013 out, err := exec.Command(exepath).Output()
1015 tg.t.Fatalf("error running %v: %v", exepath, err)
1017 if !regexp.MustCompile(match).Match(out) {
1018 tg.t.Log(string(out))
1019 tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local)
1023 func testLocalEasy(tg *testgoData, local string) {
1025 exepath := "./easy" + exeSuffix
1026 tg.creatingTemp(exepath)
1027 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go"))
1028 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1031 func testLocalEasySub(tg *testgoData, local string) {
1033 exepath := "./easysub" + exeSuffix
1034 tg.creatingTemp(exepath)
1035 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go"))
1036 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1039 func testLocalHard(tg *testgoData, local string) {
1041 exepath := "./hard" + exeSuffix
1042 tg.creatingTemp(exepath)
1043 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go"))
1044 testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`)
1047 func testLocalInstall(tg *testgoData, local string) {
1049 tg.runFail("install", filepath.Join("testdata", local, "easy.go"))
1052 func TestLocalImportsEasy(t *testing.T) {
1055 testLocalEasy(tg, "local")
1058 func TestLocalImportsEasySub(t *testing.T) {
1061 testLocalEasySub(tg, "local")
1064 func TestLocalImportsHard(t *testing.T) {
1067 testLocalHard(tg, "local")
1070 func TestLocalImportsGoInstallShouldFail(t *testing.T) {
1073 testLocalInstall(tg, "local")
1076 const badDirName = `#$%:, &()*;<=>?\^{}`
1078 func copyBad(tg *testgoData) {
1080 if runtime.GOOS == "windows" {
1081 tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName)
1084 tg.must(filepath.Walk("testdata/local",
1085 func(path string, info os.FileInfo, err error) error {
1093 data, err = ioutil.ReadFile(path)
1097 newpath := strings.Replace(path, "local", badDirName, 1)
1098 tg.tempFile(newpath, string(data))
1104 func TestBadImportsEasy(t *testing.T) {
1107 // TODO: tg.parallel()
1109 testLocalEasy(tg, badDirName)
1112 func TestBadImportsEasySub(t *testing.T) {
1116 testLocalEasySub(tg, badDirName)
1119 func TestBadImportsHard(t *testing.T) {
1123 testLocalHard(tg, badDirName)
1126 func TestBadImportsGoInstallShouldFail(t *testing.T) {
1130 testLocalInstall(tg, badDirName)
1133 func TestInternalPackagesInGOROOTAreRespected(t *testing.T) {
1134 skipIfGccgo(t, "gccgo does not have GOROOT")
1137 tg.runFail("build", "-v", "./testdata/testinternal")
1138 tg.grepBoth(`testinternal(\/|\\)p\.go\:3\:8\: use of internal package net/http/internal not allowed`, "wrong error message for testdata/testinternal")
1141 func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) {
1144 tg.runFail("build", "-v", "./testdata/testinternal2")
1145 tg.grepBoth(`testinternal2(\/|\\)p\.go\:3\:8\: use of internal package .*internal/w not allowed`, "wrote error message for testdata/testinternal2")
1148 func TestRunInternal(t *testing.T) {
1151 dir := filepath.Join(tg.pwd(), "testdata")
1152 tg.setenv("GOPATH", dir)
1153 tg.run("run", filepath.Join(dir, "src/run/good.go"))
1154 tg.runFail("run", filepath.Join(dir, "src/run/bad.go"))
1155 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")
1158 func TestRunPkg(t *testing.T) {
1161 dir := filepath.Join(tg.pwd(), "testdata")
1162 tg.setenv("GOPATH", dir)
1163 tg.run("run", "hello")
1164 tg.grepStderr("hello, world", "did not find hello, world")
1165 tg.cd(filepath.Join(dir, "src/hello"))
1167 tg.grepStderr("hello, world", "did not find hello, world")
1170 func testMove(t *testing.T, vcs, url, base, config string) {
1171 testenv.MustHaveExternalNetwork(t)
1177 tg.must(os.Mkdir(tg.path(".hg"), 0700))
1178 tg.must(ioutil.WriteFile(filepath.Join(tg.path(".hg"), "hgrc"), nil, 0600))
1179 tg.setenv("GOPATH", tg.path("."))
1180 tg.run("get", "-d", url)
1181 tg.run("get", "-d", "-u", url)
1184 // SVN doesn't believe in text files so we can't just edit the config.
1185 // Check out a different repo into the wrong place.
1186 tg.must(robustio.RemoveAll(tg.path("src/code.google.com/p/rsc-svn")))
1187 tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk")
1188 tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn")))
1190 path := tg.path(filepath.Join("src", config))
1191 data, err := ioutil.ReadFile(path)
1193 data = bytes.ReplaceAll(data, []byte(base), []byte(base+"XXX"))
1194 tg.must(ioutil.WriteFile(path, data, 0644))
1197 // git will ask for a username and password when we
1198 // run go get -d -f -u. An empty username and
1199 // password will work. Prevent asking by setting
1201 tg.creatingTemp("sink" + exeSuffix)
1202 tg.tempFile("src/sink/sink.go", `package main; func main() {}`)
1203 tg.run("build", "-o", "sink"+exeSuffix, "sink")
1204 tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix))
1206 tg.runFail("get", "-d", "-u", url)
1207 tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason")
1208 tg.runFail("get", "-d", "-f", "-u", url)
1209 tg.grepStderr("validating server certificate|[nN]ot [fF]ound", "go get -d -f -u "+url+" failed for wrong reason")
1212 func TestInternalPackageErrorsAreHandled(t *testing.T) {
1215 tg.run("list", "./testdata/testinternal3")
1218 func TestInternalCache(t *testing.T) {
1221 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4"))
1222 tg.runFail("build", "p")
1223 tg.grepStderr("internal", "did not fail to build p")
1226 func TestMoveGit(t *testing.T) {
1227 testenv.MustHaveExecPath(t, "git")
1228 testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config")
1231 func TestMoveHG(t *testing.T) {
1232 testenv.MustHaveExecPath(t, "hg")
1233 testMove(t, "hg", "vcs-test.golang.org/go/custom-hg-hello", "custom-hg-hello", "vcs-test.golang.org/go/custom-hg-hello/.hg/hgrc")
1236 // TODO(rsc): Set up a test case on SourceForge (?) for svn.
1237 // func testMoveSVN(t *testing.T) {
1238 // testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-")
1241 func TestImportCommandMatch(t *testing.T) {
1244 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1245 tg.run("build", "./testdata/importcom/works.go")
1248 func TestImportCommentMismatch(t *testing.T) {
1251 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1252 tg.runFail("build", "./testdata/importcom/wrongplace.go")
1253 tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import")
1256 func TestImportCommentSyntaxError(t *testing.T) {
1259 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1260 tg.runFail("build", "./testdata/importcom/bad.go")
1261 tg.grepStderr("cannot parse import comment", "go build did not mention syntax error")
1264 func TestImportCommentConflict(t *testing.T) {
1267 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1268 tg.runFail("build", "./testdata/importcom/conflict.go")
1269 tg.grepStderr("found import comments", "go build did not mention comment conflict")
1272 func TestImportCycle(t *testing.T) {
1276 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcycle"))
1277 tg.runFail("build", "selfimport")
1279 count := tg.grepCountBoth("import cycle not allowed")
1281 t.Fatal("go build did not mention cyclical import")
1284 t.Fatal("go build mentioned import cycle more than once")
1287 // Don't hang forever.
1288 tg.run("list", "-e", "-json", "selfimport")
1291 // cmd/go: custom import path checking should not apply to Go packages without import comment.
1292 func TestIssue10952(t *testing.T) {
1293 testenv.MustHaveExternalNetwork(t)
1294 testenv.MustHaveExecPath(t, "git")
1300 tg.setenv("GOPATH", tg.path("."))
1301 const importPath = "github.com/zombiezen/go-get-issue-10952"
1302 tg.run("get", "-d", "-u", importPath)
1303 repoDir := tg.path("src/" + importPath)
1304 tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git")
1305 tg.run("get", "-d", "-u", importPath)
1308 func TestIssue16471(t *testing.T) {
1309 testenv.MustHaveExternalNetwork(t)
1310 testenv.MustHaveExecPath(t, "git")
1316 tg.setenv("GOPATH", tg.path("."))
1317 tg.must(os.MkdirAll(tg.path("src/rsc.io/go-get-issue-10952"), 0755))
1318 tg.runGit(tg.path("src/rsc.io"), "clone", "https://github.com/zombiezen/go-get-issue-10952")
1319 tg.runFail("get", "-u", "rsc.io/go-get-issue-10952")
1320 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")
1323 // Test git clone URL that uses SCP-like syntax and custom import path checking.
1324 func TestIssue11457(t *testing.T) {
1325 testenv.MustHaveExternalNetwork(t)
1326 testenv.MustHaveExecPath(t, "git")
1332 tg.setenv("GOPATH", tg.path("."))
1333 const importPath = "rsc.io/go-get-issue-11457"
1334 tg.run("get", "-d", "-u", importPath)
1335 repoDir := tg.path("src/" + importPath)
1336 tg.runGit(repoDir, "remote", "set-url", "origin", "git@github.com:rsc/go-get-issue-11457")
1338 // At this time, custom import path checking compares remotes verbatim (rather than
1339 // just the host and path, skipping scheme and user), so we expect go get -u to fail.
1340 // However, the goal of this test is to verify that gitRemoteRepo correctly parsed
1341 // the SCP-like syntax, and we expect it to appear in the error message.
1342 tg.runFail("get", "-d", "-u", importPath)
1343 want := " is checked out from ssh://git@github.com/rsc/go-get-issue-11457"
1344 if !strings.HasSuffix(strings.TrimSpace(tg.getStderr()), want) {
1345 t.Error("expected clone URL to appear in stderr")
1349 func TestGetGitDefaultBranch(t *testing.T) {
1350 testenv.MustHaveExternalNetwork(t)
1351 testenv.MustHaveExecPath(t, "git")
1357 tg.setenv("GOPATH", tg.path("."))
1359 // This repo has two branches, master and another-branch.
1360 // The another-branch is the default that you get from 'git clone'.
1361 // The go get command variants should not override this.
1362 const importPath = "github.com/rsc/go-get-default-branch"
1364 tg.run("get", "-d", importPath)
1365 repoDir := tg.path("src/" + importPath)
1366 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1367 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1369 tg.run("get", "-d", "-u", importPath)
1370 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1371 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1374 // Security issue. Don't disable. See golang.org/issue/22125.
1375 func TestAccidentalGitCheckout(t *testing.T) {
1376 testenv.MustHaveExternalNetwork(t)
1377 testenv.MustHaveExecPath(t, "git")
1384 tg.setenv("GOPATH", tg.path("."))
1386 tg.runFail("get", "-u", "vcs-test.golang.org/go/test1-svn-git")
1387 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1389 if _, err := os.Stat(tg.path("SrC")); err == nil {
1390 // This case only triggers on a case-insensitive file system.
1391 tg.runFail("get", "-u", "vcs-test.golang.org/go/test2-svn-git/test2main")
1392 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1396 func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) {
1399 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1400 tg.runFail("test", "syntaxerror")
1401 tg.grepStderr("x_test.go:", "did not diagnose error")
1402 tg.grepStdout("FAIL", "go test did not say FAIL")
1405 func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) {
1408 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1409 tg.runFail("list", "...")
1410 tg.grepBoth("badpkg", "go list ... failure does not mention badpkg")
1411 tg.run("list", "m...")
1414 func TestRelativeImportsGoTest(t *testing.T) {
1417 tg.run("test", "./testdata/testimport")
1420 func TestRelativeImportsGoTestDashI(t *testing.T) {
1424 // don't let test -i overwrite runtime
1425 tg.wantNotStale("runtime", "", "must be non-stale before test -i")
1427 tg.run("test", "-i", "./testdata/testimport")
1430 func TestRelativeImportsInCommandLinePackage(t *testing.T) {
1433 // TODO: tg.parallel()
1434 files, err := filepath.Glob("./testdata/testimport/*.go")
1436 tg.run(append([]string{"test"}, files...)...)
1439 func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) {
1442 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1"))
1443 tg.runFail("get", "-u", "foo")
1445 // TODO(iant): We should not have to use strconv.Quote here.
1446 // The code in vcs.go should be changed so that it is not required.
1447 quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo"))
1448 quoted = quoted[1 : len(quoted)-1]
1450 tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo")
1453 func TestInstallFailsWithNoBuildableFiles(t *testing.T) {
1456 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1457 tg.setenv("CGO_ENABLED", "0")
1458 tg.runFail("install", "cgotest")
1459 tg.grepStderr("build constraints exclude all Go files", "go install cgotest did not report 'build constraints exclude all Go files'")
1463 func TestMSanAndRaceRequireCgo(t *testing.T) {
1464 if !canMSan && !canRace {
1465 t.Skip("skipping because both msan and the race detector are not supported")
1470 tg.tempFile("triv.go", `package main; func main() {}`)
1471 tg.setenv("CGO_ENABLED", "0")
1473 tg.runFail("install", "-race", "triv.go")
1474 tg.grepStderr("-race requires cgo", "did not correctly report that -race requires cgo")
1475 tg.grepStderrNot("-msan", "reported that -msan instead of -race requires cgo")
1478 tg.runFail("install", "-msan", "triv.go")
1479 tg.grepStderr("-msan requires cgo", "did not correctly report that -msan requires cgo")
1480 tg.grepStderrNot("-race", "reported that -race instead of -msan requires cgo")
1484 func TestRelativeGOBINFail(t *testing.T) {
1487 tg.tempFile("triv.go", `package main; func main() {}`)
1488 tg.setenv("GOBIN", ".")
1490 tg.runFail("install")
1491 tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path")
1494 // Test that without $GOBIN set, binaries get installed
1495 // into the GOPATH bin directory.
1496 func TestInstallIntoGOPATH(t *testing.T) {
1499 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1500 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1501 tg.run("install", "go-cmd-test")
1502 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1506 func TestBuildOutputToDevNull(t *testing.T) {
1509 fi1, err1 := os.Lstat(os.DevNull)
1510 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1511 tg.run("build", "-o", os.DevNull, "go-cmd-test")
1512 fi2, err2 := os.Lstat(os.DevNull)
1515 t.Errorf("second stat of /dev/null failed: %v", err2)
1516 } else if !os.SameFile(fi1, fi2) {
1517 t.Errorf("/dev/null changed: now %v was %v", fi1, fi2)
1523 func TestTestOutputToDevNull(t *testing.T) {
1526 fi1, err1 := os.Lstat(os.DevNull)
1528 tg.setenv("GOPATH", tg.path("."))
1529 tg.tempFile("src/p/p.go", "package p\n")
1530 tg.tempFile("src/p/p_test.go", "package p\nimport \"testing\"\nfunc TestX(t *testing.T) {}\n")
1531 tg.run("test", "-o", os.DevNull, "-c", "p")
1532 tg.mustNotExist("p.test")
1533 fi2, err2 := os.Lstat(os.DevNull)
1536 t.Errorf("second stat of /dev/null failed: %v", err2)
1537 } else if !os.SameFile(fi1, fi2) {
1538 t.Errorf("/dev/null changed: now %v was %v", fi1, fi2)
1543 func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) {
1548 gobin := filepath.Join(tg.pwd(), "testdata", "bin")
1549 tg.creatingTemp(gobin)
1550 tg.setenv("GOBIN", gobin)
1551 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1552 tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now()))
1554 tg.run("test", "main_test")
1555 tg.run("install", "main_test")
1556 tg.wantNotStale("main_test", "", "after go install, main listed as stale")
1557 tg.run("test", "main_test")
1560 func TestPackageMainTestCompilerFlags(t *testing.T) {
1565 tg.setenv("GOPATH", tg.path("."))
1566 tg.tempFile("src/p1/p1.go", "package main\n")
1567 tg.tempFile("src/p1/p1_test.go", "package main\nimport \"testing\"\nfunc Test(t *testing.T){}\n")
1568 tg.run("test", "-c", "-n", "p1")
1569 tg.grepBothNot(`([\\/]compile|gccgo).* (-p main|-fgo-pkgpath=main).*p1\.go`, "should not have run compile -p main p1.go")
1570 tg.grepStderr(`([\\/]compile|gccgo).* (-p p1|-fgo-pkgpath=p1).*p1\.go`, "should have run compile -p p1 p1.go")
1574 func TestPackageNotStaleWithTrailingSlash(t *testing.T) {
1575 skipIfGccgo(t, "gccgo does not have GOROOT")
1579 // Make sure the packages below are not stale.
1580 tg.wantNotStale("runtime", "", "must be non-stale before test runs")
1581 tg.wantNotStale("os", "", "must be non-stale before test runs")
1582 tg.wantNotStale("io", "", "must be non-stale before test runs")
1584 goroot := runtime.GOROOT()
1585 tg.setenv("GOROOT", goroot+"/")
1587 tg.wantNotStale("runtime", "", "with trailing slash in GOROOT, runtime listed as stale")
1588 tg.wantNotStale("os", "", "with trailing slash in GOROOT, os listed as stale")
1589 tg.wantNotStale("io", "", "with trailing slash in GOROOT, io listed as stale")
1592 // With $GOBIN set, binaries get installed to $GOBIN.
1593 func TestInstallIntoGOBIN(t *testing.T) {
1596 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1597 tg.creatingTemp(gobin)
1598 tg.setenv("GOBIN", gobin)
1599 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1600 tg.run("install", "go-cmd-test")
1601 tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test")
1605 func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) {
1608 pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test")
1609 tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix))
1610 tg.setenv("GOBIN", pkg)
1611 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1614 tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory")
1617 // Without $GOBIN set, installing a program outside $GOPATH should fail
1618 // (there is nowhere to install it).
1619 func TestInstallWithoutDestinationFails(t *testing.T) {
1622 tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go")
1623 tg.grepStderr("no install location for .go files listed on command line", "wrong error")
1626 // With $GOBIN set, should install there.
1627 func TestInstallToGOBINCommandLinePackage(t *testing.T) {
1630 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1631 tg.creatingTemp(gobin)
1632 tg.setenv("GOBIN", gobin)
1633 tg.run("install", "testdata/src/go-cmd-test/helloworld.go")
1634 tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld")
1637 func TestGoGetNonPkg(t *testing.T) {
1638 testenv.MustHaveExternalNetwork(t)
1639 testenv.MustHaveExecPath(t, "git")
1644 tg.setenv("GOPATH", tg.path("."))
1645 tg.setenv("GOBIN", tg.path("gobin"))
1646 tg.runFail("get", "-d", "golang.org/x/tools")
1647 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1648 tg.runFail("get", "-d", "-u", "golang.org/x/tools")
1649 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1650 tg.runFail("get", "-d", "golang.org/x/tools")
1651 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1654 func TestGoGetTestOnlyPkg(t *testing.T) {
1655 testenv.MustHaveExternalNetwork(t)
1656 testenv.MustHaveExecPath(t, "git")
1660 tg.tempDir("gopath")
1661 tg.setenv("GOPATH", tg.path("gopath"))
1662 tg.run("get", "golang.org/x/tour/content...")
1663 tg.run("get", "-t", "golang.org/x/tour/content...")
1666 func TestInstalls(t *testing.T) {
1667 if testing.Short() {
1668 t.Skip("don't install into GOROOT in short mode")
1675 tg.setenv("GOPATH", tg.path("."))
1676 goroot := runtime.GOROOT()
1677 tg.setenv("GOROOT", goroot)
1679 // cmd/fix installs into tool
1680 tg.run("env", "GOOS")
1681 goos := strings.TrimSpace(tg.getStdout())
1682 tg.setenv("GOOS", goos)
1683 tg.run("env", "GOARCH")
1684 goarch := strings.TrimSpace(tg.getStdout())
1685 tg.setenv("GOARCH", goarch)
1686 fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix
1687 tg.must(robustio.RemoveAll(fixbin))
1688 tg.run("install", "cmd/fix")
1689 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool")
1690 tg.must(os.Remove(fixbin))
1691 tg.setenv("GOBIN", tg.path("gobin"))
1692 tg.run("install", "cmd/fix")
1693 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set")
1694 tg.unsetenv("GOBIN")
1696 // gopath program installs into GOBIN
1697 tg.tempFile("src/progname/p.go", `package main; func main() {}`)
1698 tg.setenv("GOBIN", tg.path("gobin"))
1699 tg.run("install", "progname")
1700 tg.unsetenv("GOBIN")
1701 tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname")
1703 // gopath program installs into GOPATH/bin
1704 tg.run("install", "progname")
1705 tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname")
1708 func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) {
1711 tg.setenv("GOPATH", ".")
1712 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1713 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1716 func TestRejectRelativePathsInGOPATH(t *testing.T) {
1719 sep := string(filepath.ListSeparator)
1720 tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".")
1721 tg.runFail("build", "go-cmd-test")
1722 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1725 func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) {
1728 tg.setenv("GOPATH", "testdata")
1729 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1730 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1734 func TestRejectBlankPathsInGOPATH(t *testing.T) {
1737 sep := string(filepath.ListSeparator)
1738 tg.setenv("GOPATH", " "+sep+filepath.Join(tg.pwd(), "testdata"))
1739 tg.runFail("build", "go-cmd-test")
1740 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1744 func TestIgnoreEmptyPathsInGOPATH(t *testing.T) {
1747 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1748 sep := string(filepath.ListSeparator)
1749 tg.setenv("GOPATH", ""+sep+filepath.Join(tg.pwd(), "testdata"))
1750 tg.run("install", "go-cmd-test")
1751 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1755 func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
1760 tg.run("test", "errors", "errors", "errors", "errors", "errors")
1761 if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") {
1762 t.Error("go test errors errors errors errors errors tested the same package multiple times")
1766 func TestGoListHasAConsistentOrder(t *testing.T) {
1771 tg.run("list", "std")
1772 first := tg.getStdout()
1773 tg.run("list", "std")
1774 if first != tg.getStdout() {
1775 t.Error("go list std ordering is inconsistent")
1779 func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
1784 tg.run("list", "std")
1785 tg.grepStdoutNot("cmd/", "go list std shows commands")
1788 func TestGoListCmdOnlyShowsCommands(t *testing.T) {
1789 skipIfGccgo(t, "gccgo does not have GOROOT")
1794 tg.run("list", "cmd")
1795 out := strings.TrimSpace(tg.getStdout())
1796 for _, line := range strings.Split(out, "\n") {
1797 if !strings.Contains(line, "cmd/") {
1798 t.Error("go list cmd shows non-commands")
1804 func TestGoListDedupsPackages(t *testing.T) {
1807 // TODO: tg.parallel()
1808 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1809 tg.run("list", "xtestonly", "./testdata/src/xtestonly/...")
1810 got := strings.TrimSpace(tg.getStdout())
1811 const want = "xtestonly"
1813 t.Errorf("got %q; want %q", got, want)
1817 func TestGoListDeps(t *testing.T) {
1821 tg.tempDir("src/p1/p2/p3/p4")
1822 tg.setenv("GOPATH", tg.path("."))
1823 tg.tempFile("src/p1/p.go", "package p1\nimport _ \"p1/p2\"\n")
1824 tg.tempFile("src/p1/p2/p.go", "package p2\nimport _ \"p1/p2/p3\"\n")
1825 tg.tempFile("src/p1/p2/p3/p.go", "package p3\nimport _ \"p1/p2/p3/p4\"\n")
1826 tg.tempFile("src/p1/p2/p3/p4/p.go", "package p4\n")
1827 tg.run("list", "-f", "{{.Deps}}", "p1")
1828 tg.grepStdout("p1/p2/p3/p4", "Deps(p1) does not mention p4")
1830 tg.run("list", "-deps", "p1")
1831 tg.grepStdout("p1/p2/p3/p4", "-deps p1 does not mention p4")
1833 if runtime.Compiler != "gccgo" {
1834 // Check the list is in dependency order.
1835 tg.run("list", "-deps", "math")
1836 want := "internal/cpu\nunsafe\nmath/bits\nmath\n"
1837 out := tg.stdout.String()
1838 if !strings.Contains(out, "internal/cpu") {
1839 // Some systems don't use internal/cpu.
1840 want = "unsafe\nmath/bits\nmath\n"
1842 if tg.stdout.String() != want {
1843 t.Fatalf("list -deps math: wrong order\nhave %q\nwant %q", tg.stdout.String(), want)
1848 func TestGoListTest(t *testing.T) {
1849 skipIfGccgo(t, "gccgo does not have standard packages")
1854 tg.setenv("GOCACHE", tg.tempdir)
1856 tg.run("list", "-test", "-deps", "sort")
1857 tg.grepStdout(`^sort.test$`, "missing test main")
1858 tg.grepStdout(`^sort$`, "missing real sort")
1859 tg.grepStdout(`^sort \[sort.test\]$`, "missing test copy of sort")
1860 tg.grepStdout(`^testing \[sort.test\]$`, "missing test copy of testing")
1861 tg.grepStdoutNot(`^testing$`, "unexpected real copy of testing")
1863 tg.run("list", "-test", "sort")
1864 tg.grepStdout(`^sort.test$`, "missing test main")
1865 tg.grepStdout(`^sort$`, "missing real sort")
1866 tg.grepStdout(`^sort \[sort.test\]$`, "unexpected test copy of sort")
1867 tg.grepStdoutNot(`^testing \[sort.test\]$`, "unexpected test copy of testing")
1868 tg.grepStdoutNot(`^testing$`, "unexpected real copy of testing")
1870 tg.run("list", "-test", "cmd/dist", "cmd/doc")
1871 tg.grepStdout(`^cmd/dist$`, "missing cmd/dist")
1872 tg.grepStdout(`^cmd/doc$`, "missing cmd/doc")
1873 tg.grepStdout(`^cmd/doc\.test$`, "missing cmd/doc test")
1874 tg.grepStdoutNot(`^cmd/dist\.test$`, "unexpected cmd/dist test")
1875 tg.grepStdoutNot(`^testing`, "unexpected testing")
1877 tg.run("list", "-test", "runtime/cgo")
1878 tg.grepStdout(`^runtime/cgo$`, "missing runtime/cgo")
1880 tg.run("list", "-deps", "-f", "{{if .DepOnly}}{{.ImportPath}}{{end}}", "sort")
1881 tg.grepStdout(`^internal/reflectlite$`, "missing internal/reflectlite")
1882 tg.grepStdoutNot(`^sort`, "unexpected sort")
1885 func TestGoListCompiledCgo(t *testing.T) {
1891 tg.setenv("GOCACHE", tg.tempdir)
1893 tg.run("list", "-f", `{{join .CgoFiles "\n"}}`, "net")
1894 if tg.stdout.String() == "" {
1895 t.Skip("net does not use cgo")
1897 if strings.Contains(tg.stdout.String(), tg.tempdir) {
1898 t.Fatalf(".CgoFiles unexpectedly mentioned cache %s", tg.tempdir)
1900 tg.run("list", "-compiled", "-f", `{{.Dir}}{{"\n"}}{{join .CompiledGoFiles "\n"}}`, "net")
1901 if !strings.Contains(tg.stdout.String(), tg.tempdir) {
1902 t.Fatalf(".CompiledGoFiles with -compiled did not mention cache %s", tg.tempdir)
1905 for _, file := range strings.Split(tg.stdout.String(), "\n") {
1913 if !strings.Contains(file, "/") && !strings.Contains(file, `\`) {
1914 file = filepath.Join(dir, file)
1916 if _, err := os.Stat(file); err != nil {
1917 t.Fatalf("cannot find .CompiledGoFiles result %s: %v", file, err)
1922 func TestGoListExport(t *testing.T) {
1923 skipIfGccgo(t, "gccgo does not have standard packages")
1928 tg.setenv("GOCACHE", tg.tempdir)
1930 tg.run("list", "-f", "{{.Export}}", "strings")
1931 if tg.stdout.String() != "" {
1932 t.Fatalf(".Export without -export unexpectedly set")
1934 tg.run("list", "-export", "-f", "{{.Export}}", "strings")
1935 file := strings.TrimSpace(tg.stdout.String())
1937 t.Fatalf(".Export with -export was empty")
1939 if _, err := os.Stat(file); err != nil {
1940 t.Fatalf("cannot find .Export result %s: %v", file, err)
1944 // Issue 4096. Validate the output of unsuccessful go install foo/quxx.
1945 func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) {
1949 tg.runFail("install", "foo/quxx")
1950 if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 {
1951 t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`)
1955 func TestGOROOTSearchFailureReporting(t *testing.T) {
1959 tg.runFail("install", "foo/quxx")
1960 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 {
1961 t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`)
1965 func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) {
1969 sep := string(filepath.ListSeparator)
1970 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1971 tg.runFail("install", "foo/quxx")
1972 if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 {
1973 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`)
1977 // Test (from $GOPATH) annotation is reported for the first GOPATH entry,
1978 func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) {
1982 sep := string(filepath.ListSeparator)
1983 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1984 tg.runFail("install", "foo/quxx")
1985 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 {
1986 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`)
1990 // but not on the second.
1991 func TestMentionGOPATHNotOnSecondEntry(t *testing.T) {
1995 sep := string(filepath.ListSeparator)
1996 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1997 tg.runFail("install", "foo/quxx")
1998 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 {
1999 t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`)
2003 func homeEnvName() string {
2004 switch runtime.GOOS {
2006 return "USERPROFILE"
2014 func tempEnvName() string {
2015 switch runtime.GOOS {
2019 return "TMPDIR" // actually plan 9 doesn't have one at all but this is fine
2025 func TestDefaultGOPATH(t *testing.T) {
2029 tg.tempDir("home/go")
2030 tg.setenv(homeEnvName(), tg.path("home"))
2032 tg.run("env", "GOPATH")
2033 tg.grepStdout(regexp.QuoteMeta(tg.path("home/go")), "want GOPATH=$HOME/go")
2035 tg.setenv("GOROOT", tg.path("home/go"))
2036 tg.run("env", "GOPATH")
2037 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go")
2039 tg.setenv("GOROOT", tg.path("home/go")+"/")
2040 tg.run("env", "GOPATH")
2041 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go/")
2044 func TestDefaultGOPATHGet(t *testing.T) {
2045 testenv.MustHaveExternalNetwork(t)
2046 testenv.MustHaveExecPath(t, "git")
2050 tg.setenv("GOPATH", "")
2052 tg.setenv(homeEnvName(), tg.path("home"))
2054 // warn for creating directory
2055 tg.run("get", "-v", "github.com/golang/example/hello")
2056 tg.grepStderr("created GOPATH="+regexp.QuoteMeta(tg.path("home/go"))+"; see 'go help gopath'", "did not create GOPATH")
2058 // no warning if directory already exists
2059 tg.must(robustio.RemoveAll(tg.path("home/go")))
2060 tg.tempDir("home/go")
2061 tg.run("get", "github.com/golang/example/hello")
2062 tg.grepStderrNot(".", "expected no output on standard error")
2064 // error if $HOME/go is a file
2065 tg.must(robustio.RemoveAll(tg.path("home/go")))
2066 tg.tempFile("home/go", "")
2067 tg.runFail("get", "github.com/golang/example/hello")
2068 tg.grepStderr(`mkdir .*[/\\]go: .*(not a directory|cannot find the path)`, "expected error because $HOME/go is a file")
2071 func TestDefaultGOPATHPrintedSearchList(t *testing.T) {
2074 tg.setenv("GOPATH", "")
2076 tg.setenv(homeEnvName(), tg.path("home"))
2078 tg.runFail("install", "github.com/golang/example/hello")
2079 tg.grepStderr(regexp.QuoteMeta(tg.path("home/go/src/github.com/golang/example/hello"))+`.*from \$GOPATH`, "expected default GOPATH")
2082 // Issue 4186. go get cannot be used to download packages to $GOROOT.
2083 // Test that without GOPATH set, go get should fail.
2084 func TestGoGetIntoGOROOT(t *testing.T) {
2085 testenv.MustHaveExternalNetwork(t)
2092 // Fails because GOROOT=GOPATH
2093 tg.setenv("GOPATH", tg.path("."))
2094 tg.setenv("GOROOT", tg.path("."))
2095 tg.runFail("get", "-d", "github.com/golang/example/hello")
2096 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2097 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2099 // Fails because GOROOT=GOPATH after cleaning.
2100 tg.setenv("GOPATH", tg.path(".")+"/")
2101 tg.setenv("GOROOT", tg.path("."))
2102 tg.runFail("get", "-d", "github.com/golang/example/hello")
2103 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2104 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2106 tg.setenv("GOPATH", tg.path("."))
2107 tg.setenv("GOROOT", tg.path(".")+"/")
2108 tg.runFail("get", "-d", "github.com/golang/example/hello")
2109 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2110 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2112 // Fails because GOROOT=$HOME/go so default GOPATH unset.
2113 tg.tempDir("home/go")
2114 tg.setenv(homeEnvName(), tg.path("home"))
2115 tg.setenv("GOPATH", "")
2116 tg.setenv("GOROOT", tg.path("home/go"))
2117 tg.runFail("get", "-d", "github.com/golang/example/hello")
2118 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2120 tg.setenv(homeEnvName(), tg.path("home")+"/")
2121 tg.setenv("GOPATH", "")
2122 tg.setenv("GOROOT", tg.path("home/go"))
2123 tg.runFail("get", "-d", "github.com/golang/example/hello")
2124 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2126 tg.setenv(homeEnvName(), tg.path("home"))
2127 tg.setenv("GOPATH", "")
2128 tg.setenv("GOROOT", tg.path("home/go")+"/")
2129 tg.runFail("get", "-d", "github.com/golang/example/hello")
2130 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2133 func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) {
2134 skipIfGccgo(t, "gccgo does not support -ldflags -X")
2139 tg.tempFile("main.go", `package main
2144 tg.run("run", "-ldflags", `-X "main.extern=hello world"`, tg.path("main.go"))
2145 tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`)
2148 func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) {
2149 skipIfGccgo(t, "gccgo has no standard packages")
2153 // TODO: tg.parallel()
2156 tg.run("test", "-cpuprofile", "errors.prof", "errors")
2157 tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test")
2160 func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) {
2161 skipIfGccgo(t, "gccgo has no standard packages")
2165 // TODO: tg.parallel()
2168 tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2169 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test")
2172 func TestGoTestMutexprofileLeavesBinaryBehind(t *testing.T) {
2173 skipIfGccgo(t, "gccgo has no standard packages")
2177 // TODO: tg.parallel()
2180 tg.run("test", "-mutexprofile", "errors.prof", "errors")
2181 tg.wantExecutable("errors.test"+exeSuffix, "go test -mutexprofile did not create errors.test")
2184 func TestGoTestMutexprofileDashOControlsBinaryLocation(t *testing.T) {
2185 skipIfGccgo(t, "gccgo has no standard packages")
2189 // TODO: tg.parallel()
2192 tg.run("test", "-mutexprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2193 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -mutexprofile -o myerrors.test did not create myerrors.test")
2196 func TestGoBuildNonMain(t *testing.T) {
2199 // TODO: tg.parallel()
2200 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2201 tg.runFail("build", "-buildmode=exe", "-o", "not_main"+exeSuffix, "not_main")
2202 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")
2203 tg.mustNotExist("not_main" + exeSuffix)
2206 func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) {
2207 skipIfGccgo(t, "gccgo has no standard packages")
2213 tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2214 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test")
2217 func TestGoTestDashOWritesBinary(t *testing.T) {
2218 skipIfGccgo(t, "gccgo has no standard packages")
2224 tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2225 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2228 func TestGoTestDashIDashOWritesBinary(t *testing.T) {
2229 skipIfGccgo(t, "gccgo has no standard packages")
2236 // don't let test -i overwrite runtime
2237 tg.wantNotStale("runtime", "", "must be non-stale before test -i")
2239 tg.run("test", "-v", "-i", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2240 tg.grepBothNot("PASS|FAIL", "test should not have run")
2241 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2245 func TestSymlinksList(t *testing.T) {
2246 testenv.MustHaveSymlink(t)
2250 // TODO: tg.parallel()
2252 tg.must(os.Symlink(tg.path("."), tg.path("src/dir1")))
2253 tg.tempFile("src/dir1/p.go", "package p")
2254 tg.setenv("GOPATH", tg.path("."))
2255 tg.cd(tg.path("src"))
2256 tg.run("list", "-f", "{{.Root}}", "dir1")
2257 if strings.TrimSpace(tg.getStdout()) != tg.path(".") {
2258 t.Error("confused by symlinks")
2263 func TestSymlinksVendor(t *testing.T) {
2264 testenv.MustHaveSymlink(t)
2268 // TODO: tg.parallel()
2269 tg.tempDir("gopath/src/dir1/vendor/v")
2270 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}")
2271 tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v")
2272 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2273 tg.setenv("GOPATH", tg.path("gopath"))
2274 tg.cd(tg.path("symdir1"))
2275 tg.run("list", "-f", "{{.Root}}", ".")
2276 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2277 t.Error("list confused by symlinks")
2280 // All of these should succeed, not die in vendor-handling code.
2281 tg.run("run", "p.go")
2287 func TestSymlinksVendor15201(t *testing.T) {
2288 testenv.MustHaveSymlink(t)
2293 tg.tempDir("gopath/src/x/y/_vendor/src/x")
2294 tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y")))
2295 tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n")
2296 tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor")))
2297 tg.tempFile("gopath/src/x/y/z/z.go", "package z\n")
2299 tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath"))
2300 tg.cd(tg.path("gopath/src"))
2301 tg.run("list", "./...")
2304 func TestSymlinksInternal(t *testing.T) {
2305 testenv.MustHaveSymlink(t)
2309 tg.tempDir("gopath/src/dir1/internal/v")
2310 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}")
2311 tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v")
2312 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2313 tg.setenv("GOPATH", tg.path("gopath"))
2314 tg.cd(tg.path("symdir1"))
2315 tg.run("list", "-f", "{{.Root}}", ".")
2316 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2317 t.Error("list confused by symlinks")
2320 // All of these should succeed, not die in internal-handling code.
2321 tg.run("run", "p.go")
2327 func TestInstallWithTags(t *testing.T) {
2333 tg.tempFile("src/example/a/main.go", `package main
2335 tg.tempFile("src/example/b/main.go", `// +build mytag
2339 tg.setenv("GOPATH", tg.path("."))
2340 tg.run("install", "-tags", "mytag", "example/a", "example/b")
2341 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries")
2342 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries")
2343 tg.must(os.Remove(tg.path("bin/a" + exeSuffix)))
2344 tg.must(os.Remove(tg.path("bin/b" + exeSuffix)))
2345 tg.run("install", "-tags", "mytag", "example/...")
2346 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries")
2347 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries")
2348 tg.run("list", "-tags", "mytag", "example/b...")
2349 if strings.TrimSpace(tg.getStdout()) != "example/b" {
2350 t.Error("go list example/b did not find example/b")
2355 func TestCaseCollisions(t *testing.T) {
2359 tg.tempDir("src/example/a/pkg")
2360 tg.tempDir("src/example/a/Pkg")
2361 tg.tempDir("src/example/b")
2362 tg.setenv("GOPATH", tg.path("."))
2363 tg.tempFile("src/example/a/a.go", `package p
2368 tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`)
2369 tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`)
2370 tg.run("list", "-json", "example/a")
2371 tg.grepStdout("case-insensitive import collision", "go list -json example/a did not report import collision")
2372 tg.runFail("build", "example/a")
2373 tg.grepStderr("case-insensitive import collision", "go build example/a did not report import collision")
2374 tg.tempFile("src/example/b/file.go", `package b`)
2375 tg.tempFile("src/example/b/FILE.go", `package b`)
2376 f, err := os.Open(tg.path("src/example/b"))
2378 names, err := f.Readdirnames(0)
2381 args := []string{"list"}
2382 if len(names) == 2 {
2383 // case-sensitive file system, let directory read find both files
2384 args = append(args, "example/b")
2386 // case-insensitive file system, list files explicitly on command line
2387 args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go"))
2390 tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision")
2392 tg.runFail("list", "example/a/pkg", "example/a/Pkg")
2393 tg.grepStderr("case-insensitive import collision", "go list example/a/pkg example/a/Pkg did not report import collision")
2394 tg.run("list", "-json", "-e", "example/a/pkg", "example/a/Pkg")
2395 tg.grepStdout("case-insensitive import collision", "go list -json -e example/a/pkg example/a/Pkg did not report import collision")
2396 tg.runFail("build", "example/a/pkg", "example/a/Pkg")
2397 tg.grepStderr("case-insensitive import collision", "go build example/a/pkg example/a/Pkg did not report import collision")
2400 // Issue 17451, 17662.
2401 func TestSymlinkWarning(t *testing.T) {
2406 tg.setenv("GOPATH", tg.path("."))
2408 tg.tempDir("src/example/xx")
2410 tg.tempFile("yy/zz/zz.go", "package zz\n")
2411 if err := os.Symlink(tg.path("yy"), tg.path("src/example/xx/yy")); err != nil {
2412 t.Skipf("symlink failed: %v", err)
2414 tg.run("list", "example/xx/z...")
2415 tg.grepStdoutNot(".", "list should not have matched anything")
2416 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2417 tg.grepStderrNot("symlink", "list should not have reported symlink")
2419 tg.run("list", "example/xx/...")
2420 tg.grepStdoutNot(".", "list should not have matched anything")
2421 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2422 tg.grepStderr("ignoring symlink", "list should have reported symlink")
2426 func TestGoGetDashTIssue8181(t *testing.T) {
2427 testenv.MustHaveExternalNetwork(t)
2428 testenv.MustHaveExecPath(t, "git")
2434 tg.setenv("GOPATH", tg.path("."))
2435 tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b")
2436 tg.run("list", "...")
2437 tg.grepStdout("x/build/gerrit", "missing expected x/build/gerrit")
2440 func TestIssue11307(t *testing.T) {
2441 // go get -u was not working except in checkout directory
2442 testenv.MustHaveExternalNetwork(t)
2443 testenv.MustHaveExecPath(t, "git")
2449 tg.setenv("GOPATH", tg.path("."))
2450 tg.run("get", "github.com/rsc/go-get-issue-11307")
2451 tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing
2454 func TestShadowingLogic(t *testing.T) {
2455 skipIfGccgo(t, "gccgo has no standard packages")
2459 sep := string(filepath.ListSeparator)
2460 tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2"))
2462 // The math in root1 is not "math" because the standard math is.
2463 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math")
2464 pwdForwardSlash := strings.ReplaceAll(pwd, string(os.PathSeparator), "/")
2465 if !strings.HasPrefix(pwdForwardSlash, "/") {
2466 pwdForwardSlash = "/" + pwdForwardSlash
2468 // The output will have makeImportValid applies, but we only
2469 // bother to deal with characters we might reasonably see.
2470 for _, r := range " :" {
2471 pwdForwardSlash = strings.ReplaceAll(pwdForwardSlash, string(r), "_")
2473 want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")"
2474 if strings.TrimSpace(tg.getStdout()) != want {
2475 t.Error("shadowed math is not shadowed; looking for", want)
2478 // The foo in root1 is "foo".
2479 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo")
2480 if strings.TrimSpace(tg.getStdout()) != "(foo) ()" {
2481 t.Error("unshadowed foo is shadowed")
2484 // The foo in root2 is not "foo" because the foo in root1 got there first.
2485 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo")
2486 want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")"
2487 if strings.TrimSpace(tg.getStdout()) != want {
2488 t.Error("shadowed foo is not shadowed; looking for", want)
2491 // The error for go install should mention the conflicting directory.
2492 tg.runFail("install", "./testdata/shadow/root2/src/foo")
2493 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")
2494 if strings.TrimSpace(tg.getStderr()) != want {
2495 t.Error("wrong shadowed install error; looking for", want)
2499 // Only succeeds if source order is preserved.
2500 func TestSourceFileNameOrderPreserved(t *testing.T) {
2503 tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go")
2506 // Check that coverage analysis works at all.
2507 // Don't worry about the exact numbers but require not 0.0%.
2508 func checkCoverage(tg *testgoData, data string) {
2510 if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) {
2511 tg.t.Error("some coverage results are 0.0%")
2515 func TestCoverageRuns(t *testing.T) {
2516 skipIfGccgo(t, "gccgo has no cover tool")
2520 tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp")
2521 data := tg.getStdout() + tg.getStderr()
2522 tg.run("test", "-short", "-cover", "strings", "math", "regexp")
2523 data += tg.getStdout() + tg.getStderr()
2524 checkCoverage(tg, data)
2527 func TestCoverageDotImport(t *testing.T) {
2528 skipIfGccgo(t, "gccgo has no cover tool")
2533 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2534 tg.run("test", "-coverpkg=coverdot1,coverdot2", "coverdot2")
2535 data := tg.getStdout() + tg.getStderr()
2536 checkCoverage(tg, data)
2539 // Check that coverage analysis uses set mode.
2540 // Also check that coverage profiles merge correctly.
2541 func TestCoverageUsesSetMode(t *testing.T) {
2542 skipIfGccgo(t, "gccgo has no cover tool")
2546 tg.creatingTemp("testdata/cover.out")
2547 tg.run("test", "-short", "-cover", "encoding/binary", "errors", "-coverprofile=testdata/cover.out")
2548 data := tg.getStdout() + tg.getStderr()
2549 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2552 if !bytes.Contains(out, []byte("mode: set")) {
2553 t.Error("missing mode: set")
2555 if !bytes.Contains(out, []byte("errors.go")) {
2556 t.Error("missing errors.go")
2558 if !bytes.Contains(out, []byte("binary.go")) {
2559 t.Error("missing binary.go")
2561 if bytes.Count(out, []byte("mode: set")) != 1 {
2562 t.Error("too many mode: set")
2565 checkCoverage(tg, data)
2568 func TestCoverageUsesAtomicModeForRace(t *testing.T) {
2571 t.Skip("skipping because race detector not supported")
2573 skipIfGccgo(t, "gccgo has no cover tool")
2577 tg.creatingTemp("testdata/cover.out")
2578 tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
2579 data := tg.getStdout() + tg.getStderr()
2580 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2583 if !bytes.Contains(out, []byte("mode: atomic")) {
2584 t.Error("missing mode: atomic")
2587 checkCoverage(tg, data)
2590 func TestCoverageSyncAtomicImport(t *testing.T) {
2591 skipIfGccgo(t, "gccgo has no cover tool")
2596 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2597 tg.run("test", "-short", "-cover", "-covermode=atomic", "-coverpkg=coverdep/p1", "coverdep")
2600 func TestCoverageDepLoop(t *testing.T) {
2605 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2606 // coverdep2/p1's xtest imports coverdep2/p2 which imports coverdep2/p1.
2607 // Make sure that coverage on coverdep2/p2 recompiles coverdep2/p2.
2608 tg.run("test", "-short", "-cover", "coverdep2/p1")
2609 tg.grepStdout("coverage: 100.0% of statements", "expected 100.0% coverage")
2612 func TestCoverageNoStatements(t *testing.T) {
2616 tg.run("test", "-cover", "./testdata/testcover/pkg4")
2617 tg.grepStdout("[no statements]", "expected [no statements] for pkg4")
2620 func TestCoverageImportMainLoop(t *testing.T) {
2621 skipIfGccgo(t, "gccgo has no cover tool")
2624 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2625 tg.runFail("test", "importmain/test")
2626 tg.grepStderr("not an importable package", "did not detect import main")
2627 tg.runFail("test", "-cover", "importmain/test")
2628 tg.grepStderr("not an importable package", "did not detect import main")
2631 func TestCoveragePattern(t *testing.T) {
2632 skipIfGccgo(t, "gccgo has no cover tool")
2638 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2640 // If coverpkg=sleepy... expands by package loading
2641 // (as opposed to pattern matching on deps)
2642 // then it will try to load sleepybad, which does not compile,
2643 // and the test command will fail.
2644 tg.run("test", "-coverprofile="+tg.path("cover.out"), "-coverpkg=sleepy...", "-run=^$", "sleepy1")
2647 func TestCoverageErrorLine(t *testing.T) {
2648 skipIfGccgo(t, "gccgo has no cover tool")
2654 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2655 tg.setenv("GOTMPDIR", tg.tempdir)
2657 tg.runFail("test", "coverbad")
2658 tg.grepStderr(`coverbad[\\/]p\.go:4`, "did not find coverbad/p.go:4")
2660 tg.grepStderr(`coverbad[\\/]p1\.go:6`, "did not find coverbad/p1.go:6")
2662 tg.grepStderrNot(regexp.QuoteMeta(tg.tempdir), "found temporary directory in error")
2663 stderr := tg.getStderr()
2665 tg.runFail("test", "-cover", "coverbad")
2666 stderr2 := tg.getStderr()
2668 // It's OK that stderr2 drops the character position in the error,
2669 // because of the //line directive (see golang.org/issue/22662).
2670 stderr = strings.ReplaceAll(stderr, "p.go:4:2:", "p.go:4:")
2671 if stderr != stderr2 {
2672 t.Logf("test -cover changed error messages:\nbefore:\n%s\n\nafter:\n%s", stderr, stderr2)
2673 t.Skip("golang.org/issue/22660")
2678 func TestTestBuildFailureOutput(t *testing.T) {
2684 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2686 // Doesn't build, -x output should not claim to run test.
2687 tg.runFail("test", "-x", "coverbad")
2688 tg.grepStderrNot(`[\\/]coverbad\.test( |$)`, "claimed to run test")
2691 func TestCoverageFunc(t *testing.T) {
2692 skipIfGccgo(t, "gccgo has no cover tool")
2698 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2700 tg.run("test", "-outputdir="+tg.tempdir, "-coverprofile=cover.out", "coverasm")
2701 tg.run("tool", "cover", "-func="+tg.path("cover.out"))
2702 tg.grepStdout(`\tg\t*100.0%`, "did not find g 100% covered")
2703 tg.grepStdoutNot(`\tf\t*[0-9]`, "reported coverage for assembly function f")
2707 func TestCoverageDashC(t *testing.T) {
2708 skipIfGccgo(t, "gccgo has no cover tool")
2714 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2715 tg.run("test", "-c", "-o", tg.path("coverdep"), "-coverprofile="+tg.path("no/such/dir/cover.out"), "coverdep")
2716 tg.wantExecutable(tg.path("coverdep"), "go -test -c -coverprofile did not create executable")
2719 func TestPluginNonMain(t *testing.T) {
2720 wd, err := os.Getwd()
2725 pkg := filepath.Join(wd, "testdata", "testdep", "p2")
2730 tg.runFail("build", "-buildmode=plugin", pkg)
2733 func TestTestEmpty(t *testing.T) {
2735 t.Skip("no race detector")
2739 testdata := filepath.Join(wd, "testdata")
2740 for _, dir := range []string{"pkg", "test", "xtest", "pkgtest", "pkgxtest", "pkgtestxtest", "testxtest"} {
2741 t.Run(dir, func(t *testing.T) {
2744 tg.setenv("GOPATH", testdata)
2745 tg.cd(filepath.Join(testdata, "src/empty/"+dir))
2746 tg.run("test", "-cover", "-coverpkg=.", "-race")
2748 if testing.Short() {
2754 func TestNoGoError(t *testing.T) {
2756 testdata := filepath.Join(wd, "testdata")
2757 for _, dir := range []string{"empty/test", "empty/xtest", "empty/testxtest", "exclude", "exclude/ignore", "exclude/empty"} {
2758 t.Run(dir, func(t *testing.T) {
2761 tg.setenv("GOPATH", testdata)
2762 tg.cd(filepath.Join(testdata, "src"))
2763 tg.runFail("build", "./"+dir)
2765 if strings.Contains(dir, "test") {
2766 want = "no non-test Go files in "
2767 } else if dir == "exclude" {
2768 want = "build constraints exclude all Go files in "
2770 want = "no Go files in "
2772 tg.grepStderr(want, "wrong reason for failure")
2777 func TestTestRaceInstall(t *testing.T) {
2779 t.Skip("no race detector")
2785 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2788 pkgdir := tg.path("pkg")
2789 tg.run("install", "-race", "-pkgdir="+pkgdir, "std")
2790 tg.run("test", "-race", "-pkgdir="+pkgdir, "-i", "-v", "empty/pkg")
2791 if tg.getStderr() != "" {
2792 t.Error("go test -i -race: rebuilds cached packages")
2796 func TestBuildDryRunWithCgo(t *testing.T) {
2798 t.Skip("skipping because cgo not enabled")
2803 tg.tempFile("foo.go", `package main
2813 tg.run("build", "-n", tg.path("foo.go"))
2814 tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file")
2817 func TestCoverageWithCgo(t *testing.T) {
2818 skipIfGccgo(t, "gccgo has no cover tool")
2821 t.Skip("skipping because cgo not enabled")
2824 for _, dir := range []string{"cgocover", "cgocover2", "cgocover3", "cgocover4"} {
2825 t.Run(dir, func(t *testing.T) {
2829 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2830 tg.run("test", "-short", "-cover", dir)
2831 data := tg.getStdout() + tg.getStderr()
2832 checkCoverage(tg, data)
2837 func TestCgoAsmError(t *testing.T) {
2839 t.Skip("skipping because cgo not enabled")
2845 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2846 tg.runFail("build", "cgoasm")
2847 tg.grepBoth("package using cgo has Go assembly file", "did not detect Go assembly file")
2850 func TestCgoDependsOnSyscall(t *testing.T) {
2851 if testing.Short() {
2852 t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode")
2855 t.Skip("skipping because cgo not enabled")
2858 t.Skip("skipping because race detector not supported")
2863 files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race"))
2865 for _, file := range files {
2866 tg.check(robustio.RemoveAll(file))
2868 tg.tempFile("src/foo/foo.go", `
2870 //#include <stdio.h>
2872 tg.setenv("GOPATH", tg.path("."))
2873 tg.run("build", "-race", "foo")
2876 func TestCgoShowsFullPathNames(t *testing.T) {
2878 t.Skip("skipping because cgo not enabled")
2884 tg.tempFile("src/x/y/dirname/foo.go", `
2888 tg.setenv("GOPATH", tg.path("."))
2889 tg.runFail("build", "x/y/dirname")
2890 tg.grepBoth("x/y/dirname", "error did not use full path")
2893 func TestCgoHandlesWlORIGIN(t *testing.T) {
2896 t.Skip("skipping because cgo not enabled")
2902 tg.tempFile("src/origin/origin.go", `package origin
2903 // #cgo !darwin LDFLAGS: -Wl,-rpath,$ORIGIN
2906 func f() { C.f() }`)
2907 tg.setenv("GOPATH", tg.path("."))
2908 tg.run("build", "origin")
2911 func TestCgoPkgConfig(t *testing.T) {
2914 t.Skip("skipping because cgo not enabled")
2920 tg.run("env", "PKG_CONFIG")
2921 pkgConfig := strings.TrimSpace(tg.getStdout())
2922 testenv.MustHaveExecPath(t, pkgConfig)
2923 if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil {
2924 t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out)
2927 // OpenBSD's pkg-config is strict about whitespace and only
2928 // supports backslash-escaped whitespace. It does not support
2929 // quotes, which the normal freedesktop.org pkg-config does
2930 // support. See https://man.openbsd.org/pkg-config.1
2931 tg.tempFile("foo.pc", `
2933 Description: The foo library
2935 Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world
2937 tg.tempFile("foo.go", `package main
2940 #cgo pkg-config: foo
2942 return DEFINED_FROM_PKG_CONFIG;
2949 if C.value() != 42 {
2950 println("value() =", C.value(), "wanted 42")
2955 tg.setenv("PKG_CONFIG_PATH", tg.path("."))
2956 tg.run("run", tg.path("foo.go"))
2959 // "go test -c -test.bench=XXX errors" should not hang.
2960 // "go test -c" should also produce reproducible binaries.
2961 // "go test -c" should also appear to write a new binary every time,
2962 // even if it's really just updating the mtime on an existing up-to-date binary.
2963 func TestIssue6480(t *testing.T) {
2964 skipIfGccgo(t, "gccgo has no standard packages")
2968 // TODO: tg.parallel()
2971 tg.run("test", "-c", "-test.bench=XXX", "errors")
2972 tg.run("test", "-c", "-o", "errors2.test", "errors")
2974 data1, err := ioutil.ReadFile("errors.test" + exeSuffix)
2976 data2, err := ioutil.ReadFile("errors2.test") // no exeSuffix because -o above doesn't have it
2978 if !bytes.Equal(data1, data2) {
2979 t.Fatalf("go test -c errors produced different binaries when run twice")
2983 tg.run("test", "-x", "-c", "-test.bench=XXX", "errors")
2984 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
2985 info, err := os.Stat("errors.test" + exeSuffix)
2989 start = truncateLike(start, info.ModTime())
2990 if info.ModTime().Before(start) {
2991 t.Fatalf("mtime of errors.test predates test -c command (%v < %v)", info.ModTime(), start)
2995 tg.run("test", "-x", "-c", "-o", "errors2.test", "errors")
2996 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
2997 info, err = os.Stat("errors2.test")
3001 start = truncateLike(start, info.ModTime())
3002 if info.ModTime().Before(start) {
3003 t.Fatalf("mtime of errors2.test predates test -c command (%v < %v)", info.ModTime(), start)
3007 // truncateLike returns the result of truncating t to the apparent precision of p.
3008 func truncateLike(t, p time.Time) time.Time {
3009 nano := p.UnixNano()
3010 d := 1 * time.Nanosecond
3011 for nano%int64(d) == 0 && d < 1*time.Second {
3014 for nano%int64(d) == 0 && d < 2*time.Second {
3017 return t.Truncate(d)
3020 // cmd/cgo: undefined reference when linking a C-library using gccgo
3021 func TestIssue7573(t *testing.T) {
3023 t.Skip("skipping because cgo not enabled")
3025 testenv.MustHaveExecPath(t, "gccgo")
3030 tg.tempFile("src/cgoref/cgoref.go", `
3032 // #cgo LDFLAGS: -L alibpath -lalib
3036 func main() { C.f() }`)
3037 tg.setenv("GOPATH", tg.path("."))
3038 tg.run("build", "-n", "-compiler", "gccgo", "cgoref")
3039 tg.grepStderr(`gccgo.*\-L [^ ]*alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`)
3042 func TestListTemplateContextFunction(t *testing.T) {
3044 for _, tt := range []struct {
3048 {"GOARCH", runtime.GOARCH},
3049 {"GOOS", runtime.GOOS},
3050 {"GOROOT", filepath.Clean(runtime.GOROOT())},
3051 {"GOPATH", os.Getenv("GOPATH")},
3053 {"UseAllFiles", ""},
3056 {"ReleaseTags", ""},
3057 {"InstallSuffix", ""},
3060 t.Run(tt.v, func(t *testing.T) {
3064 tmpl := "{{context." + tt.v + "}}"
3065 tg.run("list", "-f", tmpl)
3069 if got := strings.TrimSpace(tg.getStdout()); got != tt.want {
3070 t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want)
3076 // cmd/go: "go test" should fail if package does not build
3077 func TestIssue7108(t *testing.T) {
3080 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3081 tg.runFail("test", "notest")
3084 // cmd/go: go test -a foo does not rebuild regexp.
3085 func TestIssue6844(t *testing.T) {
3086 if testing.Short() {
3087 t.Skip("don't rebuild the standard library in short mode")
3092 tg.creatingTemp("deps.test" + exeSuffix)
3093 tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go")
3094 tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp")
3097 func TestBuildDashIInstallsDependencies(t *testing.T) {
3103 tg.tempFile("src/x/y/foo/foo.go", `package foo
3105 tg.tempFile("src/x/y/bar/bar.go", `package bar
3107 func F() { foo.F() }`)
3108 tg.setenv("GOPATH", tg.path("."))
3110 // don't let build -i overwrite runtime
3111 tg.wantNotStale("runtime", "", "must be non-stale before build -i")
3113 checkbar := func(desc string) {
3114 tg.run("build", "-v", "-i", "x/y/bar")
3115 tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo")
3116 tg.run("build", "-v", "-i", "x/y/bar")
3117 tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo")
3121 tg.creatingTemp("bar" + exeSuffix)
3123 tg.tempFile("src/x/y/foo/foo.go", `package foo
3125 tg.tempFile("src/x/y/bar/bar.go", `package main
3127 func main() { foo.F() }`)
3131 func TestGoBuildTestOnly(t *testing.T) {
3135 tg.setenv("GOPATH", tg.path("."))
3136 tg.tempFile("src/testonly/t_test.go", `package testonly`)
3137 tg.tempFile("src/testonly2/t.go", `package testonly2`)
3138 tg.cd(tg.path("src"))
3140 // Named explicitly, test-only packages should be reported as unbuildable/uninstallable,
3141 // even if there is a wildcard also matching.
3142 tg.runFail("build", "testonly", "testonly...")
3143 tg.grepStderr("no non-test Go files in", "go build ./xtestonly produced unexpected error")
3144 tg.runFail("install", "./testonly")
3145 tg.grepStderr("no non-test Go files in", "go install ./testonly produced unexpected error")
3147 // Named through a wildcards, the test-only packages should be silently ignored.
3148 tg.run("build", "testonly...")
3149 tg.run("install", "./testonly...")
3152 func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) {
3155 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3156 tg.runFail("test", "-c", "testcycle/p3")
3157 tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error")
3159 tg.runFail("test", "-c", "testcycle/q1")
3160 tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error")
3163 func TestGoTestFooTestWorks(t *testing.T) {
3166 tg.run("test", "testdata/standalone_test.go")
3169 func TestGoTestTestMainSeesTestingFlags(t *testing.T) {
3172 tg.run("test", "testdata/standalone_testmain_flag_test.go")
3176 func TestGoTestMainWithWrongSignature(t *testing.T) {
3179 tg.runFail("test", "testdata/standalone_main_wrong_test.go")
3180 tg.grepStderr(`wrong signature for TestMain, must be: func TestMain\(m \*testing.M\)`, "detected wrong error message")
3183 func TestGoTestMainAsNormalTest(t *testing.T) {
3186 tg.run("test", "testdata/standalone_main_normal_test.go")
3187 tg.grepBoth(okPattern, "go test did not say ok")
3190 func TestGoTestMainTwice(t *testing.T) {
3191 if testing.Short() {
3192 t.Skip("Skipping in short mode")
3197 tg.setenv("GOCACHE", tg.tempdir)
3198 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3199 tg.run("test", "-v", "multimain")
3200 if strings.Count(tg.getStdout(), "notwithstanding") != 2 {
3201 t.Fatal("tests did not run twice")
3205 func TestGoTestFlagsAfterPackage(t *testing.T) {
3209 tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags.
3210 tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags.
3213 func TestGoTestXtestonlyWorks(t *testing.T) {
3216 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3217 tg.run("clean", "-i", "xtestonly")
3218 tg.run("test", "xtestonly")
3221 func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) {
3224 tg.run("test", "-v", "./testdata/norunexample")
3225 tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built")
3228 func TestGoGenerateHandlesSimpleCommand(t *testing.T) {
3229 if runtime.GOOS == "windows" {
3230 t.Skip("skipping because windows has no echo command")
3235 tg.run("generate", "./testdata/generate/test1.go")
3236 tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output")
3239 func TestGoGenerateHandlesCommandAlias(t *testing.T) {
3240 if runtime.GOOS == "windows" {
3241 t.Skip("skipping because windows has no echo command")
3246 tg.run("generate", "./testdata/generate/test2.go")
3247 tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output")
3250 func TestGoGenerateVariableSubstitution(t *testing.T) {
3251 if runtime.GOOS == "windows" {
3252 t.Skip("skipping because windows has no echo command")
3257 tg.run("generate", "./testdata/generate/test3.go")
3258 tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output")
3261 func TestGoGenerateRunFlag(t *testing.T) {
3262 if runtime.GOOS == "windows" {
3263 t.Skip("skipping because windows has no echo command")
3268 tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go")
3269 tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes")
3270 tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no")
3273 func TestGoGenerateEnv(t *testing.T) {
3274 switch runtime.GOOS {
3275 case "plan9", "windows":
3276 t.Skipf("skipping because %s does not have the env command", runtime.GOOS)
3281 tg.tempFile("env.go", "package main\n\n//go:generate env")
3282 tg.run("generate", tg.path("env.go"))
3283 for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} {
3284 tg.grepStdout("^"+v+"=", "go generate environment missing "+v)
3288 func TestGoGenerateXTestPkgName(t *testing.T) {
3289 if runtime.GOOS == "windows" {
3290 t.Skip("skipping because windows has no echo command")
3296 tg.tempFile("env_test.go", "package main_test\n\n//go:generate echo $GOPACKAGE")
3297 tg.run("generate", tg.path("env_test.go"))
3299 if got := strings.TrimSpace(tg.getStdout()); got != want {
3300 t.Errorf("go generate in XTest file got package name %q; want %q", got, want)
3304 func TestGoGenerateBadImports(t *testing.T) {
3305 if runtime.GOOS == "windows" {
3306 t.Skip("skipping because windows has no echo command")
3309 // This package has an invalid import causing an import cycle,
3310 // but go generate is supposed to still run.
3313 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3314 tg.run("generate", "gencycle")
3315 tg.grepStdout("hello world", "go generate gencycle did not run generator")
3318 func TestGoGetCustomDomainWildcard(t *testing.T) {
3319 testenv.MustHaveExternalNetwork(t)
3320 testenv.MustHaveExecPath(t, "git")
3325 tg.setenv("GOPATH", tg.path("."))
3326 tg.run("get", "-u", "rsc.io/pdf/...")
3327 tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd")
3330 func TestGoGetInternalWildcard(t *testing.T) {
3331 testenv.MustHaveExternalNetwork(t)
3332 testenv.MustHaveExecPath(t, "git")
3337 tg.setenv("GOPATH", tg.path("."))
3338 // used to fail with errors about internal packages
3339 tg.run("get", "github.com/rsc/go-get-issue-11960/...")
3342 func TestGoVetWithExternalTests(t *testing.T) {
3346 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3347 tg.runFail("vet", "vetpkg")
3348 tg.grepBoth("Printf", "go vet vetpkg did not find missing argument for Printf")
3351 func TestGoVetWithTags(t *testing.T) {
3355 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3356 tg.runFail("vet", "-tags", "tagtest", "vetpkg")
3357 tg.grepBoth(`c\.go.*Printf`, "go vet vetpkg did not run scan tagged file")
3360 func TestGoVetWithFlagsOn(t *testing.T) {
3364 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3365 tg.runFail("vet", "-printf", "vetpkg")
3366 tg.grepBoth("Printf", "go vet -printf vetpkg did not find missing argument for Printf")
3369 func TestGoVetWithFlagsOff(t *testing.T) {
3373 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3374 tg.run("vet", "-printf=false", "vetpkg")
3378 func TestGoVetWithOnlyTestFiles(t *testing.T) {
3382 tg.tempFile("src/p/p_test.go", "package p; import \"testing\"; func TestMe(*testing.T) {}")
3383 tg.setenv("GOPATH", tg.path("."))
3388 func TestVetWithOnlyCgoFiles(t *testing.T) {
3390 t.Skip("skipping because cgo not enabled")
3397 tg.tempFile("src/p/p.go", "package p; import \"C\"; func F() {}")
3398 tg.setenv("GOPATH", tg.path("."))
3402 // Issue 9767, 19769.
3403 func TestGoGetDotSlashDownload(t *testing.T) {
3404 testenv.MustHaveExternalNetwork(t)
3405 testenv.MustHaveExecPath(t, "git")
3409 tg.tempDir("src/rsc.io")
3410 tg.setenv("GOPATH", tg.path("."))
3411 tg.cd(tg.path("src/rsc.io"))
3412 tg.run("get", "./pprof_mac_fix")
3415 // Test that you cannot import a main package.
3416 // See golang.org/issue/4210 and golang.org/issue/17475.
3417 func TestImportMain(t *testing.T) {
3424 // Importing package main from that package main's test should work.
3425 tg.tempFile("src/x/main.go", `package main
3428 tg.tempFile("src/x/main_test.go", `package main_test
3432 func TestFoo(t *testing.T) {}
3434 tg.setenv("GOPATH", tg.path("."))
3435 tg.creatingTemp("x" + exeSuffix)
3436 tg.run("build", "x")
3439 // Importing package main from another package should fail.
3440 tg.tempFile("src/p1/p.go", `package p1
3444 tg.runFail("build", "p1")
3445 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3447 // ... even in that package's test.
3448 tg.tempFile("src/p2/p.go", `package p2
3450 tg.tempFile("src/p2/p_test.go", `package p2
3454 func TestFoo(t *testing.T) {}
3456 tg.run("build", "p2")
3457 tg.runFail("test", "p2")
3458 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3460 // ... even if that package's test is an xtest.
3461 tg.tempFile("src/p3/p.go", `package p
3463 tg.tempFile("src/p3/p_test.go", `package p_test
3467 func TestFoo(t *testing.T) {}
3469 tg.run("build", "p3")
3470 tg.runFail("test", "p3")
3471 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3473 // ... even if that package is a package main
3474 tg.tempFile("src/p4/p.go", `package main
3477 tg.tempFile("src/p4/p_test.go", `package main
3481 func TestFoo(t *testing.T) {}
3483 tg.creatingTemp("p4" + exeSuffix)
3484 tg.run("build", "p4")
3485 tg.runFail("test", "p4")
3486 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3488 // ... even if that package is a package main using an xtest.
3489 tg.tempFile("src/p5/p.go", `package main
3492 tg.tempFile("src/p5/p_test.go", `package main_test
3496 func TestFoo(t *testing.T) {}
3498 tg.creatingTemp("p5" + exeSuffix)
3499 tg.run("build", "p5")
3500 tg.runFail("test", "p5")
3501 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3504 // Test that you cannot use a local import in a package
3505 // accessed by a non-local import (found in a GOPATH/GOROOT).
3506 // See golang.org/issue/17475.
3507 func TestImportLocal(t *testing.T) {
3514 tg.tempFile("src/dir/x/x.go", `package x
3517 tg.setenv("GOPATH", tg.path("."))
3518 tg.run("build", "dir/x")
3520 // Ordinary import should work.
3521 tg.tempFile("src/dir/p0/p.go", `package p0
3525 tg.run("build", "dir/p0")
3527 // Relative import should not.
3528 tg.tempFile("src/dir/p1/p.go", `package p1
3532 tg.runFail("build", "dir/p1")
3533 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3535 // ... even in a test.
3536 tg.tempFile("src/dir/p2/p.go", `package p2
3538 tg.tempFile("src/dir/p2/p_test.go", `package p2
3542 func TestFoo(t *testing.T) {}
3544 tg.run("build", "dir/p2")
3545 tg.runFail("test", "dir/p2")
3546 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3548 // ... even in an xtest.
3549 tg.tempFile("src/dir/p2/p_test.go", `package p2_test
3553 func TestFoo(t *testing.T) {}
3555 tg.run("build", "dir/p2")
3556 tg.runFail("test", "dir/p2")
3557 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3559 // Relative import starting with ./ should not work either.
3560 tg.tempFile("src/dir/d.go", `package dir
3564 tg.runFail("build", "dir")
3565 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3567 // ... even in a test.
3568 tg.tempFile("src/dir/d.go", `package dir
3570 tg.tempFile("src/dir/d_test.go", `package dir
3574 func TestFoo(t *testing.T) {}
3576 tg.run("build", "dir")
3577 tg.runFail("test", "dir")
3578 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3580 // ... even in an xtest.
3581 tg.tempFile("src/dir/d_test.go", `package dir_test
3585 func TestFoo(t *testing.T) {}
3587 tg.run("build", "dir")
3588 tg.runFail("test", "dir")
3589 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3591 // Relative import plain ".." should not work.
3592 tg.tempFile("src/dir/x/y/y.go", `package dir
3596 tg.runFail("build", "dir/x/y")
3597 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3599 // ... even in a test.
3600 tg.tempFile("src/dir/x/y/y.go", `package y
3602 tg.tempFile("src/dir/x/y/y_test.go", `package y
3606 func TestFoo(t *testing.T) {}
3608 tg.run("build", "dir/x/y")
3609 tg.runFail("test", "dir/x/y")
3610 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3612 // ... even in an x test.
3613 tg.tempFile("src/dir/x/y/y_test.go", `package y_test
3617 func TestFoo(t *testing.T) {}
3619 tg.run("build", "dir/x/y")
3620 tg.runFail("test", "dir/x/y")
3621 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3623 // Relative import "." should not work.
3624 tg.tempFile("src/dir/x/xx.go", `package x
3628 tg.runFail("build", "dir/x")
3629 tg.grepStderr("cannot import current directory", "did not diagnose import current directory")
3631 // ... even in a test.
3632 tg.tempFile("src/dir/x/xx.go", `package x
3634 tg.tempFile("src/dir/x/xx_test.go", `package x
3638 func TestFoo(t *testing.T) {}
3640 tg.run("build", "dir/x")
3641 tg.runFail("test", "dir/x")
3642 tg.grepStderr("cannot import current directory", "did not diagnose import current directory")
3644 // ... even in an xtest.
3645 tg.tempFile("src/dir/x/xx.go", `package x
3647 tg.tempFile("src/dir/x/xx_test.go", `package x_test
3651 func TestFoo(t *testing.T) {}
3653 tg.run("build", "dir/x")
3654 tg.runFail("test", "dir/x")
3655 tg.grepStderr("cannot import current directory", "did not diagnose import current directory")
3658 func TestGoGetInsecure(t *testing.T) {
3659 test := func(t *testing.T, modules bool) {
3660 testenv.MustHaveExternalNetwork(t)
3661 testenv.MustHaveExecPath(t, "git")
3669 tg.setenv("GOPATH", tg.path("gp"))
3670 tg.tempFile("go.mod", "module m")
3672 tg.setenv("GO111MODULE", "on")
3673 tg.setenv("GOPROXY", "")
3675 tg.setenv("GOPATH", tg.path("."))
3676 tg.setenv("GO111MODULE", "off")
3679 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3681 // Try go get -d of HTTP-only repo (should fail).
3682 tg.runFail("get", "-d", repo)
3684 // Try again with -insecure (should succeed).
3685 tg.run("get", "-d", "-insecure", repo)
3687 // Try updating without -insecure (should fail).
3688 tg.runFail("get", "-d", "-u", "-f", repo)
3691 tg.run("list", "-m", "...")
3692 tg.grepStdout("insecure.go-get-issue", "should find insecure module")
3696 t.Run("gopath", func(t *testing.T) { test(t, false) })
3697 t.Run("modules", func(t *testing.T) { test(t, true) })
3700 func TestGoGetUpdateInsecure(t *testing.T) {
3701 testenv.MustHaveExternalNetwork(t)
3702 testenv.MustHaveExecPath(t, "git")
3707 tg.setenv("GOPATH", tg.path("."))
3709 const repo = "github.com/golang/example"
3711 // Clone the repo via HTTP manually.
3712 cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
3713 if out, err := cmd.CombinedOutput(); err != nil {
3714 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3717 // Update without -insecure should fail.
3718 // Update with -insecure should succeed.
3719 // We need -f to ignore import comments.
3720 const pkg = repo + "/hello"
3721 tg.runFail("get", "-d", "-u", "-f", pkg)
3722 tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
3725 func TestGoGetUpdateUnknownProtocol(t *testing.T) {
3726 testenv.MustHaveExternalNetwork(t)
3727 testenv.MustHaveExecPath(t, "git")
3732 tg.setenv("GOPATH", tg.path("."))
3734 const repo = "github.com/golang/example"
3736 // Clone the repo via HTTPS manually.
3737 repoDir := tg.path("src/" + repo)
3738 cmd := exec.Command("git", "clone", "-q", "https://"+repo, repoDir)
3739 if out, err := cmd.CombinedOutput(); err != nil {
3740 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3743 // Configure the repo to use a protocol unknown to cmd/go
3744 // that still actually works.
3745 cmd = exec.Command("git", "remote", "set-url", "origin", "xyz://"+repo)
3747 if out, err := cmd.CombinedOutput(); err != nil {
3748 t.Fatalf("git remote set-url: %v\n%s", err, out)
3750 cmd = exec.Command("git", "config", "--local", "url.https://github.com/.insteadOf", "xyz://github.com/")
3752 if out, err := cmd.CombinedOutput(); err != nil {
3753 t.Fatalf("git config: %v\n%s", err, out)
3756 // We need -f to ignore import comments.
3757 tg.run("get", "-d", "-u", "-f", repo+"/hello")
3760 func TestGoGetInsecureCustomDomain(t *testing.T) {
3761 testenv.MustHaveExternalNetwork(t)
3762 testenv.MustHaveExecPath(t, "git")
3767 tg.setenv("GOPATH", tg.path("."))
3769 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3770 tg.runFail("get", "-d", repo)
3771 tg.run("get", "-d", "-insecure", repo)
3774 func TestGoRunDirs(t *testing.T) {
3777 tg.cd("testdata/rundir")
3778 tg.runFail("run", "x.go", "sub/sub.go")
3779 tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
3780 tg.runFail("run", "sub/sub.go", "x.go")
3781 tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
3784 func TestGoInstallPkgdir(t *testing.T) {
3785 skipIfGccgo(t, "gccgo has no standard packages")
3793 tg.run("install", "-pkgdir", pkg, "sync")
3794 tg.mustExist(filepath.Join(pkg, "sync.a"))
3795 tg.mustNotExist(filepath.Join(pkg, "sync/atomic.a"))
3796 tg.run("install", "-i", "-pkgdir", pkg, "sync")
3797 tg.mustExist(filepath.Join(pkg, "sync.a"))
3798 tg.mustExist(filepath.Join(pkg, "sync/atomic.a"))
3801 func TestGoTestRaceInstallCgo(t *testing.T) {
3803 t.Skip("skipping because race detector not supported")
3806 // golang.org/issue/10500.
3807 // This used to install a race-enabled cgo.
3810 tg.run("tool", "-n", "cgo")
3811 cgo := strings.TrimSpace(tg.stdout.String())
3812 old, err := os.Stat(cgo)
3814 tg.run("test", "-race", "-i", "runtime/race")
3815 new, err := os.Stat(cgo)
3817 if !new.ModTime().Equal(old.ModTime()) {
3818 t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
3822 func TestGoTestRaceFailures(t *testing.T) {
3826 t.Skip("skipping because race detector not supported")
3832 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3834 tg.run("test", "testrace")
3836 tg.runFail("test", "-race", "testrace")
3837 tg.grepStdout("FAIL: TestRace", "TestRace did not fail")
3838 tg.grepBothNot("PASS", "something passed")
3840 tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".")
3841 tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail")
3842 tg.grepBothNot("PASS", "something passed")
3845 func TestGoTestImportErrorStack(t *testing.T) {
3846 const out = `package testdep/p1 (test)
3848 imports testdep/p3: build constraints exclude all Go files `
3852 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3853 tg.runFail("test", "testdep/p1")
3854 if !strings.Contains(tg.stderr.String(), out) {
3855 t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String())
3859 func TestGoGetUpdate(t *testing.T) {
3860 // golang.org/issue/9224.
3861 // The recursive updating was trying to walk to
3862 // former dependencies, not current ones.
3864 testenv.MustHaveExternalNetwork(t)
3865 testenv.MustHaveExecPath(t, "git")
3870 tg.setenv("GOPATH", tg.path("."))
3873 tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
3874 cmd := exec.Command("git", "reset", "--hard", "HEAD~")
3875 cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
3876 out, err := cmd.CombinedOutput()
3878 t.Fatalf("git: %v\n%s", err, out)
3883 tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3885 // Again with -d -u.
3887 tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3891 func TestGoGetRace(t *testing.T) {
3892 testenv.MustHaveExternalNetwork(t)
3893 testenv.MustHaveExecPath(t, "git")
3895 t.Skip("skipping because race detector not supported")
3901 tg.setenv("GOPATH", tg.path("."))
3902 tg.run("get", "-race", "github.com/rsc/go-get-issue-9224-cmd")
3905 func TestGoGetDomainRoot(t *testing.T) {
3906 // golang.org/issue/9357.
3907 // go get foo.io (not foo.io/subdir) was not working consistently.
3909 testenv.MustHaveExternalNetwork(t)
3910 testenv.MustHaveExecPath(t, "git")
3915 tg.setenv("GOPATH", tg.path("."))
3917 // go-get-issue-9357.appspot.com is running
3918 // the code at github.com/rsc/go-get-issue-9357,
3919 // a trivial Go on App Engine app that serves a
3920 // <meta> tag for the domain root.
3921 tg.run("get", "-d", "go-get-issue-9357.appspot.com")
3922 tg.run("get", "go-get-issue-9357.appspot.com")
3923 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3925 tg.must(robustio.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3926 tg.run("get", "go-get-issue-9357.appspot.com")
3928 tg.must(robustio.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3929 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3932 func TestGoInstallShadowedGOPATH(t *testing.T) {
3933 // golang.org/issue/3652.
3934 // go get foo.io (not foo.io/subdir) was not working consistently.
3936 testenv.MustHaveExternalNetwork(t)
3941 tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
3943 tg.tempDir("gopath1/src/test")
3944 tg.tempDir("gopath2/src/test")
3945 tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
3947 tg.cd(tg.path("gopath2/src/test"))
3948 tg.runFail("install")
3949 tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
3952 func TestGoBuildGOPATHOrder(t *testing.T) {
3953 // golang.org/issue/14176#issuecomment-179895769
3954 // golang.org/issue/14192
3955 // -I arguments to compiler could end up not in GOPATH order,
3956 // leading to unexpected import resolution in the compiler.
3957 // This is still not a complete fix (see golang.org/issue/14271 and next test)
3958 // but it is clearly OK and enough to fix both of the two reported
3959 // instances of the underlying problem. It will have to do for now.
3964 tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2"))
3966 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3967 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3968 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3969 tg.tempFile("p1/src/bar/bar.go", `
3975 tg.run("install", "-x", "bar")
3978 func TestGoBuildGOPATHOrderBroken(t *testing.T) {
3979 // This test is known not to work.
3980 // See golang.org/issue/14271.
3981 t.Skip("golang.org/issue/14271")
3987 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3988 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3989 tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n")
3990 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3991 tg.tempFile("p1/src/bar/bar.go", `
3997 colon := string(filepath.ListSeparator)
3998 tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2"))
3999 tg.run("install", "-x", "bar")
4001 tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1"))
4002 tg.run("install", "-x", "bar")
4005 func TestIssue11709(t *testing.T) {
4008 tg.tempFile("run.go", `
4012 if os.Getenv("TERM") != "" {
4017 tg.run("run", tg.path("run.go"))
4020 func TestIssue12096(t *testing.T) {
4023 tg.tempFile("test_test.go", `
4025 import ("os"; "testing")
4026 func TestEnv(t *testing.T) {
4027 if os.Getenv("TERM") != "" {
4028 t.Fatal("TERM is set")
4032 tg.run("test", tg.path("test_test.go"))
4035 func TestGoBuildOutput(t *testing.T) {
4036 skipIfGccgo(t, "gccgo has no standard packages")
4044 nonExeSuffix := ".exe"
4045 if exeSuffix == ".exe" {
4049 tg.tempFile("x.go", "package main\nfunc main(){}\n")
4050 tg.run("build", "x.go")
4051 tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
4052 tg.must(os.Remove(tg.path("x" + exeSuffix)))
4053 tg.mustNotExist("x" + nonExeSuffix)
4055 tg.run("build", "-o", "myprog", "x.go")
4056 tg.mustNotExist("x")
4057 tg.mustNotExist("x.exe")
4058 tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
4059 tg.mustNotExist("myprog.exe")
4061 tg.tempFile("p.go", "package p\n")
4062 tg.run("build", "p.go")
4063 tg.mustNotExist("p")
4064 tg.mustNotExist("p.a")
4065 tg.mustNotExist("p.o")
4066 tg.mustNotExist("p.exe")
4068 tg.run("build", "-o", "p.a", "p.go")
4069 tg.wantArchive("p.a")
4071 tg.run("build", "cmd/gofmt")
4072 tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
4073 tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
4074 tg.mustNotExist("gofmt" + nonExeSuffix)
4076 tg.run("build", "-o", "mygofmt", "cmd/gofmt")
4077 tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
4078 tg.mustNotExist("mygofmt.exe")
4079 tg.mustNotExist("gofmt")
4080 tg.mustNotExist("gofmt.exe")
4082 tg.run("build", "sync/atomic")
4083 tg.mustNotExist("atomic")
4084 tg.mustNotExist("atomic.exe")
4086 tg.run("build", "-o", "myatomic.a", "sync/atomic")
4087 tg.wantArchive("myatomic.a")
4088 tg.mustNotExist("atomic")
4089 tg.mustNotExist("atomic.a")
4090 tg.mustNotExist("atomic.exe")
4092 tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
4093 tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
4096 func TestGoBuildARM(t *testing.T) {
4097 if testing.Short() {
4098 t.Skip("skipping cross-compile in short mode")
4107 tg.setenv("GOARCH", "arm")
4108 tg.setenv("GOOS", "linux")
4109 tg.setenv("GOARM", "5")
4110 tg.tempFile("hello.go", `package main
4112 tg.run("build", "hello.go")
4113 tg.grepStderrNot("unable to find math.a", "did not build math.a correctly")
4117 func TestParallelTest(t *testing.T) {
4123 const testSrc = `package package_test
4127 func TestTest(t *testing.T) {
4129 tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
4130 tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
4131 tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
4132 tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
4133 tg.setenv("GOPATH", tg.path("."))
4134 tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
4137 func TestCgoConsistentResults(t *testing.T) {
4140 t.Skip("skipping because cgo not enabled")
4142 switch runtime.GOOS {
4143 case "solaris", "illumos":
4144 testenv.SkipFlaky(t, 13247)
4151 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4152 exe1 := tg.path("cgotest1" + exeSuffix)
4153 exe2 := tg.path("cgotest2" + exeSuffix)
4154 tg.run("build", "-o", exe1, "cgotest")
4155 tg.run("build", "-x", "-o", exe2, "cgotest")
4156 b1, err := ioutil.ReadFile(exe1)
4158 b2, err := ioutil.ReadFile(exe2)
4161 if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) {
4162 t.Skip("skipping because C compiler does not support -fdebug-prefix-map")
4164 if !bytes.Equal(b1, b2) {
4165 t.Error("building cgotest twice did not produce the same output")
4169 // Issue 14444: go get -u .../ duplicate loads errors
4170 func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) {
4171 testenv.MustHaveExternalNetwork(t)
4176 tg.setenv("GOPATH", tg.path("."))
4177 tg.run("get", "-u", ".../")
4178 tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache")
4181 // Issue 17119 more duplicate load errors
4182 func TestIssue17119(t *testing.T) {
4183 testenv.MustHaveExternalNetwork(t)
4188 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4189 tg.runFail("build", "dupload")
4190 tg.grepBothNot("duplicate load|internal error", "internal error")
4193 func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) {
4196 // TODO: tg.parallel()
4197 tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal")
4198 tg.grepBothNot("^ok", "test passed unexpectedly")
4199 tg.grepBoth("FAIL.*benchfatal", "test did not run everything")
4202 func TestBinaryOnlyPackages(t *testing.T) {
4209 tg.setenv("GOPATH", tg.path("."))
4211 tg.tempFile("src/p1/p1.go", `//go:binary-only-package
4215 tg.wantStale("p1", "binary-only packages are no longer supported", "p1 is binary-only, and this message should always be printed")
4216 tg.runFail("install", "p1")
4217 tg.grepStderr("binary-only packages are no longer supported", "did not report attempt to compile binary-only package")
4219 tg.tempFile("src/p1/p1.go", `
4222 func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } }
4224 tg.run("install", "p1")
4225 os.Remove(tg.path("src/p1/p1.go"))
4226 tg.mustNotExist(tg.path("src/p1/p1.go"))
4228 tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great
4232 func F() { p1.F(true) }
4234 tg.runFail("install", "p2")
4235 tg.grepStderr("no Go files", "did not complain about missing sources")
4237 tg.tempFile("src/p1/missing.go", `//go:binary-only-package
4243 tg.wantStale("p1", "binary-only package", "should NOT want to rebuild p1 (first)")
4244 tg.runFail("install", "p2")
4245 tg.grepStderr("p1: binary-only packages are no longer supported", "did not report error for binary-only p1")
4247 tg.run("list", "-deps", "-f", "{{.ImportPath}}: {{.BinaryOnly}}", "p2")
4248 tg.grepStdout("p1: true", "p1 not listed as BinaryOnly")
4249 tg.grepStdout("p2: false", "p2 listed as BinaryOnly")
4252 // Issue 16050 and 21884.
4253 func TestLinkSysoFiles(t *testing.T) {
4254 if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
4255 t.Skip("not linux/amd64")
4261 tg.tempDir("src/syso")
4262 tg.tempFile("src/syso/a.syso", ``)
4263 tg.tempFile("src/syso/b.go", `package syso`)
4264 tg.setenv("GOPATH", tg.path("."))
4266 // We should see the .syso file regardless of the setting of
4269 tg.setenv("CGO_ENABLED", "1")
4270 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4271 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1")
4273 tg.setenv("CGO_ENABLED", "0")
4274 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4275 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0")
4277 tg.setenv("CGO_ENABLED", "1")
4278 tg.run("list", "-msan", "-f", "{{.SysoFiles}}", "syso")
4279 tg.grepStdoutNot("a.syso", "unexpected syso file with -msan")
4283 func TestGenerateUsesBuildContext(t *testing.T) {
4284 if runtime.GOOS == "windows" {
4285 t.Skip("this test won't run under Windows")
4291 tg.tempDir("src/gen")
4292 tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n")
4293 tg.setenv("GOPATH", tg.path("."))
4295 tg.setenv("GOOS", "linux")
4296 tg.setenv("GOARCH", "amd64")
4297 tg.run("generate", "gen")
4298 tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination")
4300 tg.setenv("GOOS", "darwin")
4301 tg.setenv("GOARCH", "386")
4302 tg.run("generate", "gen")
4303 tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination")
4306 // Issue 14450: go get -u .../ tried to import not downloaded package
4307 func TestGoGetUpdateWithWildcard(t *testing.T) {
4308 testenv.MustHaveExternalNetwork(t)
4309 testenv.MustHaveExecPath(t, "git")
4315 tg.setenv("GOPATH", tg.path("."))
4316 const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a"
4317 tg.run("get", aPkgImportPath)
4318 tg.runFail("get", "-u", ".../")
4319 tg.grepStderr("cannot find package.*d-dependency/e", "should have detected e missing")
4321 // Even though get -u failed, the source for others should be downloaded.
4322 var expectedPkgPaths = []string{
4323 "src/github.com/tmwh/go-get-issue-14450/b",
4324 "src/github.com/tmwh/go-get-issue-14450-b-dependency/c",
4325 "src/github.com/tmwh/go-get-issue-14450-b-dependency/d",
4328 for _, importPath := range expectedPkgPaths {
4329 _, err := os.Stat(tg.path(importPath))
4332 const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e"
4333 tg.mustNotExist(tg.path(notExpectedPkgPath))
4336 func TestGoEnv(t *testing.T) {
4340 tg.setenv("GOOS", "freebsd") // to avoid invalid pair errors
4341 tg.setenv("GOARCH", "arm")
4342 tg.run("env", "GOARCH")
4343 tg.grepStdout("^arm$", "GOARCH not honored")
4345 tg.run("env", "GCCGO")
4346 tg.grepStdout(".", "GCCGO unexpectedly empty")
4348 tg.run("env", "CGO_CFLAGS")
4349 tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty")
4351 tg.setenv("CGO_CFLAGS", "-foobar")
4352 tg.run("env", "CGO_CFLAGS")
4353 tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored")
4355 tg.setenv("CC", "gcc -fmust -fgo -ffaster")
4357 tg.grepStdout("gcc", "CC not found")
4358 tg.run("env", "GOGCCFLAGS")
4359 tg.grepStdout("-ffaster", "CC arguments not found")
4363 noMatchesPattern = `(?m)^ok.*\[no tests to run\]`
4364 okPattern = `(?m)^ok`
4367 func TestMatchesNoTests(t *testing.T) {
4370 // TODO: tg.parallel()
4371 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go")
4372 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4375 func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) {
4379 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4380 tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror")
4381 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4382 tg.grepBoth("FAIL", "go test did not say FAIL")
4385 func TestMatchesNoBenchmarksIsOK(t *testing.T) {
4388 // TODO: tg.parallel()
4389 tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go")
4390 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4391 tg.grepBoth(okPattern, "go test did not say ok")
4394 func TestMatchesOnlyExampleIsOK(t *testing.T) {
4397 // TODO: tg.parallel()
4398 tg.run("test", "-run", "Example", "testdata/example1_test.go")
4399 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4400 tg.grepBoth(okPattern, "go test did not say ok")
4403 func TestMatchesOnlyBenchmarkIsOK(t *testing.T) {
4406 // TODO: tg.parallel()
4407 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4408 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4409 tg.grepBoth(okPattern, "go test did not say ok")
4412 func TestBenchmarkLabels(t *testing.T) {
4415 // TODO: tg.parallel()
4416 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4417 tg.run("test", "-run", "^$", "-bench", ".", "bench")
4418 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4419 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4420 tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench")
4421 tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times")
4424 func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) {
4427 // TODO: tg.parallel()
4428 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4429 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4430 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4431 tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:")
4434 func TestMatchesOnlyTestIsOK(t *testing.T) {
4437 // TODO: tg.parallel()
4438 tg.run("test", "-run", "Test", "testdata/standalone_test.go")
4439 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4440 tg.grepBoth(okPattern, "go test did not say ok")
4443 func TestMatchesNoTestsWithSubtests(t *testing.T) {
4446 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go")
4447 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4450 func TestMatchesNoSubtestsMatch(t *testing.T) {
4453 tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go")
4454 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4457 func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) {
4460 tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go")
4461 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4462 tg.grepBoth("FAIL", "go test did not say FAIL")
4465 func TestMatchesOnlySubtestIsOK(t *testing.T) {
4468 tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go")
4469 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4470 tg.grepBoth(okPattern, "go test did not say ok")
4473 func TestMatchesNoSubtestsParallel(t *testing.T) {
4476 tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go")
4477 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4480 func TestMatchesOnlySubtestParallelIsOK(t *testing.T) {
4483 tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go")
4484 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4485 tg.grepBoth(okPattern, "go test did not say ok")
4489 func TestBenchTimeout(t *testing.T) {
4493 tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go")
4497 func TestWriteProfilesOnTimeout(t *testing.T) {
4501 tg.tempDir("profiling")
4502 tg.tempFile("profiling/timeouttest_test.go", `package timeouttest_test
4505 func TestSleep(t *testing.T) { time.Sleep(time.Second) }`)
4506 tg.cd(tg.path("profiling"))
4509 "-cpuprofile", tg.path("profiling/cpu.pprof"), "-memprofile", tg.path("profiling/mem.pprof"),
4511 tg.mustHaveContent(tg.path("profiling/cpu.pprof"))
4512 tg.mustHaveContent(tg.path("profiling/mem.pprof"))
4515 func TestLinkXImportPathEscape(t *testing.T) {
4516 // golang.org/issue/16710
4517 skipIfGccgo(t, "gccgo does not support -ldflags -X")
4522 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4523 exe := tg.path("linkx" + exeSuffix)
4524 tg.creatingTemp(exe)
4525 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main")
4526 out, err := exec.Command(exe).CombinedOutput()
4530 if string(out) != "linkXworked\n" {
4531 tg.t.Log(string(out))
4532 tg.t.Fatal(`incorrect output: expected "linkXworked\n"`)
4537 func TestLdBindNow(t *testing.T) {
4541 tg.setenv("LD_BIND_NOW", "1")
4546 // This is really a cmd/asm issue but this is a convenient place to test it.
4547 func TestConcurrentAsm(t *testing.T) {
4548 skipIfGccgo(t, "gccgo does not use cmd/asm")
4552 asm := `DATA ·constants<>+0x0(SB)/8,$0
4553 GLOBL ·constants<>(SB),8,$8
4555 tg.tempFile("go/src/p/a.s", asm)
4556 tg.tempFile("go/src/p/b.s", asm)
4557 tg.tempFile("go/src/p/p.go", `package p`)
4558 tg.setenv("GOPATH", tg.path("go"))
4559 tg.run("build", "p")
4563 func TestDotDotDotOutsideGOPATH(t *testing.T) {
4567 tg.tempFile("pkgs/a.go", `package x`)
4568 tg.tempFile("pkgs/a_test.go", `package x_test
4570 func TestX(t *testing.T) {}`)
4572 tg.tempFile("pkgs/a/a.go", `package a`)
4573 tg.tempFile("pkgs/a/a_test.go", `package a_test
4575 func TestA(t *testing.T) {}`)
4577 tg.cd(tg.path("pkgs"))
4578 tg.run("build", "./...")
4579 tg.run("test", "./...")
4580 tg.run("list", "./...")
4581 tg.grepStdout("pkgs$", "expected package not listed")
4582 tg.grepStdout("pkgs/a", "expected package not listed")
4586 func TestFFLAGS(t *testing.T) {
4588 t.Skip("skipping because cgo not enabled")
4595 tg.tempFile("p/src/p/main.go", `package main
4596 // #cgo FFLAGS: -no-such-fortran-flag
4600 tg.tempFile("p/src/p/a.f", `! comment`)
4601 tg.setenv("GOPATH", tg.path("p"))
4603 // This should normally fail because we are passing an unknown flag,
4604 // but issue #19080 points to Fortran compilers that succeed anyhow.
4605 // To work either way we call doRun directly rather than run or runFail.
4606 tg.doRun([]string{"build", "-x", "p"})
4608 tg.grepStderr("no-such-fortran-flag", `missing expected "-no-such-fortran-flag"`)
4612 // This is really a cmd/link issue but this is a convenient place to test it.
4613 func TestDuplicateGlobalAsmSymbols(t *testing.T) {
4614 skipIfGccgo(t, "gccgo does not use cmd/asm")
4616 if runtime.GOARCH != "386" && runtime.GOARCH != "amd64" {
4617 t.Skipf("skipping test on %s", runtime.GOARCH)
4620 t.Skip("skipping because cgo not enabled")
4628 #include "textflag.h"
4630 DATA sym<>+0x0(SB)/8,$0
4631 GLOBL sym<>(SB),(NOPTR+RODATA),$8
4633 TEXT ·Data(SB),NOSPLIT,$0
4638 tg.tempFile("go/src/a/a.s", asm)
4639 tg.tempFile("go/src/a/a.go", `package a; func Data() uint8`)
4640 tg.tempFile("go/src/b/b.s", asm)
4641 tg.tempFile("go/src/b/b.go", `package b; func Data() uint8`)
4642 tg.tempFile("go/src/p/p.go", `
4648 _ = a.Data() + b.Data()
4651 tg.setenv("GOPATH", tg.path("go"))
4652 exe := tg.path("p.exe")
4653 tg.creatingTemp(exe)
4654 tg.run("build", "-o", exe, "p")
4657 func TestBuildTagsNoComma(t *testing.T) {
4658 skipIfGccgo(t, "gccgo has no standard packages")
4662 tg.setenv("GOPATH", tg.path("go"))
4663 tg.run("build", "-tags", "tag1 tag2", "math")
4664 tg.runFail("build", "-tags", "tag1,tag2 tag3", "math")
4665 tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
4668 func copyFile(src, dst string, perm os.FileMode) error {
4669 sf, err := os.Open(src)
4675 df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
4680 _, err = io.Copy(df, sf)
4688 // TestExecutableGOROOT verifies that the cmd/go binary itself uses
4689 // os.Executable (when available) to locate GOROOT.
4690 func TestExecutableGOROOT(t *testing.T) {
4691 skipIfGccgo(t, "gccgo has no GOROOT")
4693 // Note: Must not call tg methods inside subtests: tg is attached to outer t.
4695 tg.unsetenv("GOROOT")
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)
4721 tg.tempDir("new/bin")
4722 newGoTool := tg.path("new/bin/go" + exeSuffix)
4723 tg.must(copyFile(tg.goTool(), newGoTool, 0775))
4724 newRoot := tg.path("new")
4726 t.Run("RelocatedExe", func(t *testing.T) {
4727 // Should fall back to default location in binary,
4728 // which is the GOROOT we used when building testgo.exe.
4729 check(t, newGoTool, testGOROOT)
4732 // If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT,
4733 // so it should find the new tree.
4734 tg.tempDir("new/pkg/tool")
4735 t.Run("RelocatedTree", func(t *testing.T) {
4736 check(t, newGoTool, newRoot)
4739 tg.tempDir("other/bin")
4740 symGoTool := tg.path("other/bin/go" + exeSuffix)
4742 // Symlink into go tree should still find go tree.
4743 t.Run("SymlinkedExe", func(t *testing.T) {
4744 testenv.MustHaveSymlink(t)
4745 if err := os.Symlink(newGoTool, symGoTool); err != nil {
4748 check(t, symGoTool, newRoot)
4751 tg.must(robustio.RemoveAll(tg.path("new/pkg")))
4753 // Binaries built in the new tree should report the
4754 // new tree when they call runtime.GOROOT.
4755 t.Run("RuntimeGoroot", func(t *testing.T) {
4756 // Build a working GOROOT the easy way, with symlinks.
4757 testenv.MustHaveSymlink(t)
4758 if err := os.Symlink(filepath.Join(testGOROOT, "src"), tg.path("new/src")); err != nil {
4761 if err := os.Symlink(filepath.Join(testGOROOT, "pkg"), tg.path("new/pkg")); err != nil {
4765 cmd := exec.Command(newGoTool, "run", "testdata/print_goroot.go")
4767 cmd.Stderr = os.Stderr
4768 out, err := cmd.Output()
4770 t.Fatalf("%s run testdata/print_goroot.go: %v, %s", newGoTool, err, out)
4772 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4776 want, err := filepath.EvalSymlinks(tg.path("new"))
4780 if !strings.EqualFold(goroot, want) {
4781 t.Errorf("go run testdata/print_goroot.go:\nhave %s\nwant %s", goroot, want)
4783 t.Logf("go run testdata/print_goroot.go: %s", goroot)
4788 func TestNeedVersion(t *testing.T) {
4789 skipIfGccgo(t, "gccgo does not use cmd/compile")
4793 tg.tempFile("goversion.go", `package main; func main() {}`)
4794 path := tg.path("goversion.go")
4795 tg.setenv("TESTGO_VERSION", "go1.testgo")
4796 tg.runFail("run", path)
4797 tg.grepStderr("compile", "does not match go tool version")
4800 // Test that user can override default code generation flags.
4801 func TestUserOverrideFlags(t *testing.T) {
4802 skipIfGccgo(t, "gccgo does not use -gcflags")
4804 t.Skip("skipping because cgo not enabled")
4806 if runtime.GOOS != "linux" {
4807 // We are testing platform-independent code, so it's
4808 // OK to skip cases that work differently.
4809 t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS)
4814 // Don't call tg.parallel, as creating override.h and override.a may
4815 // confuse other tests.
4816 tg.tempFile("override.go", `package main
4824 tg.creatingTemp("override.a")
4825 tg.creatingTemp("override.h")
4826 tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=all=-shared=false", tg.path("override.go"))
4827 tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag")
4830 func TestCgoFlagContainsSpace(t *testing.T) {
4833 t.Skip("skipping because cgo not enabled")
4840 tg.tempFile("main.go", `package main
4841 // #cgo CFLAGS: -I"c flags"
4842 // #cgo LDFLAGS: -L"ld flags"
4846 tg.run("run", "-x", "main.go")
4847 tg.grepStderr(`"-I[^"]+c flags"`, "did not find quoted c flags")
4848 tg.grepStderrNot(`"-I[^"]+c flags".*"-I[^"]+c flags"`, "found too many quoted c flags")
4849 tg.grepStderr(`"-L[^"]+ld flags"`, "did not find quoted ld flags")
4850 tg.grepStderrNot(`"-L[^"]+c flags".*"-L[^"]+c flags"`, "found too many quoted ld flags")
4854 func TestGoTestRaceCoverModeFailures(t *testing.T) {
4857 t.Skip("skipping because race detector not supported")
4863 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4865 tg.run("test", "testrace")
4867 tg.runFail("test", "-race", "-covermode=set", "testrace")
4868 tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed")
4869 tg.grepBothNot("PASS", "something passed")
4872 // Issue 9737: verify that GOARM and GO386 affect the computed build ID.
4873 func TestBuildIDContainsArchModeEnv(t *testing.T) {
4874 if testing.Short() {
4875 t.Skip("skipping in short mode")
4879 testWith := func(before, after func()) func(*testing.T) {
4880 return func(t *testing.T) {
4883 tg.tempFile("src/mycmd/x.go", `package main
4885 tg.setenv("GOPATH", tg.path("."))
4887 tg.cd(tg.path("src/mycmd"))
4888 tg.setenv("GOOS", "linux")
4890 tg.run("install", "mycmd")
4892 tg.wantStale("mycmd", "stale dependency", "should be stale after environment variable change")
4896 t.Run("386", testWith(func() {
4897 tg.setenv("GOARCH", "386")
4898 tg.setenv("GO386", "387")
4900 tg.setenv("GO386", "sse2")
4903 t.Run("arm", testWith(func() {
4904 tg.setenv("GOARCH", "arm")
4905 tg.setenv("GOARM", "5")
4907 tg.setenv("GOARM", "7")
4911 func TestTestRegexps(t *testing.T) {
4914 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4915 tg.run("test", "-cpu=1", "-run=X/Y", "-bench=X/Y", "-count=2", "-v", "testregexp")
4917 for _, line := range strings.SplitAfter(tg.getStdout(), "\n") {
4918 if strings.Contains(line, "=== RUN") || strings.Contains(line, "--- BENCH") || strings.Contains(line, "LOG") {
4919 lines = append(lines, line)
4924 // TestX is run, twice
4925 // TestX/Y is run, twice
4926 // TestXX is run, twice
4928 // BenchmarkX is run but only with N=1, once
4929 // BenchmarkXX is run but only with N=1, once
4930 // BenchmarkX/Y is run in full, twice
4931 want := `=== RUN TestX
4932 TestX: x_test.go:6: LOG: X running
4934 TestX/Y: x_test.go:8: LOG: Y running
4936 TestXX: z_test.go:10: LOG: XX running
4938 TestX: x_test.go:6: LOG: X running
4940 TestX/Y: x_test.go:8: LOG: Y running
4942 TestXX: z_test.go:10: LOG: XX running
4943 BenchmarkX: x_test.go:13: LOG: X running N=1
4944 BenchmarkX/Y: x_test.go:15: LOG: Y running N=1
4945 BenchmarkX/Y: x_test.go:15: LOG: Y running N=100
4946 BenchmarkX/Y: x_test.go:15: LOG: Y running N=10000
4947 BenchmarkX/Y: x_test.go:15: LOG: Y running N=1000000
4948 BenchmarkX/Y: x_test.go:15: LOG: Y running N=100000000
4949 BenchmarkX/Y: x_test.go:15: LOG: Y running N=1000000000
4950 BenchmarkX/Y: x_test.go:15: LOG: Y running N=1
4951 BenchmarkX/Y: x_test.go:15: LOG: Y running N=100
4952 BenchmarkX/Y: x_test.go:15: LOG: Y running N=10000
4953 BenchmarkX/Y: x_test.go:15: LOG: Y running N=1000000
4954 BenchmarkX/Y: x_test.go:15: LOG: Y running N=100000000
4955 BenchmarkX/Y: x_test.go:15: LOG: Y running N=1000000000
4956 BenchmarkXX: z_test.go:18: LOG: XX running N=1
4959 have := strings.Join(lines, "")
4961 t.Errorf("reduced output:<<<\n%s>>> want:<<<\n%s>>>", have, want)
4965 func TestListTests(t *testing.T) {
4968 testWith := func(listName, expected string) func(*testing.T) {
4969 return func(t *testing.T) {
4972 tg.run("test", "./testdata/src/testlist/...", fmt.Sprintf("-list=%s", listName))
4973 tg.grepStdout(expected, fmt.Sprintf("-test.list=%s returned %q, expected %s", listName, tg.getStdout(), expected))
4977 t.Run("Test", testWith("Test", "TestSimple"))
4978 t.Run("Bench", testWith("Benchmark", "BenchmarkSimple"))
4979 t.Run("Example1", testWith("Example", "ExampleSimple"))
4980 t.Run("Example2", testWith("Example", "ExampleWithEmptyOutput"))
4983 func TestBuildmodePIE(t *testing.T) {
4984 if testing.Short() && testenv.Builder() == "" {
4985 t.Skipf("skipping in -short mode on non-builder")
4988 platform := fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
4990 case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x",
4991 "android/amd64", "android/arm", "android/arm64", "android/386",
4993 case "darwin/amd64":
4995 t.Skipf("skipping test because buildmode=pie is not supported on %s", platform)
5001 tg.tempFile("main.go", `package main; func main() { print("hello") }`)
5002 src := tg.path("main.go")
5003 obj := tg.path("main")
5004 tg.run("build", "-buildmode=pie", "-o", obj, src)
5006 switch runtime.GOOS {
5007 case "linux", "android", "freebsd":
5008 f, err := elf.Open(obj)
5013 if f.Type != elf.ET_DYN {
5014 t.Errorf("PIE type must be ET_DYN, but %s", f.Type)
5017 f, err := macho.Open(obj)
5022 if f.Flags&macho.FlagDyldLink == 0 {
5023 t.Error("PIE must have DyldLink flag, but not")
5025 if f.Flags&macho.FlagPIE == 0 {
5026 t.Error("PIE must have PIE flag, but not")
5029 panic("unreachable")
5032 out, err := exec.Command(obj).CombinedOutput()
5037 if string(out) != "hello" {
5038 t.Errorf("got %q; want %q", out, "hello")
5042 func TestExecBuildX(t *testing.T) {
5045 t.Skip("skipping because cgo not enabled")
5048 testenv.MustHaveExecPath(t, "/usr/bin/env")
5049 testenv.MustHaveExecPath(t, "bash")
5055 tg.setenv("GOCACHE", tg.path("cache"))
5057 // Before building our test main.go, ensure that an up-to-date copy of
5058 // runtime/cgo is present in the cache. If it isn't, the 'go build' step below
5059 // will fail with "can't open import". See golang.org/issue/29004.
5060 tg.run("build", "runtime/cgo")
5062 tg.tempFile("main.go", `package main; import "C"; func main() { print("hello") }`)
5063 src := tg.path("main.go")
5064 obj := tg.path("main")
5065 tg.run("build", "-x", "-o", obj, src)
5066 sh := tg.path("test.sh")
5067 cmds := tg.getStderr()
5068 err := ioutil.WriteFile(sh, []byte("set -e\n"+cmds), 0666)
5073 out, err := exec.Command(obj).CombinedOutput()
5077 if string(out) != "hello" {
5078 t.Fatalf("got %q; want %q", out, "hello")
5081 err = os.Remove(obj)
5086 out, err = exec.Command("/usr/bin/env", "bash", "-x", sh).CombinedOutput()
5088 t.Fatalf("/bin/sh %s: %v\n%s", sh, err, out)
5090 t.Logf("shell output:\n%s", out)
5092 out, err = exec.Command(obj).CombinedOutput()
5096 if string(out) != "hello" {
5097 t.Fatalf("got %q; want %q", out, "hello")
5100 matches := regexp.MustCompile(`^WORK=(.*)\n`).FindStringSubmatch(cmds)
5101 if len(matches) == 0 {
5102 t.Fatal("no WORK directory")
5104 tg.must(robustio.RemoveAll(matches[1]))
5107 func TestParallelNumber(t *testing.T) {
5109 for _, n := range [...]string{"-1", "0"} {
5110 t.Run(n, func(t *testing.T) {
5113 tg.runFail("test", "-parallel", n, "testdata/standalone_parallel_sub_test.go")
5114 tg.grepBoth("-parallel can only be given", "go test -parallel with N<1 did not error")
5119 func TestWrongGOOSErrorBeforeLoadError(t *testing.T) {
5120 skipIfGccgo(t, "gccgo assumes cross-compilation is always possible")
5123 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5124 tg.setenv("GOOS", "windwos")
5125 tg.runFail("build", "exclude")
5126 tg.grepStderr("unsupported GOOS/GOARCH pair", "GOOS=windwos go build exclude did not report 'unsupported GOOS/GOARCH pair'")
5129 func TestUpxCompression(t *testing.T) {
5130 if runtime.GOOS != "linux" ||
5131 (runtime.GOARCH != "amd64" && runtime.GOARCH != "386") {
5132 t.Skipf("skipping upx test on %s/%s", runtime.GOOS, runtime.GOARCH)
5135 testenv.MustHaveExecPath(t, "upx")
5136 out, err := exec.Command("upx", "--version").CombinedOutput()
5138 t.Fatalf("upx --version failed: %v", err)
5141 // upx --version prints `upx <version>` in the first line of output:
5144 re := regexp.MustCompile(`([[:digit:]]+)\.([[:digit:]]+)`)
5145 upxVersion := re.FindStringSubmatch(string(out))
5146 if len(upxVersion) != 3 {
5147 t.Fatalf("bad upx version string: %s", upxVersion)
5150 major, err1 := strconv.Atoi(upxVersion[1])
5151 minor, err2 := strconv.Atoi(upxVersion[2])
5152 if err1 != nil || err2 != nil {
5153 t.Fatalf("bad upx version string: %s", upxVersion[0])
5156 // Anything below 3.94 is known not to work with go binaries
5157 if (major < 3) || (major == 3 && minor < 94) {
5158 t.Skipf("skipping because upx version %v.%v is too old", major, minor)
5164 tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello upx") }`)
5165 src := tg.path("main.go")
5166 obj := tg.path("main")
5167 tg.run("build", "-o", obj, src)
5169 out, err = exec.Command("upx", obj).CombinedOutput()
5171 t.Logf("executing upx\n%s\n", out)
5172 t.Fatalf("upx failed with %v", err)
5175 out, err = exec.Command(obj).CombinedOutput()
5178 t.Fatalf("running compressed go binary failed with error %s", err)
5180 if string(out) != "hello upx" {
5181 t.Fatalf("bad output from compressed go binary:\ngot %q; want %q", out, "hello upx")
5185 func TestCacheListStale(t *testing.T) {
5187 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5188 t.Skip("GODEBUG gocacheverify")
5194 tg.setenv("GOCACHE", tg.path("cache"))
5195 tg.tempFile("gopath/src/p/p.go", "package p; import _ \"q\"; func F(){}\n")
5196 tg.tempFile("gopath/src/q/q.go", "package q; func F(){}\n")
5197 tg.tempFile("gopath/src/m/m.go", "package main; import _ \"q\"; func main(){}\n")
5199 tg.setenv("GOPATH", tg.path("gopath"))
5200 tg.run("install", "p", "m")
5201 tg.run("list", "-f={{.ImportPath}} {{.Stale}}", "m", "q", "p")
5202 tg.grepStdout("^m false", "m should not be stale")
5203 tg.grepStdout("^q true", "q should be stale")
5204 tg.grepStdout("^p false", "p should not be stale")
5207 func TestCacheCoverage(t *testing.T) {
5210 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5211 t.Skip("GODEBUG gocacheverify")
5217 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5220 tg.setenv("GOCACHE", tg.path("c1"))
5221 tg.run("test", "-cover", "-short", "strings")
5222 tg.run("test", "-cover", "-short", "math", "strings")
5225 func TestCacheVet(t *testing.T) {
5226 skipIfGccgo(t, "gccgo has no standard packages")
5231 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5232 t.Skip("GODEBUG gocacheverify")
5234 if testing.Short() {
5235 // In short mode, reuse cache.
5236 // Test failures may be masked if the cache has just the right entries already
5237 // (not a concern during all.bash, which runs in a clean cache).
5238 if cfg.Getenv("GOCACHE") == "off" {
5243 tg.setenv("GOCACHE", tg.path("cache"))
5246 // Check that second vet reuses cgo-derived inputs.
5247 // The first command could be build instead of vet,
5248 // except that if the cache is empty and there's a net.a
5249 // in GOROOT/pkg, the build will not bother to regenerate
5250 // and cache the cgo outputs, whereas vet always will.
5251 tg.run("vet", "os/user")
5252 tg.run("vet", "-x", "os/user")
5253 tg.grepStderrNot(`^(clang|gcc)`, "should not have run compiler")
5254 tg.grepStderrNot(`[\\/]cgo `, "should not have run cgo")
5257 func TestIssue22588(t *testing.T) {
5258 // Don't get confused by stderr coming from tools.
5263 if _, err := os.Stat("/usr/bin/time"); err != nil {
5267 tg.run("list", "-f={{.Stale}}", "runtime")
5268 tg.run("list", "-toolexec=/usr/bin/time", "-f={{.Stale}}", "runtime")
5269 tg.grepStdout("false", "incorrectly reported runtime as stale")
5272 func TestIssue22531(t *testing.T) {
5274 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5275 t.Skip("GODEBUG gocacheverify")
5281 tg.setenv("GOPATH", tg.tempdir)
5282 tg.setenv("GOCACHE", tg.path("cache"))
5283 tg.tempFile("src/m/main.go", "package main /* c1 */; func main() {}\n")
5284 tg.run("install", "-x", "m")
5285 tg.run("list", "-f", "{{.Stale}}", "m")
5286 tg.grepStdout("false", "reported m as stale after install")
5287 tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5289 // The link action ID did not include the full main build ID,
5290 // even though the full main build ID is written into the
5291 // eventual binary. That caused the following install to
5292 // be a no-op, thinking the gofmt binary was up-to-date,
5293 // even though .Stale could see it was not.
5294 tg.tempFile("src/m/main.go", "package main /* c2 */; func main() {}\n")
5295 tg.run("install", "-x", "m")
5296 tg.run("list", "-f", "{{.Stale}}", "m")
5297 tg.grepStdout("false", "reported m as stale after reinstall")
5298 tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5301 func TestIssue22596(t *testing.T) {
5303 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5304 t.Skip("GODEBUG gocacheverify")
5310 tg.setenv("GOCACHE", tg.path("cache"))
5311 tg.tempFile("gopath1/src/p/p.go", "package p; func F(){}\n")
5312 tg.tempFile("gopath2/src/p/p.go", "package p; func F(){}\n")
5314 tg.setenv("GOPATH", tg.path("gopath1"))
5315 tg.run("list", "-f={{.Target}}", "p")
5316 target1 := strings.TrimSpace(tg.getStdout())
5317 tg.run("install", "p")
5318 tg.wantNotStale("p", "", "p stale after install")
5320 tg.setenv("GOPATH", tg.path("gopath2"))
5321 tg.run("list", "-f={{.Target}}", "p")
5322 target2 := strings.TrimSpace(tg.getStdout())
5323 tg.must(os.MkdirAll(filepath.Dir(target2), 0777))
5324 tg.must(copyFile(target1, target2, 0666))
5325 tg.wantStale("p", "build ID mismatch", "p not stale after copy from gopath1")
5326 tg.run("install", "p")
5327 tg.wantNotStale("p", "", "p stale after install2")
5330 func TestTestCache(t *testing.T) {
5333 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5334 t.Skip("GODEBUG gocacheverify")
5340 tg.setenv("GOPATH", tg.tempdir)
5341 tg.setenv("GOCACHE", tg.path("cache"))
5343 if runtime.Compiler != "gccgo" {
5344 // timeout here should not affect result being cached
5345 // or being retrieved later.
5346 tg.run("test", "-x", "-timeout=10s", "errors")
5347 tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler")
5348 tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
5349 tg.grepStderr(`errors\.test`, "did not run test")
5351 tg.run("test", "-x", "errors")
5352 tg.grepStdout(`ok \terrors\t\(cached\)`, "did not report cached result")
5353 tg.grepStderrNot(`[\\/]compile|gccgo`, "incorrectly ran compiler")
5354 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly ran linker")
5355 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5356 tg.grepStderrNot("DO NOT USE", "poisoned action status leaked")
5358 // Even very low timeouts do not disqualify cached entries.
5359 tg.run("test", "-timeout=1ns", "-x", "errors")
5360 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5362 tg.run("clean", "-testcache")
5363 tg.run("test", "-x", "errors")
5364 tg.grepStderr(`errors\.test`, "did not run test")
5367 // The -p=1 in the commands below just makes the -x output easier to read.
5369 t.Log("\n\nINITIAL\n\n")
5371 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5372 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\nvar X = 1\n")
5373 tg.tempFile("src/t/t1/t1_test.go", "package t\nimport \"testing\"\nfunc Test1(*testing.T) {}\n")
5374 tg.tempFile("src/t/t2/t2_test.go", "package t\nimport _ \"p1\"\nimport \"testing\"\nfunc Test2(*testing.T) {}\n")
5375 tg.tempFile("src/t/t3/t3_test.go", "package t\nimport \"p1\"\nimport \"testing\"\nfunc Test3(t *testing.T) {t.Log(p1.X)}\n")
5376 tg.tempFile("src/t/t4/t4_test.go", "package t\nimport \"p2\"\nimport \"testing\"\nfunc Test4(t *testing.T) {t.Log(p2.X)}")
5377 tg.run("test", "-x", "-v", "-short", "t/...")
5379 t.Log("\n\nREPEAT\n\n")
5381 tg.run("test", "-x", "-v", "-short", "t/...")
5382 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5383 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5384 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5385 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5386 tg.grepStderrNot(`[\\/](compile|gccgo) `, "incorrectly ran compiler")
5387 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5388 tg.grepStderrNot(`p[0-9]\.test`, "incorrectly ran test")
5390 t.Log("\n\nCOMMENT\n\n")
5392 // Changing the program text without affecting the compiled package
5393 // should result in the package being rebuilt but nothing more.
5394 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 01\n")
5395 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5396 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5397 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5398 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5399 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5400 tg.grepStderrNot(`([\\/](compile|gccgo) ).*t[0-9]_test\.go`, "incorrectly ran compiler")
5401 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5402 tg.grepStderrNot(`t[0-9]\.test.*test\.short`, "incorrectly ran test")
5404 t.Log("\n\nCHANGE\n\n")
5406 // Changing the actual package should have limited effects.
5407 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 02\n")
5408 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5410 // p2 should have been rebuilt.
5411 tg.grepStderr(`([\\/]compile|gccgo).*p2.go`, "did not recompile p2")
5413 // t1 does not import anything, should not have been rebuilt.
5414 tg.grepStderrNot(`([\\/]compile|gccgo).*t1_test.go`, "incorrectly recompiled t1")
5415 tg.grepStderrNot(`([\\/]link|gccgo).*t1_test`, "incorrectly relinked t1_test")
5416 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t/t1")
5418 // t2 imports p1 and must be rebuilt and relinked,
5419 // but the change should not have any effect on the test binary,
5420 // so the test should not have been rerun.
5421 tg.grepStderr(`([\\/]compile|gccgo).*t2_test.go`, "did not recompile t2")
5422 tg.grepStderr(`([\\/]link|gccgo).*t2\.test`, "did not relink t2_test")
5423 // This check does not currently work with gccgo, as garbage
5424 // collection of unused variables is not turned on by default.
5425 if runtime.Compiler != "gccgo" {
5426 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t/t2")
5429 // t3 imports p1, and changing X changes t3's test binary.
5430 tg.grepStderr(`([\\/]compile|gccgo).*t3_test.go`, "did not recompile t3")
5431 tg.grepStderr(`([\\/]link|gccgo).*t3\.test`, "did not relink t3_test")
5432 tg.grepStderr(`t3\.test.*-test.short`, "did not rerun t3_test")
5433 tg.grepStdoutNot(`ok \tt/t3\t\(cached\)`, "reported cached t3_test result")
5435 // t4 imports p2, but p2 did not change, so t4 should be relinked, not recompiled,
5437 tg.grepStderrNot(`([\\/]compile|gccgo).*t4_test.go`, "incorrectly recompiled t4")
5438 tg.grepStderr(`([\\/]link|gccgo).*t4\.test`, "did not relink t4_test")
5439 // This check does not currently work with gccgo, as garbage
5440 // collection of unused variables is not turned on by default.
5441 if runtime.Compiler != "gccgo" {
5442 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t/t4")
5446 func TestTestCacheInputs(t *testing.T) {
5449 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5450 t.Skip("GODEBUG gocacheverify")
5456 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5457 tg.setenv("GOCACHE", tg.path("cache"))
5459 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5460 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"))
5461 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("x"), 0644))
5462 old := time.Now().Add(-1 * time.Minute)
5463 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5464 info, err := os.Stat(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5468 t.Logf("file.txt: old=%v, info.ModTime=%v", old, info.ModTime()) // help debug when Chtimes lies about succeeding
5469 tg.setenv("TESTKEY", "x")
5471 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), []byte("#!/bin/sh\nexit 0\n"), 0755))
5472 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old, old))
5474 tg.run("test", "testcache")
5475 tg.run("test", "testcache")
5476 tg.grepStdout(`\(cached\)`, "did not cache")
5478 tg.setenv("TESTKEY", "y")
5479 tg.run("test", "testcache")
5480 tg.grepStdoutNot(`\(cached\)`, "did not notice env var change")
5481 tg.run("test", "testcache")
5482 tg.grepStdout(`\(cached\)`, "did not cache")
5484 tg.run("test", "testcache", "-run=FileSize")
5485 tg.run("test", "testcache", "-run=FileSize")
5486 tg.grepStdout(`\(cached\)`, "did not cache")
5487 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxx"), 0644))
5488 tg.run("test", "testcache", "-run=FileSize")
5489 tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5490 tg.run("test", "testcache", "-run=FileSize")
5491 tg.grepStdout(`\(cached\)`, "did not cache")
5493 tg.run("test", "testcache", "-run=Chdir")
5494 tg.run("test", "testcache", "-run=Chdir")
5495 tg.grepStdout(`\(cached\)`, "did not cache")
5496 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxxxx"), 0644))
5497 tg.run("test", "testcache", "-run=Chdir")
5498 tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5499 tg.run("test", "testcache", "-run=Chdir")
5500 tg.grepStdout(`\(cached\)`, "did not cache")
5502 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5503 tg.run("test", "testcache", "-run=FileContent")
5504 tg.run("test", "testcache", "-run=FileContent")
5505 tg.grepStdout(`\(cached\)`, "did not cache")
5506 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("yyy"), 0644))
5507 old2 := old.Add(10 * time.Second)
5508 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old2, old2))
5509 tg.run("test", "testcache", "-run=FileContent")
5510 tg.grepStdoutNot(`\(cached\)`, "did not notice file content change")
5511 tg.run("test", "testcache", "-run=FileContent")
5512 tg.grepStdout(`\(cached\)`, "did not cache")
5514 tg.run("test", "testcache", "-run=DirList")
5515 tg.run("test", "testcache", "-run=DirList")
5516 tg.grepStdout(`\(cached\)`, "did not cache")
5517 tg.must(os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt")))
5518 tg.run("test", "testcache", "-run=DirList")
5519 tg.grepStdoutNot(`\(cached\)`, "did not notice directory change")
5520 tg.run("test", "testcache", "-run=DirList")
5521 tg.grepStdout(`\(cached\)`, "did not cache")
5523 tg.tempFile("file.txt", "")
5524 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"), []byte(`package testcache
5531 func TestExternalFile(t *testing.T) {
5532 os.Open(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5533 _, err := os.Stat(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5539 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"))
5540 tg.run("test", "testcache", "-run=ExternalFile")
5541 tg.run("test", "testcache", "-run=ExternalFile")
5542 tg.grepStdout(`\(cached\)`, "did not cache")
5543 tg.must(os.Remove(filepath.Join(tg.tempdir, "file.txt")))
5544 tg.run("test", "testcache", "-run=ExternalFile")
5545 tg.grepStdout(`\(cached\)`, "did not cache")
5547 switch runtime.GOOS {
5548 case "plan9", "windows":
5551 tg.run("test", "testcache", "-run=Exec")
5552 tg.run("test", "testcache", "-run=Exec")
5553 tg.grepStdout(`\(cached\)`, "did not cache")
5554 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old2, old2))
5555 tg.run("test", "testcache", "-run=Exec")
5556 tg.grepStdoutNot(`\(cached\)`, "did not notice script change")
5557 tg.run("test", "testcache", "-run=Exec")
5558 tg.grepStdout(`\(cached\)`, "did not cache")
5562 func TestTestVet(t *testing.T) {
5568 tg.tempFile("p1_test.go", `
5571 func Test(t *testing.T) {
5572 t.Logf("%d") // oops
5576 tg.runFail("test", tg.path("p1_test.go"))
5577 tg.grepStderr(`Logf format %d`, "did not diagnose bad Logf")
5578 tg.run("test", "-vet=off", tg.path("p1_test.go"))
5579 tg.grepStdout(`^ok`, "did not print test summary")
5581 tg.tempFile("p1.go", `
5585 fmt.Printf("%d") // oops
5588 tg.runFail("test", tg.path("p1.go"))
5589 tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5590 tg.run("test", "-x", "-vet=shift", tg.path("p1.go"))
5591 tg.grepStderr(`[\\/]vet.*-shift`, "did not run vet with -shift")
5592 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5593 tg.run("test", "-vet=off", tg.path("p1.go"))
5594 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5596 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5597 tg.run("test", "vetcycle") // must not fail; #22890
5599 tg.runFail("test", "vetfail/...")
5600 tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5601 tg.grepStdout(`ok\s+vetfail/p2`, "did not run vetfail/p2")
5603 // Use -a so that we need to recompute the vet-specific export data for
5605 tg.run("test", "-a", "vetfail/p2")
5606 tg.grepStderrNot(`invalid.*constraint`, "did diagnose bad build constraint in vetxonly mode")
5609 func TestTestSkipVetAfterFailedBuild(t *testing.T) {
5614 tg.tempFile("x_test.go", `package x
5620 tg.runFail("test", tg.path("x_test.go"))
5621 tg.grepStderrNot(`vet`, "vet should be skipped after the failed build")
5624 func TestTestVetRebuild(t *testing.T) {
5630 // golang.org/issue/23701.
5631 // b_test imports b with augmented method from export_test.go.
5632 // b_test also imports a, which imports b.
5633 // Must not accidentally see un-augmented b propagate through a to b_test.
5634 tg.tempFile("src/a/a.go", `package a
5637 func (*Type) M() b.T {return 0}
5639 tg.tempFile("src/b/b.go", `package b
5641 type I interface {M() T}
5643 tg.tempFile("src/b/export_test.go", `package b
5644 func (*T) Method() *T { return nil }
5646 tg.tempFile("src/b/b_test.go", `package b_test
5652 func TestBroken(t *testing.T) {
5659 tg.setenv("GOPATH", tg.path("."))
5664 func TestInstallDeps(t *testing.T) {
5670 tg.setenv("GOPATH", tg.tempdir)
5672 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5673 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\n")
5674 tg.tempFile("src/main1/main.go", "package main\nimport _ \"p2\"\nfunc main() {}\n")
5676 tg.run("list", "-f={{.Target}}", "p1")
5677 p1 := strings.TrimSpace(tg.getStdout())
5678 tg.run("list", "-f={{.Target}}", "p2")
5679 p2 := strings.TrimSpace(tg.getStdout())
5680 tg.run("list", "-f={{.Target}}", "main1")
5681 main1 := strings.TrimSpace(tg.getStdout())
5683 tg.run("install", "main1")
5689 tg.run("install", "p2")
5693 // don't let install -i overwrite runtime
5694 tg.wantNotStale("runtime", "", "must be non-stale before install -i")
5696 tg.run("install", "-i", "main1")
5698 tg.must(os.Remove(p1))
5700 tg.run("install", "-i", "p2")
5704 func TestGoTestMinusN(t *testing.T) {
5705 // Intent here is to verify that 'go test -n' works without crashing.
5706 // This reuses flag_test.go, but really any test would do.
5709 tg.run("test", "testdata/flag_test.go", "-n", "-args", "-v=7")
5712 func TestGoTestJSON(t *testing.T) {
5713 skipIfGccgo(t, "gccgo does not have standard packages")
5720 tg.setenv("GOCACHE", tg.tempdir)
5721 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5723 // It would be nice to test that the output is interlaced
5724 // but it seems to be impossible to do that in a short test
5725 // that isn't also flaky. Just check that we get JSON output.
5726 tg.run("test", "-json", "-short", "-v", "errors", "empty/pkg", "skipper")
5727 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5728 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5730 tg.grepStdout(`"Action":"output","Package":"empty/pkg","Output":".*no test files`, "did not see no test files print")
5731 tg.grepStdout(`"Action":"skip","Package":"empty/pkg"`, "did not see skip")
5733 tg.grepStdout(`"Action":"output","Package":"skipper","Test":"Test","Output":"--- SKIP:`, "did not see SKIP output")
5734 tg.grepStdout(`"Action":"skip","Package":"skipper","Test":"Test"`, "did not see skip result for Test")
5736 tg.run("test", "-json", "-short", "-v", "errors")
5737 tg.grepStdout(`"Action":"output","Package":"errors","Output":".*\(cached\)`, "did not see no cached output")
5739 tg.run("test", "-json", "-bench=NONE", "-short", "-v", "errors")
5740 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5741 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5743 tg.run("test", "-o", tg.path("errors.test.exe"), "-c", "errors")
5744 tg.run("tool", "test2json", "-p", "errors", tg.path("errors.test.exe"), "-test.v", "-test.short")
5745 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5746 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5747 tg.grepStdout(`\{"Action":"pass","Package":"errors"\}`, "did not see final pass")
5750 func TestFailFast(t *testing.T) {
5760 {"TestFailingA", true, 1},
5761 {"TestFailing[AB]", true, 1},
5762 {"TestFailing[AB]", false, 2},
5763 // mix with non-failing tests:
5764 {"TestA|TestFailing[AB]", true, 1},
5765 {"TestA|TestFailing[AB]", false, 2},
5766 // mix with parallel tests:
5767 {"TestFailingB|TestParallelFailingA", true, 2},
5768 {"TestFailingB|TestParallelFailingA", false, 2},
5769 {"TestFailingB|TestParallelFailing[AB]", true, 3},
5770 {"TestFailingB|TestParallelFailing[AB]", false, 3},
5771 // mix with parallel sub-tests
5772 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", true, 3},
5773 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", false, 5},
5774 {"TestParallelFailingSubtestsA", true, 1},
5776 {"TestParallelFailing[AB]", false, 2},
5777 // non-parallel subtests:
5778 {"TestFailingSubtestsA", true, 1},
5779 {"TestFailingSubtestsA", false, 2},
5781 {"TestFatal[CD]", true, 1},
5782 {"TestFatal[CD]", false, 2},
5785 for _, tt := range tests {
5786 t.Run(tt.run, func(t *testing.T) {
5787 tg.runFail("test", "./testdata/src/failfast_test.go", "-run="+tt.run, "-failfast="+strconv.FormatBool(tt.failfast))
5789 nfail := strings.Count(tg.getStdout(), "FAIL - ")
5791 if nfail != tt.nfail {
5792 t.Errorf("go test -run=%s -failfast=%t printed %d FAILs, want %d", tt.run, tt.failfast, nfail, tt.nfail)
5799 func TestImportPath(t *testing.T) {
5805 tg.tempFile("src/a/a.go", `
5819 tg.tempFile("src/a/a_test.go", `
5827 func TestV(t *testing.T) {
5833 tg.tempFile("src/a/p-1.0/p.go", `
5841 tg.setenv("GOPATH", tg.path("."))
5842 tg.run("build", "-o", tg.path("a.exe"), "a")
5846 func TestBadCommandLines(t *testing.T) {
5850 tg.tempFile("src/x/x.go", "package x\n")
5851 tg.setenv("GOPATH", tg.path("."))
5853 tg.run("build", "x")
5855 tg.tempFile("src/x/@y.go", "package x\n")
5856 tg.runFail("build", "x")
5857 tg.grepStderr("invalid input file name \"@y.go\"", "did not reject @y.go")
5858 tg.must(os.Remove(tg.path("src/x/@y.go")))
5860 tg.tempFile("src/x/-y.go", "package x\n")
5861 tg.runFail("build", "x")
5862 tg.grepStderr("invalid input file name \"-y.go\"", "did not reject -y.go")
5863 tg.must(os.Remove(tg.path("src/x/-y.go")))
5865 if runtime.Compiler == "gccgo" {
5866 tg.runFail("build", "-gccgoflags=all=@x", "x")
5868 tg.runFail("build", "-gcflags=all=@x", "x")
5870 tg.grepStderr("invalid command-line argument @x in command", "did not reject @x during exec")
5872 tg.tempFile("src/@x/x.go", "package x\n")
5873 tg.setenv("GOPATH", tg.path("."))
5874 tg.runFail("build", "@x")
5875 tg.grepStderr("invalid input directory name \"@x\"|cannot use path@version syntax", "did not reject @x directory")
5877 tg.tempFile("src/@x/y/y.go", "package y\n")
5878 tg.setenv("GOPATH", tg.path("."))
5879 tg.runFail("build", "@x/y")
5880 tg.grepStderr("invalid import path \"@x/y\"|cannot use path@version syntax", "did not reject @x/y import path")
5882 tg.tempFile("src/-x/x.go", "package x\n")
5883 tg.setenv("GOPATH", tg.path("."))
5884 tg.runFail("build", "--", "-x")
5885 tg.grepStderr("invalid input directory name \"-x\"", "did not reject -x directory")
5887 tg.tempFile("src/-x/y/y.go", "package y\n")
5888 tg.setenv("GOPATH", tg.path("."))
5889 tg.runFail("build", "--", "-x/y")
5890 tg.grepStderr("invalid import path \"-x/y\"", "did not reject -x/y import path")
5893 func TestBadCgoDirectives(t *testing.T) {
5901 tg.tempFile("src/x/x.go", "package x\n")
5902 tg.setenv("GOPATH", tg.path("."))
5904 if runtime.Compiler == "gc" {
5905 tg.tempFile("src/x/x.go", `package x
5907 //go:cgo_ldflag "-fplugin=foo.so"
5911 tg.runFail("build", "x")
5912 tg.grepStderr("//go:cgo_ldflag .* only allowed in cgo-generated code", "did not reject //go:cgo_ldflag directive")
5915 tg.must(os.Remove(tg.path("src/x/x.go")))
5916 tg.runFail("build", "x")
5917 tg.grepStderr("no Go files", "did not report missing source code")
5918 tg.tempFile("src/x/_cgo_yy.go", `package x
5920 //go:cgo_ldflag "-fplugin=foo.so"
5924 tg.runFail("build", "x")
5925 tg.grepStderr("no Go files", "did not report missing source code") // _* files are ignored...
5927 if runtime.Compiler == "gc" {
5928 tg.runFail("build", tg.path("src/x/_cgo_yy.go")) // ... but if forced, the comment is rejected
5929 // Actually, today there is a separate issue that _ files named
5930 // on the command line are ignored. Once that is fixed,
5931 // we want to see the cgo_ldflag error.
5932 tg.grepStderr("//go:cgo_ldflag only allowed in cgo-generated code|no Go files", "did not reject //go:cgo_ldflag directive")
5935 tg.must(os.Remove(tg.path("src/x/_cgo_yy.go")))
5937 tg.tempFile("src/x/x.go", "package x\n")
5938 tg.tempFile("src/x/y.go", `package x
5939 // #cgo CFLAGS: -fplugin=foo.so
5942 tg.runFail("build", "x")
5943 tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
5945 tg.tempFile("src/x/y.go", `package x
5946 // #cgo CFLAGS: -Ibar -fplugin=foo.so
5949 tg.runFail("build", "x")
5950 tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
5952 tg.tempFile("src/x/y.go", `package x
5953 // #cgo pkg-config: -foo
5956 tg.runFail("build", "x")
5957 tg.grepStderr("invalid pkg-config package name: -foo", "did not reject pkg-config: -foo")
5959 tg.tempFile("src/x/y.go", `package x
5960 // #cgo pkg-config: @foo
5963 tg.runFail("build", "x")
5964 tg.grepStderr("invalid pkg-config package name: @foo", "did not reject pkg-config: -foo")
5966 tg.tempFile("src/x/y.go", `package x
5967 // #cgo CFLAGS: @foo
5970 tg.runFail("build", "x")
5971 tg.grepStderr("invalid flag in #cgo CFLAGS: @foo", "did not reject @foo flag")
5973 tg.tempFile("src/x/y.go", `package x
5977 tg.runFail("build", "x")
5978 tg.grepStderr("invalid flag in #cgo CFLAGS: -D without argument", "did not reject trailing -I flag")
5980 // Note that -I @foo is allowed because we rewrite it into -I /path/to/src/@foo
5981 // before the check is applied. There's no such rewrite for -D.
5983 tg.tempFile("src/x/y.go", `package x
5984 // #cgo CFLAGS: -D @foo
5987 tg.runFail("build", "x")
5988 tg.grepStderr("invalid flag in #cgo CFLAGS: -D @foo", "did not reject -D @foo flag")
5990 tg.tempFile("src/x/y.go", `package x
5991 // #cgo CFLAGS: -D@foo
5994 tg.runFail("build", "x")
5995 tg.grepStderr("invalid flag in #cgo CFLAGS: -D@foo", "did not reject -D@foo flag")
5997 tg.setenv("CGO_CFLAGS", "-D@foo")
5998 tg.tempFile("src/x/y.go", `package x
6001 tg.run("build", "-n", "x")
6002 tg.grepStderr("-D@foo", "did not find -D@foo in commands")
6005 func TestTwoPkgConfigs(t *testing.T) {
6009 if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
6010 t.Skipf("no shell scripts on %s", runtime.GOOS)
6016 tg.tempFile("src/x/a.go", `package x
6017 // #cgo pkg-config: --static a
6020 tg.tempFile("src/x/b.go", `package x
6021 // #cgo pkg-config: --static a
6024 tg.tempFile("pkg-config.sh", `#!/bin/sh
6025 echo $* >>`+tg.path("pkg-config.out"))
6026 tg.must(os.Chmod(tg.path("pkg-config.sh"), 0755))
6027 tg.setenv("GOPATH", tg.path("."))
6028 tg.setenv("PKG_CONFIG", tg.path("pkg-config.sh"))
6029 tg.run("build", "x")
6030 out, err := ioutil.ReadFile(tg.path("pkg-config.out"))
6032 out = bytes.TrimSpace(out)
6033 want := "--cflags --static --static -- a a\n--libs --static --static -- a a"
6034 if !bytes.Equal(out, []byte(want)) {
6035 t.Errorf("got %q want %q", out, want)
6039 func TestCgoCache(t *testing.T) {
6048 tg.tempFile("src/x/a.go", `package main
6055 func main() { fmt.Println(C.val) }
6057 tg.setenv("GOPATH", tg.path("."))
6058 exe := tg.path("x.exe")
6059 tg.run("build", "-o", exe, "x")
6060 tg.setenv("CGO_LDFLAGS", "-lnosuchlibraryexists")
6061 tg.runFail("build", "-o", exe, "x")
6062 tg.grepStderr(`nosuchlibraryexists`, "did not run linker with changed CGO_LDFLAGS")
6066 func TestFilepathUnderCwdFormat(t *testing.T) {
6069 tg.run("test", "-x", "-cover", "log")
6070 tg.grepStderrNot(`\.log\.cover\.go`, "-x output should contain correctly formatted filepath under cwd")
6074 func TestDontReportRemoveOfEmptyDir(t *testing.T) {
6078 tg.tempFile("src/a/a.go", `package a`)
6079 tg.setenv("GOPATH", tg.path("."))
6080 tg.run("install", "-x", "a")
6081 tg.run("install", "-x", "a")
6082 // The second install should have printed only a WORK= line,
6084 if bytes.Count(tg.stdout.Bytes(), []byte{'\n'})+bytes.Count(tg.stderr.Bytes(), []byte{'\n'}) > 1 {
6085 t.Error("unnecessary output when installing installed package")
6090 func TestLinkerTmpDirIsDeleted(t *testing.T) {
6091 skipIfGccgo(t, "gccgo does not use cmd/link")
6093 t.Skip("skipping because cgo not enabled")
6100 tg.tempFile("a.go", `package main; import "C"; func main() {}`)
6101 tg.run("build", "-ldflags", "-v", "-o", os.DevNull, tg.path("a.go"))
6102 // Find line that has "host link:" in linker output.
6103 stderr := tg.getStderr()
6104 var hostLinkLine string
6105 for _, line := range strings.Split(stderr, "\n") {
6106 if !strings.Contains(line, "host link:") {
6112 if hostLinkLine == "" {
6113 t.Fatal(`fail to find with "host link:" string in linker output`)
6115 // Find parameter, like "/tmp/go-link-408556474/go.o" inside of
6116 // "host link:" line, and extract temp directory /tmp/go-link-408556474
6118 tmpdir := hostLinkLine
6119 i := strings.Index(tmpdir, `go.o"`)
6121 t.Fatalf(`fail to find "go.o" in "host link:" line %q`, hostLinkLine)
6123 tmpdir = tmpdir[:i-1]
6124 i = strings.LastIndex(tmpdir, `"`)
6126 t.Fatalf(`fail to find " in "host link:" line %q`, hostLinkLine)
6128 tmpdir = tmpdir[i+1:]
6129 // Verify that temp directory has been removed.
6130 _, err := os.Stat(tmpdir)
6132 t.Fatalf("temp directory %q has not been removed", tmpdir)
6134 if !os.IsNotExist(err) {
6135 t.Fatalf("Stat(%q) returns unexpected error: %v", tmpdir, err)
6139 func testCDAndGOPATHAreDifferent(tg *testgoData, cd, gopath string) {
6140 skipIfGccgo(tg.t, "gccgo does not support -ldflags -X")
6141 tg.setenv("GOPATH", gopath)
6144 exe := tg.path("dir/a.exe")
6148 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked")
6149 out, err := exec.Command(exe).CombinedOutput()
6153 if string(out) != "linkXworked\n" {
6154 tg.t.Errorf(`incorrect output with GOPATH=%q and CD=%q: expected "linkXworked\n", but have %q`, gopath, cd, string(out))
6158 func TestCDAndGOPATHAreDifferent(t *testing.T) {
6162 gopath := filepath.Join(tg.pwd(), "testdata")
6163 cd := filepath.Join(gopath, "src/my.pkg/main")
6165 testCDAndGOPATHAreDifferent(tg, cd, gopath)
6166 if runtime.GOOS == "windows" {
6167 testCDAndGOPATHAreDifferent(tg, cd, strings.ReplaceAll(gopath, `\`, `/`))
6168 testCDAndGOPATHAreDifferent(tg, cd, strings.ToUpper(gopath))
6169 testCDAndGOPATHAreDifferent(tg, cd, strings.ToLower(gopath))
6174 func TestGoTestWithoutTests(t *testing.T) {
6178 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
6179 tg.run("test", "testnorun")
6180 tg.grepStdout(`testnorun\t\[no test files\]`, "do not want test to run")
6184 func TestGoBuildDashODevNull(t *testing.T) {
6189 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
6190 tg.run("build", "-o", os.DevNull, filepath.Join(tg.pwd(), "testdata", "src", "hello", "hello.go"))
6191 tg.mustNotExist("hello")
6192 tg.mustNotExist("hello.exe")
6196 func TestCoverpkgTestOnly(t *testing.T) {
6197 skipIfGccgo(t, "gccgo has no cover tool")
6202 tg.tempFile("src/a/a.go", `package a
6206 tg.tempFile("src/atest/a_test.go", `
6208 import ( "a"; "testing" )
6209 func TestF(t *testing.T) { a.F(2) }
6211 tg.setenv("GOPATH", tg.path("."))
6212 tg.run("test", "-coverpkg=a", "atest")
6213 tg.grepStderrNot("no packages being tested depend on matches", "bad match message")
6214 tg.grepStdout("coverage: 100", "no coverage")