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")
59 case "android", "js", "nacl":
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 buid 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",
921 filepath.Join("pkg", runtime.GOOS+"_"+runtime.GOARCH),
922 filepath.Join("pkg/tool", runtime.GOOS+"_"+runtime.GOARCH),
925 srcdir := filepath.Join(testGOROOT, copydir)
926 tg.tempDir(filepath.Join("goroot", copydir))
927 err := filepath.Walk(srcdir,
928 func(path string, info os.FileInfo, err error) error {
935 srcrel, err := filepath.Rel(srcdir, path)
939 dest := filepath.Join("goroot", copydir, srcrel)
940 data, err := ioutil.ReadFile(path)
944 tg.tempFile(dest, string(data))
945 if err := os.Chmod(tg.path(dest), info.Mode()); err != nil {
954 tg.setenv("GOROOT", tg.path("goroot"))
956 addVar := func(name string, idx int) (restore func()) {
957 data, err := ioutil.ReadFile(name)
962 data = append(data, fmt.Sprintf("var DummyUnusedVar%d bool\n", idx)...)
963 if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil {
968 if err := ioutil.WriteFile(name, old, 0666); err != nil {
974 // Every main package depends on the "runtime".
975 tg.tempFile("d1/src/p1/p1.go", `package main; func main(){}`)
976 tg.setenv("GOPATH", tg.path("d1"))
977 // Pass -i flag to rebuild everything outdated.
978 tg.run("install", "-i", "p1")
979 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, before any changes")
981 // Changing mtime of runtime/internal/sys/sys.go
982 // should have no effect: only the content matters.
983 // In fact this should be true even outside a release branch.
984 sys := tg.path("goroot/src/runtime/internal/sys/sys.go")
986 restore := addVar(sys, 0)
988 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after updating mtime of runtime/internal/sys/sys.go")
990 // But changing content of any file should have an effect.
991 // Previously zversion.go was the only one that mattered;
992 // now they all matter, so keep using sys.go.
993 restore = addVar(sys, 1)
995 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go")
997 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after changing back to old release")
999 tg.wantStale("p1", "stale dependency: runtime", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go again")
1000 tg.run("install", "-i", "p1")
1001 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with new release")
1003 // Restore to "old" release.
1005 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after restoring sys.go")
1006 tg.run("install", "-i", "p1")
1007 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release")
1010 func testLocalRun(tg *testgoData, exepath, local, match string) {
1012 out, err := exec.Command(exepath).Output()
1014 tg.t.Fatalf("error running %v: %v", exepath, err)
1016 if !regexp.MustCompile(match).Match(out) {
1017 tg.t.Log(string(out))
1018 tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local)
1022 func testLocalEasy(tg *testgoData, local string) {
1024 exepath := "./easy" + exeSuffix
1025 tg.creatingTemp(exepath)
1026 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go"))
1027 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1030 func testLocalEasySub(tg *testgoData, local string) {
1032 exepath := "./easysub" + exeSuffix
1033 tg.creatingTemp(exepath)
1034 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go"))
1035 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1038 func testLocalHard(tg *testgoData, local string) {
1040 exepath := "./hard" + exeSuffix
1041 tg.creatingTemp(exepath)
1042 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go"))
1043 testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`)
1046 func testLocalInstall(tg *testgoData, local string) {
1048 tg.runFail("install", filepath.Join("testdata", local, "easy.go"))
1051 func TestLocalImportsEasy(t *testing.T) {
1054 testLocalEasy(tg, "local")
1057 func TestLocalImportsEasySub(t *testing.T) {
1060 testLocalEasySub(tg, "local")
1063 func TestLocalImportsHard(t *testing.T) {
1066 testLocalHard(tg, "local")
1069 func TestLocalImportsGoInstallShouldFail(t *testing.T) {
1072 testLocalInstall(tg, "local")
1075 const badDirName = `#$%:, &()*;<=>?\^{}`
1077 func copyBad(tg *testgoData) {
1079 if runtime.GOOS == "windows" {
1080 tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName)
1083 tg.must(filepath.Walk("testdata/local",
1084 func(path string, info os.FileInfo, err error) error {
1092 data, err = ioutil.ReadFile(path)
1096 newpath := strings.Replace(path, "local", badDirName, 1)
1097 tg.tempFile(newpath, string(data))
1103 func TestBadImportsEasy(t *testing.T) {
1106 // TODO: tg.parallel()
1108 testLocalEasy(tg, badDirName)
1111 func TestBadImportsEasySub(t *testing.T) {
1115 testLocalEasySub(tg, badDirName)
1118 func TestBadImportsHard(t *testing.T) {
1122 testLocalHard(tg, badDirName)
1125 func TestBadImportsGoInstallShouldFail(t *testing.T) {
1129 testLocalInstall(tg, badDirName)
1132 func TestInternalPackagesInGOROOTAreRespected(t *testing.T) {
1133 skipIfGccgo(t, "gccgo does not have GOROOT")
1136 tg.runFail("build", "-v", "./testdata/testinternal")
1137 tg.grepBoth(`testinternal(\/|\\)p\.go\:3\:8\: use of internal package net/http/internal not allowed`, "wrong error message for testdata/testinternal")
1140 func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) {
1143 tg.runFail("build", "-v", "./testdata/testinternal2")
1144 tg.grepBoth(`testinternal2(\/|\\)p\.go\:3\:8\: use of internal package .*internal/w not allowed`, "wrote error message for testdata/testinternal2")
1147 func TestRunInternal(t *testing.T) {
1150 dir := filepath.Join(tg.pwd(), "testdata")
1151 tg.setenv("GOPATH", dir)
1152 tg.run("run", filepath.Join(dir, "src/run/good.go"))
1153 tg.runFail("run", filepath.Join(dir, "src/run/bad.go"))
1154 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")
1157 func TestRunPkg(t *testing.T) {
1160 dir := filepath.Join(tg.pwd(), "testdata")
1161 tg.setenv("GOPATH", dir)
1162 tg.run("run", "hello")
1163 tg.grepStderr("hello, world", "did not find hello, world")
1164 tg.cd(filepath.Join(dir, "src/hello"))
1166 tg.grepStderr("hello, world", "did not find hello, world")
1169 func testMove(t *testing.T, vcs, url, base, config string) {
1170 testenv.MustHaveExternalNetwork(t)
1176 tg.must(os.Mkdir(tg.path(".hg"), 0700))
1177 tg.must(ioutil.WriteFile(filepath.Join(tg.path(".hg"), "hgrc"), nil, 0600))
1178 tg.setenv("GOPATH", tg.path("."))
1179 tg.run("get", "-d", url)
1180 tg.run("get", "-d", "-u", url)
1183 // SVN doesn't believe in text files so we can't just edit the config.
1184 // Check out a different repo into the wrong place.
1185 tg.must(robustio.RemoveAll(tg.path("src/code.google.com/p/rsc-svn")))
1186 tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk")
1187 tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn")))
1189 path := tg.path(filepath.Join("src", config))
1190 data, err := ioutil.ReadFile(path)
1192 data = bytes.ReplaceAll(data, []byte(base), []byte(base+"XXX"))
1193 tg.must(ioutil.WriteFile(path, data, 0644))
1196 // git will ask for a username and password when we
1197 // run go get -d -f -u. An empty username and
1198 // password will work. Prevent asking by setting
1200 tg.creatingTemp("sink" + exeSuffix)
1201 tg.tempFile("src/sink/sink.go", `package main; func main() {}`)
1202 tg.run("build", "-o", "sink"+exeSuffix, "sink")
1203 tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix))
1205 tg.runFail("get", "-d", "-u", url)
1206 tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason")
1207 tg.runFail("get", "-d", "-f", "-u", url)
1208 tg.grepStderr("validating server certificate|[nN]ot [fF]ound", "go get -d -f -u "+url+" failed for wrong reason")
1211 func TestInternalPackageErrorsAreHandled(t *testing.T) {
1214 tg.run("list", "./testdata/testinternal3")
1217 func TestInternalCache(t *testing.T) {
1220 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4"))
1221 tg.runFail("build", "p")
1222 tg.grepStderr("internal", "did not fail to build p")
1225 func TestMoveGit(t *testing.T) {
1226 testenv.MustHaveExecPath(t, "git")
1227 testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config")
1230 func TestMoveHG(t *testing.T) {
1231 testenv.MustHaveExecPath(t, "hg")
1232 testMove(t, "hg", "vcs-test.golang.org/go/custom-hg-hello", "custom-hg-hello", "vcs-test.golang.org/go/custom-hg-hello/.hg/hgrc")
1235 // TODO(rsc): Set up a test case on SourceForge (?) for svn.
1236 // func testMoveSVN(t *testing.T) {
1237 // testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-")
1240 func TestImportCommandMatch(t *testing.T) {
1243 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1244 tg.run("build", "./testdata/importcom/works.go")
1247 func TestImportCommentMismatch(t *testing.T) {
1250 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1251 tg.runFail("build", "./testdata/importcom/wrongplace.go")
1252 tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import")
1255 func TestImportCommentSyntaxError(t *testing.T) {
1258 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1259 tg.runFail("build", "./testdata/importcom/bad.go")
1260 tg.grepStderr("cannot parse import comment", "go build did not mention syntax error")
1263 func TestImportCommentConflict(t *testing.T) {
1266 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1267 tg.runFail("build", "./testdata/importcom/conflict.go")
1268 tg.grepStderr("found import comments", "go build did not mention comment conflict")
1271 func TestImportCycle(t *testing.T) {
1275 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcycle"))
1276 tg.runFail("build", "selfimport")
1278 count := tg.grepCountBoth("import cycle not allowed")
1280 t.Fatal("go build did not mention cyclical import")
1283 t.Fatal("go build mentioned import cycle more than once")
1286 // Don't hang forever.
1287 tg.run("list", "-e", "-json", "selfimport")
1290 // cmd/go: custom import path checking should not apply to Go packages without import comment.
1291 func TestIssue10952(t *testing.T) {
1292 testenv.MustHaveExternalNetwork(t)
1293 testenv.MustHaveExecPath(t, "git")
1299 tg.setenv("GOPATH", tg.path("."))
1300 const importPath = "github.com/zombiezen/go-get-issue-10952"
1301 tg.run("get", "-d", "-u", importPath)
1302 repoDir := tg.path("src/" + importPath)
1303 tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git")
1304 tg.run("get", "-d", "-u", importPath)
1307 func TestIssue16471(t *testing.T) {
1308 testenv.MustHaveExternalNetwork(t)
1309 testenv.MustHaveExecPath(t, "git")
1315 tg.setenv("GOPATH", tg.path("."))
1316 tg.must(os.MkdirAll(tg.path("src/rsc.io/go-get-issue-10952"), 0755))
1317 tg.runGit(tg.path("src/rsc.io"), "clone", "https://github.com/zombiezen/go-get-issue-10952")
1318 tg.runFail("get", "-u", "rsc.io/go-get-issue-10952")
1319 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")
1322 // Test git clone URL that uses SCP-like syntax and custom import path checking.
1323 func TestIssue11457(t *testing.T) {
1324 testenv.MustHaveExternalNetwork(t)
1325 testenv.MustHaveExecPath(t, "git")
1331 tg.setenv("GOPATH", tg.path("."))
1332 const importPath = "rsc.io/go-get-issue-11457"
1333 tg.run("get", "-d", "-u", importPath)
1334 repoDir := tg.path("src/" + importPath)
1335 tg.runGit(repoDir, "remote", "set-url", "origin", "git@github.com:rsc/go-get-issue-11457")
1337 // At this time, custom import path checking compares remotes verbatim (rather than
1338 // just the host and path, skipping scheme and user), so we expect go get -u to fail.
1339 // However, the goal of this test is to verify that gitRemoteRepo correctly parsed
1340 // the SCP-like syntax, and we expect it to appear in the error message.
1341 tg.runFail("get", "-d", "-u", importPath)
1342 want := " is checked out from ssh://git@github.com/rsc/go-get-issue-11457"
1343 if !strings.HasSuffix(strings.TrimSpace(tg.getStderr()), want) {
1344 t.Error("expected clone URL to appear in stderr")
1348 func TestGetGitDefaultBranch(t *testing.T) {
1349 testenv.MustHaveExternalNetwork(t)
1350 testenv.MustHaveExecPath(t, "git")
1356 tg.setenv("GOPATH", tg.path("."))
1358 // This repo has two branches, master and another-branch.
1359 // The another-branch is the default that you get from 'git clone'.
1360 // The go get command variants should not override this.
1361 const importPath = "github.com/rsc/go-get-default-branch"
1363 tg.run("get", "-d", importPath)
1364 repoDir := tg.path("src/" + importPath)
1365 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1366 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1368 tg.run("get", "-d", "-u", importPath)
1369 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1370 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1373 // Security issue. Don't disable. See golang.org/issue/22125.
1374 func TestAccidentalGitCheckout(t *testing.T) {
1375 testenv.MustHaveExternalNetwork(t)
1376 testenv.MustHaveExecPath(t, "git")
1383 tg.setenv("GOPATH", tg.path("."))
1385 tg.runFail("get", "-u", "vcs-test.golang.org/go/test1-svn-git")
1386 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1388 if _, err := os.Stat(tg.path("SrC")); err == nil {
1389 // This case only triggers on a case-insensitive file system.
1390 tg.runFail("get", "-u", "vcs-test.golang.org/go/test2-svn-git/test2main")
1391 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1395 func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) {
1398 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1399 tg.runFail("test", "syntaxerror")
1400 tg.grepStderr("x_test.go:", "did not diagnose error")
1401 tg.grepStdout("FAIL", "go test did not say FAIL")
1404 func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) {
1407 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1408 tg.runFail("list", "...")
1409 tg.grepBoth("badpkg", "go list ... failure does not mention badpkg")
1410 tg.run("list", "m...")
1413 func TestRelativeImportsGoTest(t *testing.T) {
1416 tg.run("test", "./testdata/testimport")
1419 func TestRelativeImportsGoTestDashI(t *testing.T) {
1423 // don't let test -i overwrite runtime
1424 tg.wantNotStale("runtime", "", "must be non-stale before test -i")
1426 tg.run("test", "-i", "./testdata/testimport")
1429 func TestRelativeImportsInCommandLinePackage(t *testing.T) {
1432 // TODO: tg.parallel()
1433 files, err := filepath.Glob("./testdata/testimport/*.go")
1435 tg.run(append([]string{"test"}, files...)...)
1438 func TestNonCanonicalImportPaths(t *testing.T) {
1442 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1443 tg.runFail("build", "canonical/d")
1444 tg.grepStderr("package canonical/d", "did not report canonical/d")
1445 tg.grepStderr("imports canonical/b", "did not report canonical/b")
1446 tg.grepStderr("imports canonical/a/: non-canonical", "did not report canonical/a/")
1449 func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) {
1452 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1"))
1453 tg.runFail("get", "-u", "foo")
1455 // TODO(iant): We should not have to use strconv.Quote here.
1456 // The code in vcs.go should be changed so that it is not required.
1457 quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo"))
1458 quoted = quoted[1 : len(quoted)-1]
1460 tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo")
1463 func TestInstallFailsWithNoBuildableFiles(t *testing.T) {
1466 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1467 tg.setenv("CGO_ENABLED", "0")
1468 tg.runFail("install", "cgotest")
1469 tg.grepStderr("build constraints exclude all Go files", "go install cgotest did not report 'build constraints exclude all Go files'")
1473 func TestMSanAndRaceRequireCgo(t *testing.T) {
1474 if !canMSan && !canRace {
1475 t.Skip("skipping because both msan and the race detector are not supported")
1480 tg.tempFile("triv.go", `package main; func main() {}`)
1481 tg.setenv("CGO_ENABLED", "0")
1483 tg.runFail("install", "-race", "triv.go")
1484 tg.grepStderr("-race requires cgo", "did not correctly report that -race requires cgo")
1485 tg.grepStderrNot("-msan", "reported that -msan instead of -race requires cgo")
1488 tg.runFail("install", "-msan", "triv.go")
1489 tg.grepStderr("-msan requires cgo", "did not correctly report that -msan requires cgo")
1490 tg.grepStderrNot("-race", "reported that -race instead of -msan requires cgo")
1494 func TestRelativeGOBINFail(t *testing.T) {
1497 tg.tempFile("triv.go", `package main; func main() {}`)
1498 tg.setenv("GOBIN", ".")
1500 tg.runFail("install")
1501 tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path")
1504 // Test that without $GOBIN set, binaries get installed
1505 // into the GOPATH bin directory.
1506 func TestInstallIntoGOPATH(t *testing.T) {
1509 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1510 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1511 tg.run("install", "go-cmd-test")
1512 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1516 func TestBuildOutputToDevNull(t *testing.T) {
1519 fi1, err1 := os.Lstat(os.DevNull)
1520 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1521 tg.run("build", "-o", os.DevNull, "go-cmd-test")
1522 fi2, err2 := os.Lstat(os.DevNull)
1525 t.Errorf("second stat of /dev/null failed: %v", err2)
1526 } else if !os.SameFile(fi1, fi2) {
1527 t.Errorf("/dev/null changed: now %v was %v", fi1, fi2)
1533 func TestTestOutputToDevNull(t *testing.T) {
1536 fi1, err1 := os.Lstat(os.DevNull)
1538 tg.setenv("GOPATH", tg.path("."))
1539 tg.tempFile("src/p/p.go", "package p\n")
1540 tg.tempFile("src/p/p_test.go", "package p\nimport \"testing\"\nfunc TestX(t *testing.T) {}\n")
1541 tg.run("test", "-o", os.DevNull, "-c", "p")
1542 tg.mustNotExist("p.test")
1543 fi2, err2 := os.Lstat(os.DevNull)
1546 t.Errorf("second stat of /dev/null failed: %v", err2)
1547 } else if !os.SameFile(fi1, fi2) {
1548 t.Errorf("/dev/null changed: now %v was %v", fi1, fi2)
1553 func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) {
1558 gobin := filepath.Join(tg.pwd(), "testdata", "bin")
1559 tg.creatingTemp(gobin)
1560 tg.setenv("GOBIN", gobin)
1561 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1562 tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now()))
1564 tg.run("test", "main_test")
1565 tg.run("install", "main_test")
1566 tg.wantNotStale("main_test", "", "after go install, main listed as stale")
1567 tg.run("test", "main_test")
1570 func TestPackageMainTestCompilerFlags(t *testing.T) {
1575 tg.setenv("GOPATH", tg.path("."))
1576 tg.tempFile("src/p1/p1.go", "package main\n")
1577 tg.tempFile("src/p1/p1_test.go", "package main\nimport \"testing\"\nfunc Test(t *testing.T){}\n")
1578 tg.run("test", "-c", "-n", "p1")
1579 tg.grepBothNot(`([\\/]compile|gccgo).* (-p main|-fgo-pkgpath=main).*p1\.go`, "should not have run compile -p main p1.go")
1580 tg.grepStderr(`([\\/]compile|gccgo).* (-p p1|-fgo-pkgpath=p1).*p1\.go`, "should have run compile -p p1 p1.go")
1584 func TestPackageNotStaleWithTrailingSlash(t *testing.T) {
1585 skipIfGccgo(t, "gccgo does not have GOROOT")
1589 // Make sure the packages below are not stale.
1590 tg.wantNotStale("runtime", "", "must be non-stale before test runs")
1591 tg.wantNotStale("os", "", "must be non-stale before test runs")
1592 tg.wantNotStale("io", "", "must be non-stale before test runs")
1594 goroot := runtime.GOROOT()
1595 tg.setenv("GOROOT", goroot+"/")
1597 tg.wantNotStale("runtime", "", "with trailing slash in GOROOT, runtime listed as stale")
1598 tg.wantNotStale("os", "", "with trailing slash in GOROOT, os listed as stale")
1599 tg.wantNotStale("io", "", "with trailing slash in GOROOT, io listed as stale")
1602 // With $GOBIN set, binaries get installed to $GOBIN.
1603 func TestInstallIntoGOBIN(t *testing.T) {
1606 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1607 tg.creatingTemp(gobin)
1608 tg.setenv("GOBIN", gobin)
1609 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1610 tg.run("install", "go-cmd-test")
1611 tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test")
1615 func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) {
1618 pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test")
1619 tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix))
1620 tg.setenv("GOBIN", pkg)
1621 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1624 tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory")
1627 // Without $GOBIN set, installing a program outside $GOPATH should fail
1628 // (there is nowhere to install it).
1629 func TestInstallWithoutDestinationFails(t *testing.T) {
1632 tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go")
1633 tg.grepStderr("no install location for .go files listed on command line", "wrong error")
1636 // With $GOBIN set, should install there.
1637 func TestInstallToGOBINCommandLinePackage(t *testing.T) {
1640 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1641 tg.creatingTemp(gobin)
1642 tg.setenv("GOBIN", gobin)
1643 tg.run("install", "testdata/src/go-cmd-test/helloworld.go")
1644 tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld")
1647 func TestGoGetNonPkg(t *testing.T) {
1648 testenv.MustHaveExternalNetwork(t)
1649 testenv.MustHaveExecPath(t, "git")
1654 tg.setenv("GOPATH", tg.path("."))
1655 tg.setenv("GOBIN", tg.path("gobin"))
1656 tg.runFail("get", "-d", "golang.org/x/tools")
1657 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1658 tg.runFail("get", "-d", "-u", "golang.org/x/tools")
1659 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1660 tg.runFail("get", "-d", "golang.org/x/tools")
1661 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1664 func TestGoGetTestOnlyPkg(t *testing.T) {
1665 testenv.MustHaveExternalNetwork(t)
1666 testenv.MustHaveExecPath(t, "git")
1670 tg.tempDir("gopath")
1671 tg.setenv("GOPATH", tg.path("gopath"))
1672 tg.run("get", "golang.org/x/tour/content...")
1673 tg.run("get", "-t", "golang.org/x/tour/content...")
1676 func TestInstalls(t *testing.T) {
1677 if testing.Short() {
1678 t.Skip("don't install into GOROOT in short mode")
1685 tg.setenv("GOPATH", tg.path("."))
1686 goroot := runtime.GOROOT()
1687 tg.setenv("GOROOT", goroot)
1689 // cmd/fix installs into tool
1690 tg.run("env", "GOOS")
1691 goos := strings.TrimSpace(tg.getStdout())
1692 tg.setenv("GOOS", goos)
1693 tg.run("env", "GOARCH")
1694 goarch := strings.TrimSpace(tg.getStdout())
1695 tg.setenv("GOARCH", goarch)
1696 fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix
1697 tg.must(robustio.RemoveAll(fixbin))
1698 tg.run("install", "cmd/fix")
1699 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool")
1700 tg.must(os.Remove(fixbin))
1701 tg.setenv("GOBIN", tg.path("gobin"))
1702 tg.run("install", "cmd/fix")
1703 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set")
1704 tg.unsetenv("GOBIN")
1706 // gopath program installs into GOBIN
1707 tg.tempFile("src/progname/p.go", `package main; func main() {}`)
1708 tg.setenv("GOBIN", tg.path("gobin"))
1709 tg.run("install", "progname")
1710 tg.unsetenv("GOBIN")
1711 tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname")
1713 // gopath program installs into GOPATH/bin
1714 tg.run("install", "progname")
1715 tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname")
1718 func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) {
1721 tg.setenv("GOPATH", ".")
1722 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1723 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1726 func TestRejectRelativePathsInGOPATH(t *testing.T) {
1729 sep := string(filepath.ListSeparator)
1730 tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".")
1731 tg.runFail("build", "go-cmd-test")
1732 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1735 func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) {
1738 tg.setenv("GOPATH", "testdata")
1739 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1740 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1744 func TestRejectBlankPathsInGOPATH(t *testing.T) {
1747 sep := string(filepath.ListSeparator)
1748 tg.setenv("GOPATH", " "+sep+filepath.Join(tg.pwd(), "testdata"))
1749 tg.runFail("build", "go-cmd-test")
1750 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1754 func TestIgnoreEmptyPathsInGOPATH(t *testing.T) {
1757 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1758 sep := string(filepath.ListSeparator)
1759 tg.setenv("GOPATH", ""+sep+filepath.Join(tg.pwd(), "testdata"))
1760 tg.run("install", "go-cmd-test")
1761 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1765 func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
1770 tg.run("test", "errors", "errors", "errors", "errors", "errors")
1771 if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") {
1772 t.Error("go test errors errors errors errors errors tested the same package multiple times")
1776 func TestGoListHasAConsistentOrder(t *testing.T) {
1781 tg.run("list", "std")
1782 first := tg.getStdout()
1783 tg.run("list", "std")
1784 if first != tg.getStdout() {
1785 t.Error("go list std ordering is inconsistent")
1789 func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
1794 tg.run("list", "std")
1795 tg.grepStdoutNot("cmd/", "go list std shows commands")
1798 func TestGoListCmdOnlyShowsCommands(t *testing.T) {
1799 skipIfGccgo(t, "gccgo does not have GOROOT")
1804 tg.run("list", "cmd")
1805 out := strings.TrimSpace(tg.getStdout())
1806 for _, line := range strings.Split(out, "\n") {
1807 if !strings.Contains(line, "cmd/") {
1808 t.Error("go list cmd shows non-commands")
1814 func TestGoListDedupsPackages(t *testing.T) {
1817 // TODO: tg.parallel()
1818 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1819 tg.run("list", "xtestonly", "./testdata/src/xtestonly/...")
1820 got := strings.TrimSpace(tg.getStdout())
1821 const want = "xtestonly"
1823 t.Errorf("got %q; want %q", got, want)
1827 func TestGoListDeps(t *testing.T) {
1831 tg.tempDir("src/p1/p2/p3/p4")
1832 tg.setenv("GOPATH", tg.path("."))
1833 tg.tempFile("src/p1/p.go", "package p1\nimport _ \"p1/p2\"\n")
1834 tg.tempFile("src/p1/p2/p.go", "package p2\nimport _ \"p1/p2/p3\"\n")
1835 tg.tempFile("src/p1/p2/p3/p.go", "package p3\nimport _ \"p1/p2/p3/p4\"\n")
1836 tg.tempFile("src/p1/p2/p3/p4/p.go", "package p4\n")
1837 tg.run("list", "-f", "{{.Deps}}", "p1")
1838 tg.grepStdout("p1/p2/p3/p4", "Deps(p1) does not mention p4")
1840 tg.run("list", "-deps", "p1")
1841 tg.grepStdout("p1/p2/p3/p4", "-deps p1 does not mention p4")
1843 if runtime.Compiler != "gccgo" {
1844 // Check the list is in dependency order.
1845 tg.run("list", "-deps", "math")
1846 want := "internal/cpu\nunsafe\nmath/bits\nmath\n"
1847 out := tg.stdout.String()
1848 if !strings.Contains(out, "internal/cpu") {
1849 // Some systems don't use internal/cpu.
1850 want = "unsafe\nmath/bits\nmath\n"
1852 if tg.stdout.String() != want {
1853 t.Fatalf("list -deps math: wrong order\nhave %q\nwant %q", tg.stdout.String(), want)
1858 func TestGoListTest(t *testing.T) {
1859 skipIfGccgo(t, "gccgo does not have standard packages")
1864 tg.setenv("GOCACHE", tg.tempdir)
1866 tg.run("list", "-test", "-deps", "sort")
1867 tg.grepStdout(`^sort.test$`, "missing test main")
1868 tg.grepStdout(`^sort$`, "missing real sort")
1869 tg.grepStdout(`^sort \[sort.test\]$`, "missing test copy of sort")
1870 tg.grepStdout(`^testing \[sort.test\]$`, "missing test copy of testing")
1871 tg.grepStdoutNot(`^testing$`, "unexpected real copy of testing")
1873 tg.run("list", "-test", "sort")
1874 tg.grepStdout(`^sort.test$`, "missing test main")
1875 tg.grepStdout(`^sort$`, "missing real sort")
1876 tg.grepStdout(`^sort \[sort.test\]$`, "unexpected test copy of sort")
1877 tg.grepStdoutNot(`^testing \[sort.test\]$`, "unexpected test copy of testing")
1878 tg.grepStdoutNot(`^testing$`, "unexpected real copy of testing")
1880 tg.run("list", "-test", "cmd/dist", "cmd/doc")
1881 tg.grepStdout(`^cmd/dist$`, "missing cmd/dist")
1882 tg.grepStdout(`^cmd/doc$`, "missing cmd/doc")
1883 tg.grepStdout(`^cmd/doc\.test$`, "missing cmd/doc test")
1884 tg.grepStdoutNot(`^cmd/dist\.test$`, "unexpected cmd/dist test")
1885 tg.grepStdoutNot(`^testing`, "unexpected testing")
1887 tg.run("list", "-test", "runtime/cgo")
1888 tg.grepStdout(`^runtime/cgo$`, "missing runtime/cgo")
1890 tg.run("list", "-deps", "-f", "{{if .DepOnly}}{{.ImportPath}}{{end}}", "sort")
1891 tg.grepStdout(`^internal/reflectlite$`, "missing internal/reflectlite")
1892 tg.grepStdoutNot(`^sort`, "unexpected sort")
1895 func TestGoListCompiledCgo(t *testing.T) {
1901 tg.setenv("GOCACHE", tg.tempdir)
1903 tg.run("list", "-f", `{{join .CgoFiles "\n"}}`, "net")
1904 if tg.stdout.String() == "" {
1905 t.Skip("net does not use cgo")
1907 if strings.Contains(tg.stdout.String(), tg.tempdir) {
1908 t.Fatalf(".CgoFiles unexpectedly mentioned cache %s", tg.tempdir)
1910 tg.run("list", "-compiled", "-f", `{{.Dir}}{{"\n"}}{{join .CompiledGoFiles "\n"}}`, "net")
1911 if !strings.Contains(tg.stdout.String(), tg.tempdir) {
1912 t.Fatalf(".CompiledGoFiles with -compiled did not mention cache %s", tg.tempdir)
1915 for _, file := range strings.Split(tg.stdout.String(), "\n") {
1923 if !strings.Contains(file, "/") && !strings.Contains(file, `\`) {
1924 file = filepath.Join(dir, file)
1926 if _, err := os.Stat(file); err != nil {
1927 t.Fatalf("cannot find .CompiledGoFiles result %s: %v", file, err)
1932 func TestGoListExport(t *testing.T) {
1933 skipIfGccgo(t, "gccgo does not have standard packages")
1938 tg.setenv("GOCACHE", tg.tempdir)
1940 tg.run("list", "-f", "{{.Export}}", "strings")
1941 if tg.stdout.String() != "" {
1942 t.Fatalf(".Export without -export unexpectedly set")
1944 tg.run("list", "-export", "-f", "{{.Export}}", "strings")
1945 file := strings.TrimSpace(tg.stdout.String())
1947 t.Fatalf(".Export with -export was empty")
1949 if _, err := os.Stat(file); err != nil {
1950 t.Fatalf("cannot find .Export result %s: %v", file, err)
1954 // Issue 4096. Validate the output of unsuccessful go install foo/quxx.
1955 func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) {
1959 tg.runFail("install", "foo/quxx")
1960 if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 {
1961 t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`)
1965 func TestGOROOTSearchFailureReporting(t *testing.T) {
1969 tg.runFail("install", "foo/quxx")
1970 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 {
1971 t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`)
1975 func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) {
1979 sep := string(filepath.ListSeparator)
1980 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1981 tg.runFail("install", "foo/quxx")
1982 if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 {
1983 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`)
1987 // Test (from $GOPATH) annotation is reported for the first GOPATH entry,
1988 func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) {
1992 sep := string(filepath.ListSeparator)
1993 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1994 tg.runFail("install", "foo/quxx")
1995 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 {
1996 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`)
2000 // but not on the second.
2001 func TestMentionGOPATHNotOnSecondEntry(t *testing.T) {
2005 sep := string(filepath.ListSeparator)
2006 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
2007 tg.runFail("install", "foo/quxx")
2008 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 {
2009 t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`)
2013 func homeEnvName() string {
2014 switch runtime.GOOS {
2016 return "USERPROFILE"
2024 func tempEnvName() string {
2025 switch runtime.GOOS {
2029 return "TMPDIR" // actually plan 9 doesn't have one at all but this is fine
2035 func TestDefaultGOPATH(t *testing.T) {
2039 tg.tempDir("home/go")
2040 tg.setenv(homeEnvName(), tg.path("home"))
2042 tg.run("env", "GOPATH")
2043 tg.grepStdout(regexp.QuoteMeta(tg.path("home/go")), "want GOPATH=$HOME/go")
2045 tg.setenv("GOROOT", tg.path("home/go"))
2046 tg.run("env", "GOPATH")
2047 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go")
2049 tg.setenv("GOROOT", tg.path("home/go")+"/")
2050 tg.run("env", "GOPATH")
2051 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go/")
2054 func TestDefaultGOPATHGet(t *testing.T) {
2055 testenv.MustHaveExternalNetwork(t)
2056 testenv.MustHaveExecPath(t, "git")
2060 tg.setenv("GOPATH", "")
2062 tg.setenv(homeEnvName(), tg.path("home"))
2064 // warn for creating directory
2065 tg.run("get", "-v", "github.com/golang/example/hello")
2066 tg.grepStderr("created GOPATH="+regexp.QuoteMeta(tg.path("home/go"))+"; see 'go help gopath'", "did not create GOPATH")
2068 // no warning if directory already exists
2069 tg.must(robustio.RemoveAll(tg.path("home/go")))
2070 tg.tempDir("home/go")
2071 tg.run("get", "github.com/golang/example/hello")
2072 tg.grepStderrNot(".", "expected no output on standard error")
2074 // error if $HOME/go is a file
2075 tg.must(robustio.RemoveAll(tg.path("home/go")))
2076 tg.tempFile("home/go", "")
2077 tg.runFail("get", "github.com/golang/example/hello")
2078 tg.grepStderr(`mkdir .*[/\\]go: .*(not a directory|cannot find the path)`, "expected error because $HOME/go is a file")
2081 func TestDefaultGOPATHPrintedSearchList(t *testing.T) {
2084 tg.setenv("GOPATH", "")
2086 tg.setenv(homeEnvName(), tg.path("home"))
2088 tg.runFail("install", "github.com/golang/example/hello")
2089 tg.grepStderr(regexp.QuoteMeta(tg.path("home/go/src/github.com/golang/example/hello"))+`.*from \$GOPATH`, "expected default GOPATH")
2092 // Issue 4186. go get cannot be used to download packages to $GOROOT.
2093 // Test that without GOPATH set, go get should fail.
2094 func TestGoGetIntoGOROOT(t *testing.T) {
2095 testenv.MustHaveExternalNetwork(t)
2102 // Fails because GOROOT=GOPATH
2103 tg.setenv("GOPATH", tg.path("."))
2104 tg.setenv("GOROOT", tg.path("."))
2105 tg.runFail("get", "-d", "github.com/golang/example/hello")
2106 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2107 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2109 // Fails because GOROOT=GOPATH after cleaning.
2110 tg.setenv("GOPATH", tg.path(".")+"/")
2111 tg.setenv("GOROOT", tg.path("."))
2112 tg.runFail("get", "-d", "github.com/golang/example/hello")
2113 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2114 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2116 tg.setenv("GOPATH", tg.path("."))
2117 tg.setenv("GOROOT", tg.path(".")+"/")
2118 tg.runFail("get", "-d", "github.com/golang/example/hello")
2119 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2120 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2122 // Fails because GOROOT=$HOME/go so default GOPATH unset.
2123 tg.tempDir("home/go")
2124 tg.setenv(homeEnvName(), tg.path("home"))
2125 tg.setenv("GOPATH", "")
2126 tg.setenv("GOROOT", tg.path("home/go"))
2127 tg.runFail("get", "-d", "github.com/golang/example/hello")
2128 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2130 tg.setenv(homeEnvName(), tg.path("home")+"/")
2131 tg.setenv("GOPATH", "")
2132 tg.setenv("GOROOT", tg.path("home/go"))
2133 tg.runFail("get", "-d", "github.com/golang/example/hello")
2134 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2136 tg.setenv(homeEnvName(), tg.path("home"))
2137 tg.setenv("GOPATH", "")
2138 tg.setenv("GOROOT", tg.path("home/go")+"/")
2139 tg.runFail("get", "-d", "github.com/golang/example/hello")
2140 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2143 func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) {
2144 skipIfGccgo(t, "gccgo does not support -ldflags -X")
2149 tg.tempFile("main.go", `package main
2154 tg.run("run", "-ldflags", `-X "main.extern=hello world"`, tg.path("main.go"))
2155 tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`)
2158 func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) {
2159 skipIfGccgo(t, "gccgo has no standard packages")
2163 // TODO: tg.parallel()
2166 tg.run("test", "-cpuprofile", "errors.prof", "errors")
2167 tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test")
2170 func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) {
2171 skipIfGccgo(t, "gccgo has no standard packages")
2175 // TODO: tg.parallel()
2178 tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2179 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test")
2182 func TestGoTestMutexprofileLeavesBinaryBehind(t *testing.T) {
2183 skipIfGccgo(t, "gccgo has no standard packages")
2187 // TODO: tg.parallel()
2190 tg.run("test", "-mutexprofile", "errors.prof", "errors")
2191 tg.wantExecutable("errors.test"+exeSuffix, "go test -mutexprofile did not create errors.test")
2194 func TestGoTestMutexprofileDashOControlsBinaryLocation(t *testing.T) {
2195 skipIfGccgo(t, "gccgo has no standard packages")
2199 // TODO: tg.parallel()
2202 tg.run("test", "-mutexprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2203 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -mutexprofile -o myerrors.test did not create myerrors.test")
2206 func TestGoBuildNonMain(t *testing.T) {
2209 // TODO: tg.parallel()
2210 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2211 tg.runFail("build", "-buildmode=exe", "-o", "not_main"+exeSuffix, "not_main")
2212 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")
2213 tg.mustNotExist("not_main" + exeSuffix)
2216 func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) {
2217 skipIfGccgo(t, "gccgo has no standard packages")
2223 tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2224 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test")
2227 func TestGoTestDashOWritesBinary(t *testing.T) {
2228 skipIfGccgo(t, "gccgo has no standard packages")
2234 tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2235 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2238 func TestGoTestDashIDashOWritesBinary(t *testing.T) {
2239 skipIfGccgo(t, "gccgo has no standard packages")
2246 // don't let test -i overwrite runtime
2247 tg.wantNotStale("runtime", "", "must be non-stale before test -i")
2249 tg.run("test", "-v", "-i", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2250 tg.grepBothNot("PASS|FAIL", "test should not have run")
2251 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2255 func TestSymlinksList(t *testing.T) {
2256 testenv.MustHaveSymlink(t)
2260 // TODO: tg.parallel()
2262 tg.must(os.Symlink(tg.path("."), tg.path("src/dir1")))
2263 tg.tempFile("src/dir1/p.go", "package p")
2264 tg.setenv("GOPATH", tg.path("."))
2265 tg.cd(tg.path("src"))
2266 tg.run("list", "-f", "{{.Root}}", "dir1")
2267 if strings.TrimSpace(tg.getStdout()) != tg.path(".") {
2268 t.Error("confused by symlinks")
2273 func TestSymlinksVendor(t *testing.T) {
2274 testenv.MustHaveSymlink(t)
2278 // TODO: tg.parallel()
2279 tg.tempDir("gopath/src/dir1/vendor/v")
2280 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}")
2281 tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v")
2282 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2283 tg.setenv("GOPATH", tg.path("gopath"))
2284 tg.cd(tg.path("symdir1"))
2285 tg.run("list", "-f", "{{.Root}}", ".")
2286 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2287 t.Error("list confused by symlinks")
2290 // All of these should succeed, not die in vendor-handling code.
2291 tg.run("run", "p.go")
2297 func TestSymlinksVendor15201(t *testing.T) {
2298 testenv.MustHaveSymlink(t)
2303 tg.tempDir("gopath/src/x/y/_vendor/src/x")
2304 tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y")))
2305 tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n")
2306 tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor")))
2307 tg.tempFile("gopath/src/x/y/z/z.go", "package z\n")
2309 tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath"))
2310 tg.cd(tg.path("gopath/src"))
2311 tg.run("list", "./...")
2314 func TestSymlinksInternal(t *testing.T) {
2315 testenv.MustHaveSymlink(t)
2319 tg.tempDir("gopath/src/dir1/internal/v")
2320 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}")
2321 tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v")
2322 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2323 tg.setenv("GOPATH", tg.path("gopath"))
2324 tg.cd(tg.path("symdir1"))
2325 tg.run("list", "-f", "{{.Root}}", ".")
2326 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2327 t.Error("list confused by symlinks")
2330 // All of these should succeed, not die in internal-handling code.
2331 tg.run("run", "p.go")
2337 func TestInstallWithTags(t *testing.T) {
2343 tg.tempFile("src/example/a/main.go", `package main
2345 tg.tempFile("src/example/b/main.go", `// +build mytag
2349 tg.setenv("GOPATH", tg.path("."))
2350 tg.run("install", "-tags", "mytag", "example/a", "example/b")
2351 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries")
2352 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries")
2353 tg.must(os.Remove(tg.path("bin/a" + exeSuffix)))
2354 tg.must(os.Remove(tg.path("bin/b" + exeSuffix)))
2355 tg.run("install", "-tags", "mytag", "example/...")
2356 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries")
2357 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries")
2358 tg.run("list", "-tags", "mytag", "example/b...")
2359 if strings.TrimSpace(tg.getStdout()) != "example/b" {
2360 t.Error("go list example/b did not find example/b")
2365 func TestCaseCollisions(t *testing.T) {
2369 tg.tempDir("src/example/a/pkg")
2370 tg.tempDir("src/example/a/Pkg")
2371 tg.tempDir("src/example/b")
2372 tg.setenv("GOPATH", tg.path("."))
2373 tg.tempFile("src/example/a/a.go", `package p
2378 tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`)
2379 tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`)
2380 tg.run("list", "-json", "example/a")
2381 tg.grepStdout("case-insensitive import collision", "go list -json example/a did not report import collision")
2382 tg.runFail("build", "example/a")
2383 tg.grepStderr("case-insensitive import collision", "go build example/a did not report import collision")
2384 tg.tempFile("src/example/b/file.go", `package b`)
2385 tg.tempFile("src/example/b/FILE.go", `package b`)
2386 f, err := os.Open(tg.path("src/example/b"))
2388 names, err := f.Readdirnames(0)
2391 args := []string{"list"}
2392 if len(names) == 2 {
2393 // case-sensitive file system, let directory read find both files
2394 args = append(args, "example/b")
2396 // case-insensitive file system, list files explicitly on command line
2397 args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go"))
2400 tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision")
2402 tg.runFail("list", "example/a/pkg", "example/a/Pkg")
2403 tg.grepStderr("case-insensitive import collision", "go list example/a/pkg example/a/Pkg did not report import collision")
2404 tg.run("list", "-json", "-e", "example/a/pkg", "example/a/Pkg")
2405 tg.grepStdout("case-insensitive import collision", "go list -json -e example/a/pkg example/a/Pkg did not report import collision")
2406 tg.runFail("build", "example/a/pkg", "example/a/Pkg")
2407 tg.grepStderr("case-insensitive import collision", "go build example/a/pkg example/a/Pkg did not report import collision")
2410 // Issue 17451, 17662.
2411 func TestSymlinkWarning(t *testing.T) {
2416 tg.setenv("GOPATH", tg.path("."))
2418 tg.tempDir("src/example/xx")
2420 tg.tempFile("yy/zz/zz.go", "package zz\n")
2421 if err := os.Symlink(tg.path("yy"), tg.path("src/example/xx/yy")); err != nil {
2422 t.Skipf("symlink failed: %v", err)
2424 tg.run("list", "example/xx/z...")
2425 tg.grepStdoutNot(".", "list should not have matched anything")
2426 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2427 tg.grepStderrNot("symlink", "list should not have reported symlink")
2429 tg.run("list", "example/xx/...")
2430 tg.grepStdoutNot(".", "list should not have matched anything")
2431 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2432 tg.grepStderr("ignoring symlink", "list should have reported symlink")
2436 func TestGoGetDashTIssue8181(t *testing.T) {
2437 testenv.MustHaveExternalNetwork(t)
2438 testenv.MustHaveExecPath(t, "git")
2444 tg.setenv("GOPATH", tg.path("."))
2445 tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b")
2446 tg.run("list", "...")
2447 tg.grepStdout("x/build/gerrit", "missing expected x/build/gerrit")
2450 func TestIssue11307(t *testing.T) {
2451 // go get -u was not working except in checkout directory
2452 testenv.MustHaveExternalNetwork(t)
2453 testenv.MustHaveExecPath(t, "git")
2459 tg.setenv("GOPATH", tg.path("."))
2460 tg.run("get", "github.com/rsc/go-get-issue-11307")
2461 tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing
2464 func TestShadowingLogic(t *testing.T) {
2465 skipIfGccgo(t, "gccgo has no standard packages")
2469 sep := string(filepath.ListSeparator)
2470 tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2"))
2472 // The math in root1 is not "math" because the standard math is.
2473 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math")
2474 pwdForwardSlash := strings.ReplaceAll(pwd, string(os.PathSeparator), "/")
2475 if !strings.HasPrefix(pwdForwardSlash, "/") {
2476 pwdForwardSlash = "/" + pwdForwardSlash
2478 // The output will have makeImportValid applies, but we only
2479 // bother to deal with characters we might reasonably see.
2480 for _, r := range " :" {
2481 pwdForwardSlash = strings.ReplaceAll(pwdForwardSlash, string(r), "_")
2483 want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")"
2484 if strings.TrimSpace(tg.getStdout()) != want {
2485 t.Error("shadowed math is not shadowed; looking for", want)
2488 // The foo in root1 is "foo".
2489 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo")
2490 if strings.TrimSpace(tg.getStdout()) != "(foo) ()" {
2491 t.Error("unshadowed foo is shadowed")
2494 // The foo in root2 is not "foo" because the foo in root1 got there first.
2495 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo")
2496 want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")"
2497 if strings.TrimSpace(tg.getStdout()) != want {
2498 t.Error("shadowed foo is not shadowed; looking for", want)
2501 // The error for go install should mention the conflicting directory.
2502 tg.runFail("install", "./testdata/shadow/root2/src/foo")
2503 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")
2504 if strings.TrimSpace(tg.getStderr()) != want {
2505 t.Error("wrong shadowed install error; looking for", want)
2509 // Only succeeds if source order is preserved.
2510 func TestSourceFileNameOrderPreserved(t *testing.T) {
2513 tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go")
2516 // Check that coverage analysis works at all.
2517 // Don't worry about the exact numbers but require not 0.0%.
2518 func checkCoverage(tg *testgoData, data string) {
2520 if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) {
2521 tg.t.Error("some coverage results are 0.0%")
2525 func TestCoverageRuns(t *testing.T) {
2526 skipIfGccgo(t, "gccgo has no cover tool")
2530 tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp")
2531 data := tg.getStdout() + tg.getStderr()
2532 tg.run("test", "-short", "-cover", "strings", "math", "regexp")
2533 data += tg.getStdout() + tg.getStderr()
2534 checkCoverage(tg, data)
2537 func TestCoverageDotImport(t *testing.T) {
2538 skipIfGccgo(t, "gccgo has no cover tool")
2543 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2544 tg.run("test", "-coverpkg=coverdot1,coverdot2", "coverdot2")
2545 data := tg.getStdout() + tg.getStderr()
2546 checkCoverage(tg, data)
2549 // Check that coverage analysis uses set mode.
2550 // Also check that coverage profiles merge correctly.
2551 func TestCoverageUsesSetMode(t *testing.T) {
2552 skipIfGccgo(t, "gccgo has no cover tool")
2556 tg.creatingTemp("testdata/cover.out")
2557 tg.run("test", "-short", "-cover", "encoding/binary", "errors", "-coverprofile=testdata/cover.out")
2558 data := tg.getStdout() + tg.getStderr()
2559 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2562 if !bytes.Contains(out, []byte("mode: set")) {
2563 t.Error("missing mode: set")
2565 if !bytes.Contains(out, []byte("errors.go")) {
2566 t.Error("missing errors.go")
2568 if !bytes.Contains(out, []byte("binary.go")) {
2569 t.Error("missing binary.go")
2571 if bytes.Count(out, []byte("mode: set")) != 1 {
2572 t.Error("too many mode: set")
2575 checkCoverage(tg, data)
2578 func TestCoverageUsesAtomicModeForRace(t *testing.T) {
2581 t.Skip("skipping because race detector not supported")
2583 skipIfGccgo(t, "gccgo has no cover tool")
2587 tg.creatingTemp("testdata/cover.out")
2588 tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
2589 data := tg.getStdout() + tg.getStderr()
2590 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2593 if !bytes.Contains(out, []byte("mode: atomic")) {
2594 t.Error("missing mode: atomic")
2597 checkCoverage(tg, data)
2600 func TestCoverageSyncAtomicImport(t *testing.T) {
2601 skipIfGccgo(t, "gccgo has no cover tool")
2606 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2607 tg.run("test", "-short", "-cover", "-covermode=atomic", "-coverpkg=coverdep/p1", "coverdep")
2610 func TestCoverageDepLoop(t *testing.T) {
2615 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2616 // coverdep2/p1's xtest imports coverdep2/p2 which imports coverdep2/p1.
2617 // Make sure that coverage on coverdep2/p2 recompiles coverdep2/p2.
2618 tg.run("test", "-short", "-cover", "coverdep2/p1")
2619 tg.grepStdout("coverage: 100.0% of statements", "expected 100.0% coverage")
2622 func TestCoverageNoStatements(t *testing.T) {
2626 tg.run("test", "-cover", "./testdata/testcover/pkg4")
2627 tg.grepStdout("[no statements]", "expected [no statements] for pkg4")
2630 func TestCoverageImportMainLoop(t *testing.T) {
2631 skipIfGccgo(t, "gccgo has no cover tool")
2634 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2635 tg.runFail("test", "importmain/test")
2636 tg.grepStderr("not an importable package", "did not detect import main")
2637 tg.runFail("test", "-cover", "importmain/test")
2638 tg.grepStderr("not an importable package", "did not detect import main")
2641 func TestCoveragePattern(t *testing.T) {
2642 skipIfGccgo(t, "gccgo has no cover tool")
2648 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2650 // If coverpkg=sleepy... expands by package loading
2651 // (as opposed to pattern matching on deps)
2652 // then it will try to load sleepybad, which does not compile,
2653 // and the test command will fail.
2654 tg.run("test", "-coverprofile="+tg.path("cover.out"), "-coverpkg=sleepy...", "-run=^$", "sleepy1")
2657 func TestCoverageErrorLine(t *testing.T) {
2658 skipIfGccgo(t, "gccgo has no cover tool")
2664 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2665 tg.setenv("GOTMPDIR", tg.tempdir)
2667 tg.runFail("test", "coverbad")
2668 tg.grepStderr(`coverbad[\\/]p\.go:4`, "did not find coverbad/p.go:4")
2670 tg.grepStderr(`coverbad[\\/]p1\.go:6`, "did not find coverbad/p1.go:6")
2672 tg.grepStderrNot(regexp.QuoteMeta(tg.tempdir), "found temporary directory in error")
2673 stderr := tg.getStderr()
2675 tg.runFail("test", "-cover", "coverbad")
2676 stderr2 := tg.getStderr()
2678 // It's OK that stderr2 drops the character position in the error,
2679 // because of the //line directive (see golang.org/issue/22662).
2680 stderr = strings.ReplaceAll(stderr, "p.go:4:2:", "p.go:4:")
2681 if stderr != stderr2 {
2682 t.Logf("test -cover changed error messages:\nbefore:\n%s\n\nafter:\n%s", stderr, stderr2)
2683 t.Skip("golang.org/issue/22660")
2688 func TestTestBuildFailureOutput(t *testing.T) {
2694 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2696 // Doesn't build, -x output should not claim to run test.
2697 tg.runFail("test", "-x", "coverbad")
2698 tg.grepStderrNot(`[\\/]coverbad\.test( |$)`, "claimed to run test")
2701 func TestCoverageFunc(t *testing.T) {
2702 skipIfGccgo(t, "gccgo has no cover tool")
2708 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2710 tg.run("test", "-outputdir="+tg.tempdir, "-coverprofile=cover.out", "coverasm")
2711 tg.run("tool", "cover", "-func="+tg.path("cover.out"))
2712 tg.grepStdout(`\tg\t*100.0%`, "did not find g 100% covered")
2713 tg.grepStdoutNot(`\tf\t*[0-9]`, "reported coverage for assembly function f")
2717 func TestCoverageDashC(t *testing.T) {
2718 skipIfGccgo(t, "gccgo has no cover tool")
2724 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2725 tg.run("test", "-c", "-o", tg.path("coverdep"), "-coverprofile="+tg.path("no/such/dir/cover.out"), "coverdep")
2726 tg.wantExecutable(tg.path("coverdep"), "go -test -c -coverprofile did not create executable")
2729 func TestPluginNonMain(t *testing.T) {
2730 wd, err := os.Getwd()
2735 pkg := filepath.Join(wd, "testdata", "testdep", "p2")
2740 tg.runFail("build", "-buildmode=plugin", pkg)
2743 func TestTestEmpty(t *testing.T) {
2745 t.Skip("no race detector")
2749 testdata := filepath.Join(wd, "testdata")
2750 for _, dir := range []string{"pkg", "test", "xtest", "pkgtest", "pkgxtest", "pkgtestxtest", "testxtest"} {
2751 t.Run(dir, func(t *testing.T) {
2754 tg.setenv("GOPATH", testdata)
2755 tg.cd(filepath.Join(testdata, "src/empty/"+dir))
2756 tg.run("test", "-cover", "-coverpkg=.", "-race")
2758 if testing.Short() {
2764 func TestNoGoError(t *testing.T) {
2766 testdata := filepath.Join(wd, "testdata")
2767 for _, dir := range []string{"empty/test", "empty/xtest", "empty/testxtest", "exclude", "exclude/ignore", "exclude/empty"} {
2768 t.Run(dir, func(t *testing.T) {
2771 tg.setenv("GOPATH", testdata)
2772 tg.cd(filepath.Join(testdata, "src"))
2773 tg.runFail("build", "./"+dir)
2775 if strings.Contains(dir, "test") {
2776 want = "no non-test Go files in "
2777 } else if dir == "exclude" {
2778 want = "build constraints exclude all Go files in "
2780 want = "no Go files in "
2782 tg.grepStderr(want, "wrong reason for failure")
2787 func TestTestRaceInstall(t *testing.T) {
2789 t.Skip("no race detector")
2795 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2798 pkgdir := tg.path("pkg")
2799 tg.run("install", "-race", "-pkgdir="+pkgdir, "std")
2800 tg.run("test", "-race", "-pkgdir="+pkgdir, "-i", "-v", "empty/pkg")
2801 if tg.getStderr() != "" {
2802 t.Error("go test -i -race: rebuilds cached packages")
2806 func TestBuildDryRunWithCgo(t *testing.T) {
2808 t.Skip("skipping because cgo not enabled")
2813 tg.tempFile("foo.go", `package main
2823 tg.run("build", "-n", tg.path("foo.go"))
2824 tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file")
2827 func TestCoverageWithCgo(t *testing.T) {
2828 skipIfGccgo(t, "gccgo has no cover tool")
2831 t.Skip("skipping because cgo not enabled")
2834 for _, dir := range []string{"cgocover", "cgocover2", "cgocover3", "cgocover4"} {
2835 t.Run(dir, func(t *testing.T) {
2839 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2840 tg.run("test", "-short", "-cover", dir)
2841 data := tg.getStdout() + tg.getStderr()
2842 checkCoverage(tg, data)
2847 func TestCgoAsmError(t *testing.T) {
2849 t.Skip("skipping because cgo not enabled")
2855 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2856 tg.runFail("build", "cgoasm")
2857 tg.grepBoth("package using cgo has Go assembly file", "did not detect Go assembly file")
2860 func TestCgoDependsOnSyscall(t *testing.T) {
2861 if testing.Short() {
2862 t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode")
2865 t.Skip("skipping because cgo not enabled")
2868 t.Skip("skipping because race detector not supported")
2873 files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race"))
2875 for _, file := range files {
2876 tg.check(robustio.RemoveAll(file))
2878 tg.tempFile("src/foo/foo.go", `
2880 //#include <stdio.h>
2882 tg.setenv("GOPATH", tg.path("."))
2883 tg.run("build", "-race", "foo")
2886 func TestCgoShowsFullPathNames(t *testing.T) {
2888 t.Skip("skipping because cgo not enabled")
2894 tg.tempFile("src/x/y/dirname/foo.go", `
2898 tg.setenv("GOPATH", tg.path("."))
2899 tg.runFail("build", "x/y/dirname")
2900 tg.grepBoth("x/y/dirname", "error did not use full path")
2903 func TestCgoHandlesWlORIGIN(t *testing.T) {
2906 t.Skip("skipping because cgo not enabled")
2912 tg.tempFile("src/origin/origin.go", `package origin
2913 // #cgo !darwin LDFLAGS: -Wl,-rpath,$ORIGIN
2916 func f() { C.f() }`)
2917 tg.setenv("GOPATH", tg.path("."))
2918 tg.run("build", "origin")
2921 func TestCgoPkgConfig(t *testing.T) {
2924 t.Skip("skipping because cgo not enabled")
2930 tg.run("env", "PKG_CONFIG")
2931 pkgConfig := strings.TrimSpace(tg.getStdout())
2932 testenv.MustHaveExecPath(t, pkgConfig)
2933 if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil {
2934 t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out)
2937 // OpenBSD's pkg-config is strict about whitespace and only
2938 // supports backslash-escaped whitespace. It does not support
2939 // quotes, which the normal freedesktop.org pkg-config does
2940 // support. See https://man.openbsd.org/pkg-config.1
2941 tg.tempFile("foo.pc", `
2943 Description: The foo library
2945 Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world
2947 tg.tempFile("foo.go", `package main
2950 #cgo pkg-config: foo
2952 return DEFINED_FROM_PKG_CONFIG;
2959 if C.value() != 42 {
2960 println("value() =", C.value(), "wanted 42")
2965 tg.setenv("PKG_CONFIG_PATH", tg.path("."))
2966 tg.run("run", tg.path("foo.go"))
2969 // "go test -c -test.bench=XXX errors" should not hang.
2970 // "go test -c" should also produce reproducible binaries.
2971 // "go test -c" should also appear to write a new binary every time,
2972 // even if it's really just updating the mtime on an existing up-to-date binary.
2973 func TestIssue6480(t *testing.T) {
2974 skipIfGccgo(t, "gccgo has no standard packages")
2978 // TODO: tg.parallel()
2981 tg.run("test", "-c", "-test.bench=XXX", "errors")
2982 tg.run("test", "-c", "-o", "errors2.test", "errors")
2984 data1, err := ioutil.ReadFile("errors.test" + exeSuffix)
2986 data2, err := ioutil.ReadFile("errors2.test") // no exeSuffix because -o above doesn't have it
2988 if !bytes.Equal(data1, data2) {
2989 t.Fatalf("go test -c errors produced different binaries when run twice")
2993 tg.run("test", "-x", "-c", "-test.bench=XXX", "errors")
2994 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
2995 info, err := os.Stat("errors.test" + exeSuffix)
2999 start = truncateLike(start, info.ModTime())
3000 if info.ModTime().Before(start) {
3001 t.Fatalf("mtime of errors.test predates test -c command (%v < %v)", info.ModTime(), start)
3005 tg.run("test", "-x", "-c", "-o", "errors2.test", "errors")
3006 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
3007 info, err = os.Stat("errors2.test")
3011 start = truncateLike(start, info.ModTime())
3012 if info.ModTime().Before(start) {
3013 t.Fatalf("mtime of errors2.test predates test -c command (%v < %v)", info.ModTime(), start)
3017 // truncateLike returns the result of truncating t to the apparent precision of p.
3018 func truncateLike(t, p time.Time) time.Time {
3019 nano := p.UnixNano()
3020 d := 1 * time.Nanosecond
3021 for nano%int64(d) == 0 && d < 1*time.Second {
3024 for nano%int64(d) == 0 && d < 2*time.Second {
3027 return t.Truncate(d)
3030 // cmd/cgo: undefined reference when linking a C-library using gccgo
3031 func TestIssue7573(t *testing.T) {
3033 t.Skip("skipping because cgo not enabled")
3035 testenv.MustHaveExecPath(t, "gccgo")
3040 tg.tempFile("src/cgoref/cgoref.go", `
3042 // #cgo LDFLAGS: -L alibpath -lalib
3046 func main() { C.f() }`)
3047 tg.setenv("GOPATH", tg.path("."))
3048 tg.run("build", "-n", "-compiler", "gccgo", "cgoref")
3049 tg.grepStderr(`gccgo.*\-L [^ ]*alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`)
3052 func TestListTemplateContextFunction(t *testing.T) {
3054 for _, tt := range []struct {
3058 {"GOARCH", runtime.GOARCH},
3059 {"GOOS", runtime.GOOS},
3060 {"GOROOT", filepath.Clean(runtime.GOROOT())},
3061 {"GOPATH", os.Getenv("GOPATH")},
3063 {"UseAllFiles", ""},
3066 {"ReleaseTags", ""},
3067 {"InstallSuffix", ""},
3070 t.Run(tt.v, func(t *testing.T) {
3074 tmpl := "{{context." + tt.v + "}}"
3075 tg.run("list", "-f", tmpl)
3079 if got := strings.TrimSpace(tg.getStdout()); got != tt.want {
3080 t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want)
3086 // cmd/go: "go test" should fail if package does not build
3087 func TestIssue7108(t *testing.T) {
3090 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3091 tg.runFail("test", "notest")
3094 // cmd/go: go test -a foo does not rebuild regexp.
3095 func TestIssue6844(t *testing.T) {
3096 if testing.Short() {
3097 t.Skip("don't rebuild the standard library in short mode")
3102 tg.creatingTemp("deps.test" + exeSuffix)
3103 tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go")
3104 tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp")
3107 func TestBuildDashIInstallsDependencies(t *testing.T) {
3113 tg.tempFile("src/x/y/foo/foo.go", `package foo
3115 tg.tempFile("src/x/y/bar/bar.go", `package bar
3117 func F() { foo.F() }`)
3118 tg.setenv("GOPATH", tg.path("."))
3120 // don't let build -i overwrite runtime
3121 tg.wantNotStale("runtime", "", "must be non-stale before build -i")
3123 checkbar := func(desc string) {
3124 tg.run("build", "-v", "-i", "x/y/bar")
3125 tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo")
3126 tg.run("build", "-v", "-i", "x/y/bar")
3127 tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo")
3131 tg.creatingTemp("bar" + exeSuffix)
3133 tg.tempFile("src/x/y/foo/foo.go", `package foo
3135 tg.tempFile("src/x/y/bar/bar.go", `package main
3137 func main() { foo.F() }`)
3141 func TestGoBuildTestOnly(t *testing.T) {
3145 tg.setenv("GOPATH", tg.path("."))
3146 tg.tempFile("src/testonly/t_test.go", `package testonly`)
3147 tg.tempFile("src/testonly2/t.go", `package testonly2`)
3148 tg.cd(tg.path("src"))
3150 // Named explicitly, test-only packages should be reported as unbuildable/uninstallable,
3151 // even if there is a wildcard also matching.
3152 tg.runFail("build", "testonly", "testonly...")
3153 tg.grepStderr("no non-test Go files in", "go build ./xtestonly produced unexpected error")
3154 tg.runFail("install", "./testonly")
3155 tg.grepStderr("no non-test Go files in", "go install ./testonly produced unexpected error")
3157 // Named through a wildcards, the test-only packages should be silently ignored.
3158 tg.run("build", "testonly...")
3159 tg.run("install", "./testonly...")
3162 func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) {
3165 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3166 tg.runFail("test", "-c", "testcycle/p3")
3167 tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error")
3169 tg.runFail("test", "-c", "testcycle/q1")
3170 tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error")
3173 func TestGoTestFooTestWorks(t *testing.T) {
3176 tg.run("test", "testdata/standalone_test.go")
3180 func TestGoTestMainWithWrongSignature(t *testing.T) {
3183 tg.runFail("test", "testdata/standalone_main_wrong_test.go")
3184 tg.grepStderr(`wrong signature for TestMain, must be: func TestMain\(m \*testing.M\)`, "detected wrong error message")
3187 func TestGoTestMainAsNormalTest(t *testing.T) {
3190 tg.run("test", "testdata/standalone_main_normal_test.go")
3191 tg.grepBoth(okPattern, "go test did not say ok")
3194 func TestGoTestMainTwice(t *testing.T) {
3195 if testing.Short() {
3196 t.Skip("Skipping in short mode")
3201 tg.setenv("GOCACHE", tg.tempdir)
3202 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3203 tg.run("test", "-v", "multimain")
3204 if strings.Count(tg.getStdout(), "notwithstanding") != 2 {
3205 t.Fatal("tests did not run twice")
3209 func TestGoTestFlagsAfterPackage(t *testing.T) {
3213 tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags.
3214 tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags.
3217 func TestGoTestXtestonlyWorks(t *testing.T) {
3220 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3221 tg.run("clean", "-i", "xtestonly")
3222 tg.run("test", "xtestonly")
3225 func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) {
3228 tg.run("test", "-v", "./testdata/norunexample")
3229 tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built")
3232 func TestGoGenerateHandlesSimpleCommand(t *testing.T) {
3233 if runtime.GOOS == "windows" {
3234 t.Skip("skipping because windows has no echo command")
3239 tg.run("generate", "./testdata/generate/test1.go")
3240 tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output")
3243 func TestGoGenerateHandlesCommandAlias(t *testing.T) {
3244 if runtime.GOOS == "windows" {
3245 t.Skip("skipping because windows has no echo command")
3250 tg.run("generate", "./testdata/generate/test2.go")
3251 tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output")
3254 func TestGoGenerateVariableSubstitution(t *testing.T) {
3255 if runtime.GOOS == "windows" {
3256 t.Skip("skipping because windows has no echo command")
3261 tg.run("generate", "./testdata/generate/test3.go")
3262 tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output")
3265 func TestGoGenerateRunFlag(t *testing.T) {
3266 if runtime.GOOS == "windows" {
3267 t.Skip("skipping because windows has no echo command")
3272 tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go")
3273 tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes")
3274 tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no")
3277 func TestGoGenerateEnv(t *testing.T) {
3278 switch runtime.GOOS {
3279 case "plan9", "windows":
3280 t.Skipf("skipping because %s does not have the env command", runtime.GOOS)
3285 tg.tempFile("env.go", "package main\n\n//go:generate env")
3286 tg.run("generate", tg.path("env.go"))
3287 for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} {
3288 tg.grepStdout("^"+v+"=", "go generate environment missing "+v)
3292 func TestGoGenerateXTestPkgName(t *testing.T) {
3293 if runtime.GOOS == "windows" {
3294 t.Skip("skipping because windows has no echo command")
3300 tg.tempFile("env_test.go", "package main_test\n\n//go:generate echo $GOPACKAGE")
3301 tg.run("generate", tg.path("env_test.go"))
3303 if got := strings.TrimSpace(tg.getStdout()); got != want {
3304 t.Errorf("go generate in XTest file got package name %q; want %q", got, want)
3308 func TestGoGenerateBadImports(t *testing.T) {
3309 if runtime.GOOS == "windows" {
3310 t.Skip("skipping because windows has no echo command")
3313 // This package has an invalid import causing an import cycle,
3314 // but go generate is supposed to still run.
3317 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3318 tg.run("generate", "gencycle")
3319 tg.grepStdout("hello world", "go generate gencycle did not run generator")
3322 func TestGoGetCustomDomainWildcard(t *testing.T) {
3323 testenv.MustHaveExternalNetwork(t)
3324 testenv.MustHaveExecPath(t, "git")
3329 tg.setenv("GOPATH", tg.path("."))
3330 tg.run("get", "-u", "rsc.io/pdf/...")
3331 tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd")
3334 func TestGoGetInternalWildcard(t *testing.T) {
3335 testenv.MustHaveExternalNetwork(t)
3336 testenv.MustHaveExecPath(t, "git")
3341 tg.setenv("GOPATH", tg.path("."))
3342 // used to fail with errors about internal packages
3343 tg.run("get", "github.com/rsc/go-get-issue-11960/...")
3346 func TestGoVetWithExternalTests(t *testing.T) {
3350 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3351 tg.runFail("vet", "vetpkg")
3352 tg.grepBoth("Printf", "go vet vetpkg did not find missing argument for Printf")
3355 func TestGoVetWithTags(t *testing.T) {
3359 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3360 tg.runFail("vet", "-tags", "tagtest", "vetpkg")
3361 tg.grepBoth(`c\.go.*Printf`, "go vet vetpkg did not run scan tagged file")
3364 func TestGoVetWithFlagsOn(t *testing.T) {
3368 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3369 tg.runFail("vet", "-printf", "vetpkg")
3370 tg.grepBoth("Printf", "go vet -printf vetpkg did not find missing argument for Printf")
3373 func TestGoVetWithFlagsOff(t *testing.T) {
3377 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3378 tg.run("vet", "-printf=false", "vetpkg")
3382 func TestGoVetWithOnlyTestFiles(t *testing.T) {
3386 tg.tempFile("src/p/p_test.go", "package p; import \"testing\"; func TestMe(*testing.T) {}")
3387 tg.setenv("GOPATH", tg.path("."))
3392 func TestVetWithOnlyCgoFiles(t *testing.T) {
3394 t.Skip("skipping because cgo not enabled")
3401 tg.tempFile("src/p/p.go", "package p; import \"C\"; func F() {}")
3402 tg.setenv("GOPATH", tg.path("."))
3406 // Issue 9767, 19769.
3407 func TestGoGetDotSlashDownload(t *testing.T) {
3408 testenv.MustHaveExternalNetwork(t)
3409 testenv.MustHaveExecPath(t, "git")
3413 tg.tempDir("src/rsc.io")
3414 tg.setenv("GOPATH", tg.path("."))
3415 tg.cd(tg.path("src/rsc.io"))
3416 tg.run("get", "./pprof_mac_fix")
3419 // Test that you cannot import a main package.
3420 // See golang.org/issue/4210 and golang.org/issue/17475.
3421 func TestImportMain(t *testing.T) {
3428 // Importing package main from that package main's test should work.
3429 tg.tempFile("src/x/main.go", `package main
3432 tg.tempFile("src/x/main_test.go", `package main_test
3436 func TestFoo(t *testing.T) {}
3438 tg.setenv("GOPATH", tg.path("."))
3439 tg.creatingTemp("x" + exeSuffix)
3440 tg.run("build", "x")
3443 // Importing package main from another package should fail.
3444 tg.tempFile("src/p1/p.go", `package p1
3448 tg.runFail("build", "p1")
3449 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3451 // ... even in that package's test.
3452 tg.tempFile("src/p2/p.go", `package p2
3454 tg.tempFile("src/p2/p_test.go", `package p2
3458 func TestFoo(t *testing.T) {}
3460 tg.run("build", "p2")
3461 tg.runFail("test", "p2")
3462 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3464 // ... even if that package's test is an xtest.
3465 tg.tempFile("src/p3/p.go", `package p
3467 tg.tempFile("src/p3/p_test.go", `package p_test
3471 func TestFoo(t *testing.T) {}
3473 tg.run("build", "p3")
3474 tg.runFail("test", "p3")
3475 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3477 // ... even if that package is a package main
3478 tg.tempFile("src/p4/p.go", `package main
3481 tg.tempFile("src/p4/p_test.go", `package main
3485 func TestFoo(t *testing.T) {}
3487 tg.creatingTemp("p4" + exeSuffix)
3488 tg.run("build", "p4")
3489 tg.runFail("test", "p4")
3490 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3492 // ... even if that package is a package main using an xtest.
3493 tg.tempFile("src/p5/p.go", `package main
3496 tg.tempFile("src/p5/p_test.go", `package main_test
3500 func TestFoo(t *testing.T) {}
3502 tg.creatingTemp("p5" + exeSuffix)
3503 tg.run("build", "p5")
3504 tg.runFail("test", "p5")
3505 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3508 // Test that you cannot use a local import in a package
3509 // accessed by a non-local import (found in a GOPATH/GOROOT).
3510 // See golang.org/issue/17475.
3511 func TestImportLocal(t *testing.T) {
3518 tg.tempFile("src/dir/x/x.go", `package x
3521 tg.setenv("GOPATH", tg.path("."))
3522 tg.run("build", "dir/x")
3524 // Ordinary import should work.
3525 tg.tempFile("src/dir/p0/p.go", `package p0
3529 tg.run("build", "dir/p0")
3531 // Relative import should not.
3532 tg.tempFile("src/dir/p1/p.go", `package p1
3536 tg.runFail("build", "dir/p1")
3537 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3539 // ... even in a test.
3540 tg.tempFile("src/dir/p2/p.go", `package p2
3542 tg.tempFile("src/dir/p2/p_test.go", `package p2
3546 func TestFoo(t *testing.T) {}
3548 tg.run("build", "dir/p2")
3549 tg.runFail("test", "dir/p2")
3550 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3552 // ... even in an xtest.
3553 tg.tempFile("src/dir/p2/p_test.go", `package p2_test
3557 func TestFoo(t *testing.T) {}
3559 tg.run("build", "dir/p2")
3560 tg.runFail("test", "dir/p2")
3561 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3563 // Relative import starting with ./ should not work either.
3564 tg.tempFile("src/dir/d.go", `package dir
3568 tg.runFail("build", "dir")
3569 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3571 // ... even in a test.
3572 tg.tempFile("src/dir/d.go", `package dir
3574 tg.tempFile("src/dir/d_test.go", `package dir
3578 func TestFoo(t *testing.T) {}
3580 tg.run("build", "dir")
3581 tg.runFail("test", "dir")
3582 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3584 // ... even in an xtest.
3585 tg.tempFile("src/dir/d_test.go", `package dir_test
3589 func TestFoo(t *testing.T) {}
3591 tg.run("build", "dir")
3592 tg.runFail("test", "dir")
3593 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3595 // Relative import plain ".." should not work.
3596 tg.tempFile("src/dir/x/y/y.go", `package dir
3600 tg.runFail("build", "dir/x/y")
3601 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3603 // ... even in a test.
3604 tg.tempFile("src/dir/x/y/y.go", `package y
3606 tg.tempFile("src/dir/x/y/y_test.go", `package y
3610 func TestFoo(t *testing.T) {}
3612 tg.run("build", "dir/x/y")
3613 tg.runFail("test", "dir/x/y")
3614 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3616 // ... even in an x test.
3617 tg.tempFile("src/dir/x/y/y_test.go", `package y_test
3621 func TestFoo(t *testing.T) {}
3623 tg.run("build", "dir/x/y")
3624 tg.runFail("test", "dir/x/y")
3625 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3627 // Relative import "." should not work.
3628 tg.tempFile("src/dir/x/xx.go", `package x
3632 tg.runFail("build", "dir/x")
3633 tg.grepStderr("cannot import current directory", "did not diagnose import current directory")
3635 // ... even in a test.
3636 tg.tempFile("src/dir/x/xx.go", `package x
3638 tg.tempFile("src/dir/x/xx_test.go", `package x
3642 func TestFoo(t *testing.T) {}
3644 tg.run("build", "dir/x")
3645 tg.runFail("test", "dir/x")
3646 tg.grepStderr("cannot import current directory", "did not diagnose import current directory")
3648 // ... even in an xtest.
3649 tg.tempFile("src/dir/x/xx.go", `package x
3651 tg.tempFile("src/dir/x/xx_test.go", `package x_test
3655 func TestFoo(t *testing.T) {}
3657 tg.run("build", "dir/x")
3658 tg.runFail("test", "dir/x")
3659 tg.grepStderr("cannot import current directory", "did not diagnose import current directory")
3662 func TestGoGetInsecure(t *testing.T) {
3663 test := func(t *testing.T, modules bool) {
3664 testenv.MustHaveExternalNetwork(t)
3665 testenv.MustHaveExecPath(t, "git")
3673 tg.setenv("GOPATH", tg.path("gp"))
3674 tg.tempFile("go.mod", "module m")
3676 tg.setenv("GO111MODULE", "on")
3677 tg.setenv("GOPROXY", "")
3679 tg.setenv("GOPATH", tg.path("."))
3680 tg.setenv("GO111MODULE", "off")
3683 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3685 // Try go get -d of HTTP-only repo (should fail).
3686 tg.runFail("get", "-d", repo)
3688 // Try again with -insecure (should succeed).
3689 tg.run("get", "-d", "-insecure", repo)
3691 // Try updating without -insecure (should fail).
3692 tg.runFail("get", "-d", "-u", "-f", repo)
3695 tg.run("list", "-m", "...")
3696 tg.grepStdout("insecure.go-get-issue", "should find insecure module")
3700 t.Run("gopath", func(t *testing.T) { test(t, false) })
3701 t.Run("modules", func(t *testing.T) { test(t, true) })
3704 func TestGoGetUpdateInsecure(t *testing.T) {
3705 testenv.MustHaveExternalNetwork(t)
3706 testenv.MustHaveExecPath(t, "git")
3711 tg.setenv("GOPATH", tg.path("."))
3713 const repo = "github.com/golang/example"
3715 // Clone the repo via HTTP manually.
3716 cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
3717 if out, err := cmd.CombinedOutput(); err != nil {
3718 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3721 // Update without -insecure should fail.
3722 // Update with -insecure should succeed.
3723 // We need -f to ignore import comments.
3724 const pkg = repo + "/hello"
3725 tg.runFail("get", "-d", "-u", "-f", pkg)
3726 tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
3729 func TestGoGetUpdateUnknownProtocol(t *testing.T) {
3730 testenv.MustHaveExternalNetwork(t)
3731 testenv.MustHaveExecPath(t, "git")
3736 tg.setenv("GOPATH", tg.path("."))
3738 const repo = "github.com/golang/example"
3740 // Clone the repo via HTTPS manually.
3741 repoDir := tg.path("src/" + repo)
3742 cmd := exec.Command("git", "clone", "-q", "https://"+repo, repoDir)
3743 if out, err := cmd.CombinedOutput(); err != nil {
3744 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3747 // Configure the repo to use a protocol unknown to cmd/go
3748 // that still actually works.
3749 cmd = exec.Command("git", "remote", "set-url", "origin", "xyz://"+repo)
3751 if out, err := cmd.CombinedOutput(); err != nil {
3752 t.Fatalf("git remote set-url: %v\n%s", err, out)
3754 cmd = exec.Command("git", "config", "--local", "url.https://github.com/.insteadOf", "xyz://github.com/")
3756 if out, err := cmd.CombinedOutput(); err != nil {
3757 t.Fatalf("git config: %v\n%s", err, out)
3760 // We need -f to ignore import comments.
3761 tg.run("get", "-d", "-u", "-f", repo+"/hello")
3764 func TestGoGetInsecureCustomDomain(t *testing.T) {
3765 testenv.MustHaveExternalNetwork(t)
3766 testenv.MustHaveExecPath(t, "git")
3771 tg.setenv("GOPATH", tg.path("."))
3773 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3774 tg.runFail("get", "-d", repo)
3775 tg.run("get", "-d", "-insecure", repo)
3778 func TestGoRunDirs(t *testing.T) {
3781 tg.cd("testdata/rundir")
3782 tg.runFail("run", "x.go", "sub/sub.go")
3783 tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
3784 tg.runFail("run", "sub/sub.go", "x.go")
3785 tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
3788 func TestGoInstallPkgdir(t *testing.T) {
3789 skipIfGccgo(t, "gccgo has no standard packages")
3797 tg.run("install", "-pkgdir", pkg, "sync")
3798 tg.mustExist(filepath.Join(pkg, "sync.a"))
3799 tg.mustNotExist(filepath.Join(pkg, "sync/atomic.a"))
3800 tg.run("install", "-i", "-pkgdir", pkg, "sync")
3801 tg.mustExist(filepath.Join(pkg, "sync.a"))
3802 tg.mustExist(filepath.Join(pkg, "sync/atomic.a"))
3805 func TestGoTestRaceInstallCgo(t *testing.T) {
3807 t.Skip("skipping because race detector not supported")
3810 // golang.org/issue/10500.
3811 // This used to install a race-enabled cgo.
3814 tg.run("tool", "-n", "cgo")
3815 cgo := strings.TrimSpace(tg.stdout.String())
3816 old, err := os.Stat(cgo)
3818 tg.run("test", "-race", "-i", "runtime/race")
3819 new, err := os.Stat(cgo)
3821 if !new.ModTime().Equal(old.ModTime()) {
3822 t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
3826 func TestGoTestRaceFailures(t *testing.T) {
3830 t.Skip("skipping because race detector not supported")
3836 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3838 tg.run("test", "testrace")
3840 tg.runFail("test", "-race", "testrace")
3841 tg.grepStdout("FAIL: TestRace", "TestRace did not fail")
3842 tg.grepBothNot("PASS", "something passed")
3844 tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".")
3845 tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail")
3846 tg.grepBothNot("PASS", "something passed")
3849 func TestGoTestImportErrorStack(t *testing.T) {
3850 const out = `package testdep/p1 (test)
3852 imports testdep/p3: build constraints exclude all Go files `
3856 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3857 tg.runFail("test", "testdep/p1")
3858 if !strings.Contains(tg.stderr.String(), out) {
3859 t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String())
3863 func TestGoGetUpdate(t *testing.T) {
3864 // golang.org/issue/9224.
3865 // The recursive updating was trying to walk to
3866 // former dependencies, not current ones.
3868 testenv.MustHaveExternalNetwork(t)
3869 testenv.MustHaveExecPath(t, "git")
3874 tg.setenv("GOPATH", tg.path("."))
3877 tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
3878 cmd := exec.Command("git", "reset", "--hard", "HEAD~")
3879 cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
3880 out, err := cmd.CombinedOutput()
3882 t.Fatalf("git: %v\n%s", err, out)
3887 tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3889 // Again with -d -u.
3891 tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3895 func TestGoGetRace(t *testing.T) {
3896 testenv.MustHaveExternalNetwork(t)
3897 testenv.MustHaveExecPath(t, "git")
3899 t.Skip("skipping because race detector not supported")
3905 tg.setenv("GOPATH", tg.path("."))
3906 tg.run("get", "-race", "github.com/rsc/go-get-issue-9224-cmd")
3909 func TestGoGetDomainRoot(t *testing.T) {
3910 // golang.org/issue/9357.
3911 // go get foo.io (not foo.io/subdir) was not working consistently.
3913 testenv.MustHaveExternalNetwork(t)
3914 testenv.MustHaveExecPath(t, "git")
3919 tg.setenv("GOPATH", tg.path("."))
3921 // go-get-issue-9357.appspot.com is running
3922 // the code at github.com/rsc/go-get-issue-9357,
3923 // a trivial Go on App Engine app that serves a
3924 // <meta> tag for the domain root.
3925 tg.run("get", "-d", "go-get-issue-9357.appspot.com")
3926 tg.run("get", "go-get-issue-9357.appspot.com")
3927 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3929 tg.must(robustio.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3930 tg.run("get", "go-get-issue-9357.appspot.com")
3932 tg.must(robustio.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3933 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3936 func TestGoInstallShadowedGOPATH(t *testing.T) {
3937 // golang.org/issue/3652.
3938 // go get foo.io (not foo.io/subdir) was not working consistently.
3940 testenv.MustHaveExternalNetwork(t)
3945 tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
3947 tg.tempDir("gopath1/src/test")
3948 tg.tempDir("gopath2/src/test")
3949 tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
3951 tg.cd(tg.path("gopath2/src/test"))
3952 tg.runFail("install")
3953 tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
3956 func TestGoBuildGOPATHOrder(t *testing.T) {
3957 // golang.org/issue/14176#issuecomment-179895769
3958 // golang.org/issue/14192
3959 // -I arguments to compiler could end up not in GOPATH order,
3960 // leading to unexpected import resolution in the compiler.
3961 // This is still not a complete fix (see golang.org/issue/14271 and next test)
3962 // but it is clearly OK and enough to fix both of the two reported
3963 // instances of the underlying problem. It will have to do for now.
3968 tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2"))
3970 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3971 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3972 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3973 tg.tempFile("p1/src/bar/bar.go", `
3979 tg.run("install", "-x", "bar")
3982 func TestGoBuildGOPATHOrderBroken(t *testing.T) {
3983 // This test is known not to work.
3984 // See golang.org/issue/14271.
3985 t.Skip("golang.org/issue/14271")
3991 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3992 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3993 tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n")
3994 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3995 tg.tempFile("p1/src/bar/bar.go", `
4001 colon := string(filepath.ListSeparator)
4002 tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2"))
4003 tg.run("install", "-x", "bar")
4005 tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1"))
4006 tg.run("install", "-x", "bar")
4009 func TestIssue11709(t *testing.T) {
4012 tg.tempFile("run.go", `
4016 if os.Getenv("TERM") != "" {
4021 tg.run("run", tg.path("run.go"))
4024 func TestIssue12096(t *testing.T) {
4027 tg.tempFile("test_test.go", `
4029 import ("os"; "testing")
4030 func TestEnv(t *testing.T) {
4031 if os.Getenv("TERM") != "" {
4032 t.Fatal("TERM is set")
4036 tg.run("test", tg.path("test_test.go"))
4039 func TestGoBuildOutput(t *testing.T) {
4040 skipIfGccgo(t, "gccgo has no standard packages")
4048 nonExeSuffix := ".exe"
4049 if exeSuffix == ".exe" {
4053 tg.tempFile("x.go", "package main\nfunc main(){}\n")
4054 tg.run("build", "x.go")
4055 tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
4056 tg.must(os.Remove(tg.path("x" + exeSuffix)))
4057 tg.mustNotExist("x" + nonExeSuffix)
4059 tg.run("build", "-o", "myprog", "x.go")
4060 tg.mustNotExist("x")
4061 tg.mustNotExist("x.exe")
4062 tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
4063 tg.mustNotExist("myprog.exe")
4065 tg.tempFile("p.go", "package p\n")
4066 tg.run("build", "p.go")
4067 tg.mustNotExist("p")
4068 tg.mustNotExist("p.a")
4069 tg.mustNotExist("p.o")
4070 tg.mustNotExist("p.exe")
4072 tg.run("build", "-o", "p.a", "p.go")
4073 tg.wantArchive("p.a")
4075 tg.run("build", "cmd/gofmt")
4076 tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
4077 tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
4078 tg.mustNotExist("gofmt" + nonExeSuffix)
4080 tg.run("build", "-o", "mygofmt", "cmd/gofmt")
4081 tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
4082 tg.mustNotExist("mygofmt.exe")
4083 tg.mustNotExist("gofmt")
4084 tg.mustNotExist("gofmt.exe")
4086 tg.run("build", "sync/atomic")
4087 tg.mustNotExist("atomic")
4088 tg.mustNotExist("atomic.exe")
4090 tg.run("build", "-o", "myatomic.a", "sync/atomic")
4091 tg.wantArchive("myatomic.a")
4092 tg.mustNotExist("atomic")
4093 tg.mustNotExist("atomic.a")
4094 tg.mustNotExist("atomic.exe")
4096 tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
4097 tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
4100 func TestGoBuildARM(t *testing.T) {
4101 if testing.Short() {
4102 t.Skip("skipping cross-compile in short mode")
4111 tg.setenv("GOARCH", "arm")
4112 tg.setenv("GOOS", "linux")
4113 tg.setenv("GOARM", "5")
4114 tg.tempFile("hello.go", `package main
4116 tg.run("build", "hello.go")
4117 tg.grepStderrNot("unable to find math.a", "did not build math.a correctly")
4121 func TestParallelTest(t *testing.T) {
4127 const testSrc = `package package_test
4131 func TestTest(t *testing.T) {
4133 tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
4134 tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
4135 tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
4136 tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
4137 tg.setenv("GOPATH", tg.path("."))
4138 tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
4141 func TestCgoConsistentResults(t *testing.T) {
4144 t.Skip("skipping because cgo not enabled")
4146 switch runtime.GOOS {
4147 case "solaris", "illumos":
4148 testenv.SkipFlaky(t, 13247)
4155 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4156 exe1 := tg.path("cgotest1" + exeSuffix)
4157 exe2 := tg.path("cgotest2" + exeSuffix)
4158 tg.run("build", "-o", exe1, "cgotest")
4159 tg.run("build", "-x", "-o", exe2, "cgotest")
4160 b1, err := ioutil.ReadFile(exe1)
4162 b2, err := ioutil.ReadFile(exe2)
4165 if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) {
4166 t.Skip("skipping because C compiler does not support -fdebug-prefix-map")
4168 if !bytes.Equal(b1, b2) {
4169 t.Error("building cgotest twice did not produce the same output")
4173 // Issue 14444: go get -u .../ duplicate loads errors
4174 func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) {
4175 testenv.MustHaveExternalNetwork(t)
4180 tg.setenv("GOPATH", tg.path("."))
4181 tg.run("get", "-u", ".../")
4182 tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache")
4185 // Issue 17119 more duplicate load errors
4186 func TestIssue17119(t *testing.T) {
4187 testenv.MustHaveExternalNetwork(t)
4192 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4193 tg.runFail("build", "dupload")
4194 tg.grepBothNot("duplicate load|internal error", "internal error")
4197 func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) {
4200 // TODO: tg.parallel()
4201 tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal")
4202 tg.grepBothNot("^ok", "test passed unexpectedly")
4203 tg.grepBoth("FAIL.*benchfatal", "test did not run everything")
4206 func TestBinaryOnlyPackages(t *testing.T) {
4213 tg.setenv("GOPATH", tg.path("."))
4215 tg.tempFile("src/p1/p1.go", `//go:binary-only-package
4219 tg.wantStale("p1", "binary-only packages are no longer supported", "p1 is binary-only, and this message should always be printed")
4220 tg.runFail("install", "p1")
4221 tg.grepStderr("binary-only packages are no longer supported", "did not report attempt to compile binary-only package")
4223 tg.tempFile("src/p1/p1.go", `
4226 func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } }
4228 tg.run("install", "p1")
4229 os.Remove(tg.path("src/p1/p1.go"))
4230 tg.mustNotExist(tg.path("src/p1/p1.go"))
4232 tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great
4236 func F() { p1.F(true) }
4238 tg.runFail("install", "p2")
4239 tg.grepStderr("no Go files", "did not complain about missing sources")
4241 tg.tempFile("src/p1/missing.go", `//go:binary-only-package
4247 tg.wantStale("p1", "binary-only package", "should NOT want to rebuild p1 (first)")
4248 tg.runFail("install", "p2")
4249 tg.grepStderr("p1: binary-only packages are no longer supported", "did not report error for binary-only p1")
4251 tg.run("list", "-deps", "-f", "{{.ImportPath}}: {{.BinaryOnly}}", "p2")
4252 tg.grepStdout("p1: true", "p1 not listed as BinaryOnly")
4253 tg.grepStdout("p2: false", "p2 listed as BinaryOnly")
4256 // Issue 16050 and 21884.
4257 func TestLinkSysoFiles(t *testing.T) {
4258 if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
4259 t.Skip("not linux/amd64")
4265 tg.tempDir("src/syso")
4266 tg.tempFile("src/syso/a.syso", ``)
4267 tg.tempFile("src/syso/b.go", `package syso`)
4268 tg.setenv("GOPATH", tg.path("."))
4270 // We should see the .syso file regardless of the setting of
4273 tg.setenv("CGO_ENABLED", "1")
4274 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4275 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1")
4277 tg.setenv("CGO_ENABLED", "0")
4278 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4279 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0")
4281 tg.setenv("CGO_ENABLED", "1")
4282 tg.run("list", "-msan", "-f", "{{.SysoFiles}}", "syso")
4283 tg.grepStdoutNot("a.syso", "unexpected syso file with -msan")
4287 func TestGenerateUsesBuildContext(t *testing.T) {
4288 if runtime.GOOS == "windows" {
4289 t.Skip("this test won't run under Windows")
4295 tg.tempDir("src/gen")
4296 tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n")
4297 tg.setenv("GOPATH", tg.path("."))
4299 tg.setenv("GOOS", "linux")
4300 tg.setenv("GOARCH", "amd64")
4301 tg.run("generate", "gen")
4302 tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination")
4304 tg.setenv("GOOS", "darwin")
4305 tg.setenv("GOARCH", "386")
4306 tg.run("generate", "gen")
4307 tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination")
4310 // Issue 14450: go get -u .../ tried to import not downloaded package
4311 func TestGoGetUpdateWithWildcard(t *testing.T) {
4312 testenv.MustHaveExternalNetwork(t)
4313 testenv.MustHaveExecPath(t, "git")
4319 tg.setenv("GOPATH", tg.path("."))
4320 const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a"
4321 tg.run("get", aPkgImportPath)
4322 tg.runFail("get", "-u", ".../")
4323 tg.grepStderr("cannot find package.*d-dependency/e", "should have detected e missing")
4325 // Even though get -u failed, the source for others should be downloaded.
4326 var expectedPkgPaths = []string{
4327 "src/github.com/tmwh/go-get-issue-14450/b",
4328 "src/github.com/tmwh/go-get-issue-14450-b-dependency/c",
4329 "src/github.com/tmwh/go-get-issue-14450-b-dependency/d",
4332 for _, importPath := range expectedPkgPaths {
4333 _, err := os.Stat(tg.path(importPath))
4336 const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e"
4337 tg.mustNotExist(tg.path(notExpectedPkgPath))
4340 func TestGoEnv(t *testing.T) {
4344 tg.setenv("GOOS", "freebsd") // to avoid invalid pair errors
4345 tg.setenv("GOARCH", "arm")
4346 tg.run("env", "GOARCH")
4347 tg.grepStdout("^arm$", "GOARCH not honored")
4349 tg.run("env", "GCCGO")
4350 tg.grepStdout(".", "GCCGO unexpectedly empty")
4352 tg.run("env", "CGO_CFLAGS")
4353 tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty")
4355 tg.setenv("CGO_CFLAGS", "-foobar")
4356 tg.run("env", "CGO_CFLAGS")
4357 tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored")
4359 tg.setenv("CC", "gcc -fmust -fgo -ffaster")
4361 tg.grepStdout("gcc", "CC not found")
4362 tg.run("env", "GOGCCFLAGS")
4363 tg.grepStdout("-ffaster", "CC arguments not found")
4367 noMatchesPattern = `(?m)^ok.*\[no tests to run\]`
4368 okPattern = `(?m)^ok`
4371 func TestMatchesNoTests(t *testing.T) {
4374 // TODO: tg.parallel()
4375 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go")
4376 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4379 func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) {
4383 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4384 tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror")
4385 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4386 tg.grepBoth("FAIL", "go test did not say FAIL")
4389 func TestMatchesNoBenchmarksIsOK(t *testing.T) {
4392 // TODO: tg.parallel()
4393 tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go")
4394 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4395 tg.grepBoth(okPattern, "go test did not say ok")
4398 func TestMatchesOnlyExampleIsOK(t *testing.T) {
4401 // TODO: tg.parallel()
4402 tg.run("test", "-run", "Example", "testdata/example1_test.go")
4403 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4404 tg.grepBoth(okPattern, "go test did not say ok")
4407 func TestMatchesOnlyBenchmarkIsOK(t *testing.T) {
4410 // TODO: tg.parallel()
4411 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4412 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4413 tg.grepBoth(okPattern, "go test did not say ok")
4416 func TestBenchmarkLabels(t *testing.T) {
4419 // TODO: tg.parallel()
4420 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4421 tg.run("test", "-run", "^$", "-bench", ".", "bench")
4422 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4423 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4424 tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench")
4425 tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times")
4428 func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) {
4431 // TODO: tg.parallel()
4432 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4433 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4434 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4435 tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:")
4438 func TestMatchesOnlyTestIsOK(t *testing.T) {
4441 // TODO: tg.parallel()
4442 tg.run("test", "-run", "Test", "testdata/standalone_test.go")
4443 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4444 tg.grepBoth(okPattern, "go test did not say ok")
4447 func TestMatchesNoTestsWithSubtests(t *testing.T) {
4450 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go")
4451 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4454 func TestMatchesNoSubtestsMatch(t *testing.T) {
4457 tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go")
4458 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4461 func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) {
4464 tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go")
4465 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4466 tg.grepBoth("FAIL", "go test did not say FAIL")
4469 func TestMatchesOnlySubtestIsOK(t *testing.T) {
4472 tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go")
4473 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4474 tg.grepBoth(okPattern, "go test did not say ok")
4477 func TestMatchesNoSubtestsParallel(t *testing.T) {
4480 tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go")
4481 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4484 func TestMatchesOnlySubtestParallelIsOK(t *testing.T) {
4487 tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go")
4488 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4489 tg.grepBoth(okPattern, "go test did not say ok")
4493 func TestBenchTimeout(t *testing.T) {
4497 tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go")
4501 func TestWriteProfilesOnTimeout(t *testing.T) {
4505 tg.tempDir("profiling")
4506 tg.tempFile("profiling/timeouttest_test.go", `package timeouttest_test
4509 func TestSleep(t *testing.T) { time.Sleep(time.Second) }`)
4510 tg.cd(tg.path("profiling"))
4513 "-cpuprofile", tg.path("profiling/cpu.pprof"), "-memprofile", tg.path("profiling/mem.pprof"),
4515 tg.mustHaveContent(tg.path("profiling/cpu.pprof"))
4516 tg.mustHaveContent(tg.path("profiling/mem.pprof"))
4519 func TestLinkXImportPathEscape(t *testing.T) {
4520 // golang.org/issue/16710
4521 skipIfGccgo(t, "gccgo does not support -ldflags -X")
4526 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4527 exe := tg.path("linkx" + exeSuffix)
4528 tg.creatingTemp(exe)
4529 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main")
4530 out, err := exec.Command(exe).CombinedOutput()
4534 if string(out) != "linkXworked\n" {
4535 tg.t.Log(string(out))
4536 tg.t.Fatal(`incorrect output: expected "linkXworked\n"`)
4541 func TestLdBindNow(t *testing.T) {
4545 tg.setenv("LD_BIND_NOW", "1")
4550 // This is really a cmd/asm issue but this is a convenient place to test it.
4551 func TestConcurrentAsm(t *testing.T) {
4552 skipIfGccgo(t, "gccgo does not use cmd/asm")
4556 asm := `DATA ·constants<>+0x0(SB)/8,$0
4557 GLOBL ·constants<>(SB),8,$8
4559 tg.tempFile("go/src/p/a.s", asm)
4560 tg.tempFile("go/src/p/b.s", asm)
4561 tg.tempFile("go/src/p/p.go", `package p`)
4562 tg.setenv("GOPATH", tg.path("go"))
4563 tg.run("build", "p")
4567 func TestDotDotDotOutsideGOPATH(t *testing.T) {
4571 tg.tempFile("pkgs/a.go", `package x`)
4572 tg.tempFile("pkgs/a_test.go", `package x_test
4574 func TestX(t *testing.T) {}`)
4576 tg.tempFile("pkgs/a/a.go", `package a`)
4577 tg.tempFile("pkgs/a/a_test.go", `package a_test
4579 func TestA(t *testing.T) {}`)
4581 tg.cd(tg.path("pkgs"))
4582 tg.run("build", "./...")
4583 tg.run("test", "./...")
4584 tg.run("list", "./...")
4585 tg.grepStdout("pkgs$", "expected package not listed")
4586 tg.grepStdout("pkgs/a", "expected package not listed")
4590 func TestFFLAGS(t *testing.T) {
4592 t.Skip("skipping because cgo not enabled")
4599 tg.tempFile("p/src/p/main.go", `package main
4600 // #cgo FFLAGS: -no-such-fortran-flag
4604 tg.tempFile("p/src/p/a.f", `! comment`)
4605 tg.setenv("GOPATH", tg.path("p"))
4607 // This should normally fail because we are passing an unknown flag,
4608 // but issue #19080 points to Fortran compilers that succeed anyhow.
4609 // To work either way we call doRun directly rather than run or runFail.
4610 tg.doRun([]string{"build", "-x", "p"})
4612 tg.grepStderr("no-such-fortran-flag", `missing expected "-no-such-fortran-flag"`)
4616 // This is really a cmd/link issue but this is a convenient place to test it.
4617 func TestDuplicateGlobalAsmSymbols(t *testing.T) {
4618 skipIfGccgo(t, "gccgo does not use cmd/asm")
4620 if runtime.GOARCH != "386" && runtime.GOARCH != "amd64" {
4621 t.Skipf("skipping test on %s", runtime.GOARCH)
4624 t.Skip("skipping because cgo not enabled")
4632 #include "textflag.h"
4634 DATA sym<>+0x0(SB)/8,$0
4635 GLOBL sym<>(SB),(NOPTR+RODATA),$8
4637 TEXT ·Data(SB),NOSPLIT,$0
4642 tg.tempFile("go/src/a/a.s", asm)
4643 tg.tempFile("go/src/a/a.go", `package a; func Data() uint8`)
4644 tg.tempFile("go/src/b/b.s", asm)
4645 tg.tempFile("go/src/b/b.go", `package b; func Data() uint8`)
4646 tg.tempFile("go/src/p/p.go", `
4652 _ = a.Data() + b.Data()
4655 tg.setenv("GOPATH", tg.path("go"))
4656 exe := tg.path("p.exe")
4657 tg.creatingTemp(exe)
4658 tg.run("build", "-o", exe, "p")
4661 func TestBuildTagsNoComma(t *testing.T) {
4662 skipIfGccgo(t, "gccgo has no standard packages")
4666 tg.setenv("GOPATH", tg.path("go"))
4667 tg.run("build", "-tags", "tag1 tag2", "math")
4668 tg.runFail("build", "-tags", "tag1,tag2 tag3", "math")
4669 tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
4672 func copyFile(src, dst string, perm os.FileMode) error {
4673 sf, err := os.Open(src)
4679 df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
4684 _, err = io.Copy(df, sf)
4692 func TestExecutableGOROOT(t *testing.T) {
4693 skipIfGccgo(t, "gccgo has no GOROOT")
4694 if runtime.GOOS == "openbsd" {
4695 t.Skipf("test case does not work on %s, missing os.Executable", runtime.GOOS)
4698 // Env with no GOROOT.
4700 for _, e := range os.Environ() {
4701 if !strings.HasPrefix(e, "GOROOT=") {
4702 env = append(env, e)
4706 check := func(t *testing.T, exe, want string) {
4707 cmd := exec.Command(exe, "env", "GOROOT")
4709 out, err := cmd.CombinedOutput()
4711 t.Fatalf("%s env GOROOT: %v, %s", exe, err, out)
4713 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4717 want, err = filepath.EvalSymlinks(want)
4721 if !strings.EqualFold(goroot, want) {
4722 t.Errorf("go env GOROOT:\nhave %s\nwant %s", goroot, want)
4724 t.Logf("go env GOROOT: %s", goroot)
4728 // Note: Must not call tg methods inside subtests: tg is attached to outer t.
4733 tg.tempDir("new/bin")
4734 newGoTool := tg.path("new/bin/go" + exeSuffix)
4735 tg.must(copyFile(tg.goTool(), newGoTool, 0775))
4736 newRoot := tg.path("new")
4738 t.Run("RelocatedExe", func(t *testing.T) {
4739 // Should fall back to default location in binary,
4740 // which is the GOROOT we used when building testgo.exe.
4741 check(t, newGoTool, testGOROOT)
4744 // If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT,
4745 // so it should find the new tree.
4746 tg.tempDir("new/pkg/tool")
4747 t.Run("RelocatedTree", func(t *testing.T) {
4748 check(t, newGoTool, newRoot)
4751 tg.tempDir("other/bin")
4752 symGoTool := tg.path("other/bin/go" + exeSuffix)
4754 // Symlink into go tree should still find go tree.
4755 t.Run("SymlinkedExe", func(t *testing.T) {
4756 testenv.MustHaveSymlink(t)
4757 if err := os.Symlink(newGoTool, symGoTool); err != nil {
4760 check(t, symGoTool, newRoot)
4763 tg.must(robustio.RemoveAll(tg.path("new/pkg")))
4765 // Binaries built in the new tree should report the
4766 // new tree when they call runtime.GOROOT.
4767 t.Run("RuntimeGoroot", func(t *testing.T) {
4768 // Build a working GOROOT the easy way, with symlinks.
4769 testenv.MustHaveSymlink(t)
4770 if err := os.Symlink(filepath.Join(testGOROOT, "src"), tg.path("new/src")); err != nil {
4773 if err := os.Symlink(filepath.Join(testGOROOT, "pkg"), tg.path("new/pkg")); err != nil {
4777 cmd := exec.Command(newGoTool, "run", "testdata/print_goroot.go")
4779 out, err := cmd.CombinedOutput()
4781 t.Fatalf("%s run testdata/print_goroot.go: %v, %s", newGoTool, err, out)
4783 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4787 want, err := filepath.EvalSymlinks(tg.path("new"))
4791 if !strings.EqualFold(goroot, want) {
4792 t.Errorf("go run testdata/print_goroot.go:\nhave %s\nwant %s", goroot, want)
4794 t.Logf("go run testdata/print_goroot.go: %s", goroot)
4799 func TestNeedVersion(t *testing.T) {
4800 skipIfGccgo(t, "gccgo does not use cmd/compile")
4804 tg.tempFile("goversion.go", `package main; func main() {}`)
4805 path := tg.path("goversion.go")
4806 tg.setenv("TESTGO_VERSION", "go1.testgo")
4807 tg.runFail("run", path)
4808 tg.grepStderr("compile", "does not match go tool version")
4811 // Test that user can override default code generation flags.
4812 func TestUserOverrideFlags(t *testing.T) {
4813 skipIfGccgo(t, "gccgo does not use -gcflags")
4815 t.Skip("skipping because cgo not enabled")
4817 if runtime.GOOS != "linux" {
4818 // We are testing platform-independent code, so it's
4819 // OK to skip cases that work differently.
4820 t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS)
4825 // Don't call tg.parallel, as creating override.h and override.a may
4826 // confuse other tests.
4827 tg.tempFile("override.go", `package main
4835 tg.creatingTemp("override.a")
4836 tg.creatingTemp("override.h")
4837 tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=all=-shared=false", tg.path("override.go"))
4838 tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag")
4841 func TestCgoFlagContainsSpace(t *testing.T) {
4844 t.Skip("skipping because cgo not enabled")
4851 tg.tempFile("main.go", `package main
4852 // #cgo CFLAGS: -I"c flags"
4853 // #cgo LDFLAGS: -L"ld flags"
4857 tg.run("run", "-x", "main.go")
4858 tg.grepStderr(`"-I[^"]+c flags"`, "did not find quoted c flags")
4859 tg.grepStderrNot(`"-I[^"]+c flags".*"-I[^"]+c flags"`, "found too many quoted c flags")
4860 tg.grepStderr(`"-L[^"]+ld flags"`, "did not find quoted ld flags")
4861 tg.grepStderrNot(`"-L[^"]+c flags".*"-L[^"]+c flags"`, "found too many quoted ld flags")
4865 func TestGoTestRaceCoverModeFailures(t *testing.T) {
4868 t.Skip("skipping because race detector not supported")
4874 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4876 tg.run("test", "testrace")
4878 tg.runFail("test", "-race", "-covermode=set", "testrace")
4879 tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed")
4880 tg.grepBothNot("PASS", "something passed")
4883 // Issue 9737: verify that GOARM and GO386 affect the computed build ID.
4884 func TestBuildIDContainsArchModeEnv(t *testing.T) {
4885 if testing.Short() {
4886 t.Skip("skipping in short mode")
4890 testWith := func(before, after func()) func(*testing.T) {
4891 return func(t *testing.T) {
4894 tg.tempFile("src/mycmd/x.go", `package main
4896 tg.setenv("GOPATH", tg.path("."))
4898 tg.cd(tg.path("src/mycmd"))
4899 tg.setenv("GOOS", "linux")
4901 tg.run("install", "mycmd")
4903 tg.wantStale("mycmd", "stale dependency", "should be stale after environment variable change")
4907 t.Run("386", testWith(func() {
4908 tg.setenv("GOARCH", "386")
4909 tg.setenv("GO386", "387")
4911 tg.setenv("GO386", "sse2")
4914 t.Run("arm", testWith(func() {
4915 tg.setenv("GOARCH", "arm")
4916 tg.setenv("GOARM", "5")
4918 tg.setenv("GOARM", "7")
4922 func TestTestRegexps(t *testing.T) {
4925 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4926 tg.run("test", "-cpu=1", "-run=X/Y", "-bench=X/Y", "-count=2", "-v", "testregexp")
4928 for _, line := range strings.SplitAfter(tg.getStdout(), "\n") {
4929 if strings.Contains(line, "=== RUN") || strings.Contains(line, "--- BENCH") || strings.Contains(line, "LOG") {
4930 lines = append(lines, line)
4935 // TestX is run, twice
4936 // TestX/Y is run, twice
4937 // TestXX is run, twice
4939 // BenchmarkX is run but only with N=1, once
4940 // BenchmarkXX is run but only with N=1, once
4941 // BenchmarkX/Y is run in full, twice
4942 want := `=== RUN TestX
4944 x_test.go:6: LOG: X running
4945 x_test.go:8: LOG: Y running
4947 z_test.go:10: LOG: XX running
4950 x_test.go:6: LOG: X running
4951 x_test.go:8: LOG: Y running
4953 z_test.go:10: LOG: XX running
4954 --- BENCH: BenchmarkX/Y
4955 x_test.go:15: LOG: Y running N=1
4956 x_test.go:15: LOG: Y running N=100
4957 x_test.go:15: LOG: Y running N=10000
4958 x_test.go:15: LOG: Y running N=1000000
4959 x_test.go:15: LOG: Y running N=100000000
4960 x_test.go:15: LOG: Y running N=1000000000
4961 --- BENCH: BenchmarkX/Y
4962 x_test.go:15: LOG: Y running N=1
4963 x_test.go:15: LOG: Y running N=100
4964 x_test.go:15: LOG: Y running N=10000
4965 x_test.go:15: LOG: Y running N=1000000
4966 x_test.go:15: LOG: Y running N=100000000
4967 x_test.go:15: LOG: Y running N=1000000000
4968 --- BENCH: BenchmarkX
4969 x_test.go:13: LOG: X running N=1
4970 --- BENCH: BenchmarkXX
4971 z_test.go:18: LOG: XX running N=1
4974 have := strings.Join(lines, "")
4976 t.Errorf("reduced output:<<<\n%s>>> want:<<<\n%s>>>", have, want)
4980 func TestListTests(t *testing.T) {
4983 testWith := func(listName, expected string) func(*testing.T) {
4984 return func(t *testing.T) {
4987 tg.run("test", "./testdata/src/testlist/...", fmt.Sprintf("-list=%s", listName))
4988 tg.grepStdout(expected, fmt.Sprintf("-test.list=%s returned %q, expected %s", listName, tg.getStdout(), expected))
4992 t.Run("Test", testWith("Test", "TestSimple"))
4993 t.Run("Bench", testWith("Benchmark", "BenchmarkSimple"))
4994 t.Run("Example1", testWith("Example", "ExampleSimple"))
4995 t.Run("Example2", testWith("Example", "ExampleWithEmptyOutput"))
4998 func TestBuildmodePIE(t *testing.T) {
4999 if testing.Short() && testenv.Builder() == "" {
5000 t.Skipf("skipping in -short mode on non-builder")
5003 platform := fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
5005 case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x",
5006 "android/amd64", "android/arm", "android/arm64", "android/386",
5008 case "darwin/amd64":
5010 t.Skipf("skipping test because buildmode=pie is not supported on %s", platform)
5016 tg.tempFile("main.go", `package main; func main() { print("hello") }`)
5017 src := tg.path("main.go")
5018 obj := tg.path("main")
5019 tg.run("build", "-buildmode=pie", "-o", obj, src)
5021 switch runtime.GOOS {
5022 case "linux", "android", "freebsd":
5023 f, err := elf.Open(obj)
5028 if f.Type != elf.ET_DYN {
5029 t.Errorf("PIE type must be ET_DYN, but %s", f.Type)
5032 f, err := macho.Open(obj)
5037 if f.Flags&macho.FlagDyldLink == 0 {
5038 t.Error("PIE must have DyldLink flag, but not")
5040 if f.Flags&macho.FlagPIE == 0 {
5041 t.Error("PIE must have PIE flag, but not")
5044 panic("unreachable")
5047 out, err := exec.Command(obj).CombinedOutput()
5052 if string(out) != "hello" {
5053 t.Errorf("got %q; want %q", out, "hello")
5057 func TestExecBuildX(t *testing.T) {
5060 t.Skip("skipping because cgo not enabled")
5063 testenv.MustHaveExecPath(t, "/usr/bin/env")
5064 testenv.MustHaveExecPath(t, "bash")
5070 tg.setenv("GOCACHE", tg.path("cache"))
5072 tg.tempFile("main.go", `package main; import "C"; func main() { print("hello") }`)
5073 src := tg.path("main.go")
5074 obj := tg.path("main")
5075 tg.run("build", "-x", "-o", obj, src)
5076 sh := tg.path("test.sh")
5077 cmds := tg.getStderr()
5078 err := ioutil.WriteFile(sh, []byte("set -e\n"+cmds), 0666)
5083 out, err := exec.Command(obj).CombinedOutput()
5087 if string(out) != "hello" {
5088 t.Fatalf("got %q; want %q", out, "hello")
5091 err = os.Remove(obj)
5096 out, err = exec.Command("/usr/bin/env", "bash", "-x", sh).CombinedOutput()
5098 t.Fatalf("/bin/sh %s: %v\n%s", sh, err, out)
5100 t.Logf("shell output:\n%s", out)
5102 out, err = exec.Command(obj).CombinedOutput()
5106 if string(out) != "hello" {
5107 t.Fatalf("got %q; want %q", out, "hello")
5110 matches := regexp.MustCompile(`^WORK=(.*)\n`).FindStringSubmatch(cmds)
5111 if len(matches) == 0 {
5112 t.Fatal("no WORK directory")
5114 tg.must(robustio.RemoveAll(matches[1]))
5117 func TestParallelNumber(t *testing.T) {
5119 for _, n := range [...]string{"-1", "0"} {
5120 t.Run(n, func(t *testing.T) {
5123 tg.runFail("test", "-parallel", n, "testdata/standalone_parallel_sub_test.go")
5124 tg.grepBoth("-parallel can only be given", "go test -parallel with N<1 did not error")
5129 func TestWrongGOOSErrorBeforeLoadError(t *testing.T) {
5130 skipIfGccgo(t, "gccgo assumes cross-compilation is always possible")
5133 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5134 tg.setenv("GOOS", "windwos")
5135 tg.runFail("build", "exclude")
5136 tg.grepStderr("unsupported GOOS/GOARCH pair", "GOOS=windwos go build exclude did not report 'unsupported GOOS/GOARCH pair'")
5139 func TestUpxCompression(t *testing.T) {
5140 if runtime.GOOS != "linux" ||
5141 (runtime.GOARCH != "amd64" && runtime.GOARCH != "386") {
5142 t.Skipf("skipping upx test on %s/%s", runtime.GOOS, runtime.GOARCH)
5145 testenv.MustHaveExecPath(t, "upx")
5146 out, err := exec.Command("upx", "--version").CombinedOutput()
5148 t.Fatalf("upx --version failed: %v", err)
5151 // upx --version prints `upx <version>` in the first line of output:
5154 re := regexp.MustCompile(`([[:digit:]]+)\.([[:digit:]]+)`)
5155 upxVersion := re.FindStringSubmatch(string(out))
5156 if len(upxVersion) != 3 {
5157 t.Fatalf("bad upx version string: %s", upxVersion)
5160 major, err1 := strconv.Atoi(upxVersion[1])
5161 minor, err2 := strconv.Atoi(upxVersion[2])
5162 if err1 != nil || err2 != nil {
5163 t.Fatalf("bad upx version string: %s", upxVersion[0])
5166 // Anything below 3.94 is known not to work with go binaries
5167 if (major < 3) || (major == 3 && minor < 94) {
5168 t.Skipf("skipping because upx version %v.%v is too old", major, minor)
5174 tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello upx") }`)
5175 src := tg.path("main.go")
5176 obj := tg.path("main")
5177 tg.run("build", "-o", obj, src)
5179 out, err = exec.Command("upx", obj).CombinedOutput()
5181 t.Logf("executing upx\n%s\n", out)
5182 t.Fatalf("upx failed with %v", err)
5185 out, err = exec.Command(obj).CombinedOutput()
5188 t.Fatalf("running compressed go binary failed with error %s", err)
5190 if string(out) != "hello upx" {
5191 t.Fatalf("bad output from compressed go binary:\ngot %q; want %q", out, "hello upx")
5195 // Test that Go binaries can be run under QEMU in user-emulation mode
5196 // (See issue #13024).
5197 func TestQEMUUserMode(t *testing.T) {
5198 if testing.Short() && testenv.Builder() == "" {
5199 t.Skipf("skipping in -short mode on non-builder")
5202 testArchs := []struct {
5206 {"arm64", "aarch64"},
5211 tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello qemu-user") }`)
5213 src, obj := tg.path("main.go"), tg.path("main")
5215 for _, arch := range testArchs {
5217 t.Run(arch.g, func(t *testing.T) {
5218 qemu := "qemu-" + arch.qemu
5219 testenv.MustHaveExecPath(t, qemu)
5221 out, err := exec.Command(qemu, "--version").CombinedOutput()
5223 t.Fatalf("%s --version failed: %v", qemu, err)
5226 tg.setenv("GOARCH", arch.g)
5227 tg.run("build", "-o", obj, src)
5229 out, err = exec.Command(qemu, obj).CombinedOutput()
5231 t.Logf("%s output:\n%s\n", qemu, out)
5232 t.Fatalf("%s failed with %v", qemu, err)
5234 if want := "hello qemu-user"; string(out) != want {
5235 t.Errorf("bad output from %s:\ngot %s; want %s", qemu, out, want)
5241 func TestCacheListStale(t *testing.T) {
5243 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5244 t.Skip("GODEBUG gocacheverify")
5250 tg.setenv("GOCACHE", tg.path("cache"))
5251 tg.tempFile("gopath/src/p/p.go", "package p; import _ \"q\"; func F(){}\n")
5252 tg.tempFile("gopath/src/q/q.go", "package q; func F(){}\n")
5253 tg.tempFile("gopath/src/m/m.go", "package main; import _ \"q\"; func main(){}\n")
5255 tg.setenv("GOPATH", tg.path("gopath"))
5256 tg.run("install", "p", "m")
5257 tg.run("list", "-f={{.ImportPath}} {{.Stale}}", "m", "q", "p")
5258 tg.grepStdout("^m false", "m should not be stale")
5259 tg.grepStdout("^q true", "q should be stale")
5260 tg.grepStdout("^p false", "p should not be stale")
5263 func TestCacheCoverage(t *testing.T) {
5266 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5267 t.Skip("GODEBUG gocacheverify")
5273 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5276 tg.setenv("GOCACHE", tg.path("c1"))
5277 tg.run("test", "-cover", "-short", "strings")
5278 tg.run("test", "-cover", "-short", "math", "strings")
5281 func TestCacheVet(t *testing.T) {
5282 skipIfGccgo(t, "gccgo has no standard packages")
5287 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5288 t.Skip("GODEBUG gocacheverify")
5290 if testing.Short() {
5291 // In short mode, reuse cache.
5292 // Test failures may be masked if the cache has just the right entries already
5293 // (not a concern during all.bash, which runs in a clean cache).
5294 if cfg.Getenv("GOCACHE") == "off" {
5299 tg.setenv("GOCACHE", tg.path("cache"))
5302 // Check that second vet reuses cgo-derived inputs.
5303 // The first command could be build instead of vet,
5304 // except that if the cache is empty and there's a net.a
5305 // in GOROOT/pkg, the build will not bother to regenerate
5306 // and cache the cgo outputs, whereas vet always will.
5307 tg.run("vet", "os/user")
5308 tg.run("vet", "-x", "os/user")
5309 tg.grepStderrNot(`^(clang|gcc)`, "should not have run compiler")
5310 tg.grepStderrNot(`[\\/]cgo `, "should not have run cgo")
5313 func TestIssue22588(t *testing.T) {
5314 // Don't get confused by stderr coming from tools.
5319 if _, err := os.Stat("/usr/bin/time"); err != nil {
5323 tg.run("list", "-f={{.Stale}}", "runtime")
5324 tg.run("list", "-toolexec=/usr/bin/time", "-f={{.Stale}}", "runtime")
5325 tg.grepStdout("false", "incorrectly reported runtime as stale")
5328 func TestIssue22531(t *testing.T) {
5330 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5331 t.Skip("GODEBUG gocacheverify")
5337 tg.setenv("GOPATH", tg.tempdir)
5338 tg.setenv("GOCACHE", tg.path("cache"))
5339 tg.tempFile("src/m/main.go", "package main /* c1 */; func main() {}\n")
5340 tg.run("install", "-x", "m")
5341 tg.run("list", "-f", "{{.Stale}}", "m")
5342 tg.grepStdout("false", "reported m as stale after install")
5343 tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5345 // The link action ID did not include the full main build ID,
5346 // even though the full main build ID is written into the
5347 // eventual binary. That caused the following install to
5348 // be a no-op, thinking the gofmt binary was up-to-date,
5349 // even though .Stale could see it was not.
5350 tg.tempFile("src/m/main.go", "package main /* c2 */; func main() {}\n")
5351 tg.run("install", "-x", "m")
5352 tg.run("list", "-f", "{{.Stale}}", "m")
5353 tg.grepStdout("false", "reported m as stale after reinstall")
5354 tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5357 func TestIssue22596(t *testing.T) {
5359 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5360 t.Skip("GODEBUG gocacheverify")
5366 tg.setenv("GOCACHE", tg.path("cache"))
5367 tg.tempFile("gopath1/src/p/p.go", "package p; func F(){}\n")
5368 tg.tempFile("gopath2/src/p/p.go", "package p; func F(){}\n")
5370 tg.setenv("GOPATH", tg.path("gopath1"))
5371 tg.run("list", "-f={{.Target}}", "p")
5372 target1 := strings.TrimSpace(tg.getStdout())
5373 tg.run("install", "p")
5374 tg.wantNotStale("p", "", "p stale after install")
5376 tg.setenv("GOPATH", tg.path("gopath2"))
5377 tg.run("list", "-f={{.Target}}", "p")
5378 target2 := strings.TrimSpace(tg.getStdout())
5379 tg.must(os.MkdirAll(filepath.Dir(target2), 0777))
5380 tg.must(copyFile(target1, target2, 0666))
5381 tg.wantStale("p", "build ID mismatch", "p not stale after copy from gopath1")
5382 tg.run("install", "p")
5383 tg.wantNotStale("p", "", "p stale after install2")
5386 func TestTestCache(t *testing.T) {
5389 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5390 t.Skip("GODEBUG gocacheverify")
5396 tg.setenv("GOPATH", tg.tempdir)
5397 tg.setenv("GOCACHE", tg.path("cache"))
5399 if runtime.Compiler != "gccgo" {
5400 // timeout here should not affect result being cached
5401 // or being retrieved later.
5402 tg.run("test", "-x", "-timeout=10s", "errors")
5403 tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler")
5404 tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
5405 tg.grepStderr(`errors\.test`, "did not run test")
5407 tg.run("test", "-x", "errors")
5408 tg.grepStdout(`ok \terrors\t\(cached\)`, "did not report cached result")
5409 tg.grepStderrNot(`[\\/]compile|gccgo`, "incorrectly ran compiler")
5410 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly ran linker")
5411 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5412 tg.grepStderrNot("DO NOT USE", "poisoned action status leaked")
5414 // Even very low timeouts do not disqualify cached entries.
5415 tg.run("test", "-timeout=1ns", "-x", "errors")
5416 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5418 tg.run("clean", "-testcache")
5419 tg.run("test", "-x", "errors")
5420 tg.grepStderr(`errors\.test`, "did not run test")
5423 // The -p=1 in the commands below just makes the -x output easier to read.
5425 t.Log("\n\nINITIAL\n\n")
5427 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5428 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\nvar X = 1\n")
5429 tg.tempFile("src/t/t1/t1_test.go", "package t\nimport \"testing\"\nfunc Test1(*testing.T) {}\n")
5430 tg.tempFile("src/t/t2/t2_test.go", "package t\nimport _ \"p1\"\nimport \"testing\"\nfunc Test2(*testing.T) {}\n")
5431 tg.tempFile("src/t/t3/t3_test.go", "package t\nimport \"p1\"\nimport \"testing\"\nfunc Test3(t *testing.T) {t.Log(p1.X)}\n")
5432 tg.tempFile("src/t/t4/t4_test.go", "package t\nimport \"p2\"\nimport \"testing\"\nfunc Test4(t *testing.T) {t.Log(p2.X)}")
5433 tg.run("test", "-x", "-v", "-short", "t/...")
5435 t.Log("\n\nREPEAT\n\n")
5437 tg.run("test", "-x", "-v", "-short", "t/...")
5438 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5439 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5440 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5441 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5442 tg.grepStderrNot(`[\\/](compile|gccgo) `, "incorrectly ran compiler")
5443 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5444 tg.grepStderrNot(`p[0-9]\.test`, "incorrectly ran test")
5446 t.Log("\n\nCOMMENT\n\n")
5448 // Changing the program text without affecting the compiled package
5449 // should result in the package being rebuilt but nothing more.
5450 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 01\n")
5451 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5452 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5453 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5454 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5455 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5456 tg.grepStderrNot(`([\\/](compile|gccgo) ).*t[0-9]_test\.go`, "incorrectly ran compiler")
5457 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5458 tg.grepStderrNot(`t[0-9]\.test.*test\.short`, "incorrectly ran test")
5460 t.Log("\n\nCHANGE\n\n")
5462 // Changing the actual package should have limited effects.
5463 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 02\n")
5464 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5466 // p2 should have been rebuilt.
5467 tg.grepStderr(`([\\/]compile|gccgo).*p2.go`, "did not recompile p2")
5469 // t1 does not import anything, should not have been rebuilt.
5470 tg.grepStderrNot(`([\\/]compile|gccgo).*t1_test.go`, "incorrectly recompiled t1")
5471 tg.grepStderrNot(`([\\/]link|gccgo).*t1_test`, "incorrectly relinked t1_test")
5472 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t/t1")
5474 // t2 imports p1 and must be rebuilt and relinked,
5475 // but the change should not have any effect on the test binary,
5476 // so the test should not have been rerun.
5477 tg.grepStderr(`([\\/]compile|gccgo).*t2_test.go`, "did not recompile t2")
5478 tg.grepStderr(`([\\/]link|gccgo).*t2\.test`, "did not relink t2_test")
5479 // This check does not currently work with gccgo, as garbage
5480 // collection of unused variables is not turned on by default.
5481 if runtime.Compiler != "gccgo" {
5482 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t/t2")
5485 // t3 imports p1, and changing X changes t3's test binary.
5486 tg.grepStderr(`([\\/]compile|gccgo).*t3_test.go`, "did not recompile t3")
5487 tg.grepStderr(`([\\/]link|gccgo).*t3\.test`, "did not relink t3_test")
5488 tg.grepStderr(`t3\.test.*-test.short`, "did not rerun t3_test")
5489 tg.grepStdoutNot(`ok \tt/t3\t\(cached\)`, "reported cached t3_test result")
5491 // t4 imports p2, but p2 did not change, so t4 should be relinked, not recompiled,
5493 tg.grepStderrNot(`([\\/]compile|gccgo).*t4_test.go`, "incorrectly recompiled t4")
5494 tg.grepStderr(`([\\/]link|gccgo).*t4\.test`, "did not relink t4_test")
5495 // This check does not currently work with gccgo, as garbage
5496 // collection of unused variables is not turned on by default.
5497 if runtime.Compiler != "gccgo" {
5498 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t/t4")
5502 func TestTestCacheInputs(t *testing.T) {
5505 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5506 t.Skip("GODEBUG gocacheverify")
5512 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5513 tg.setenv("GOCACHE", tg.path("cache"))
5515 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5516 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"))
5517 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("x"), 0644))
5518 old := time.Now().Add(-1 * time.Minute)
5519 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5520 info, err := os.Stat(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5524 t.Logf("file.txt: old=%v, info.ModTime=%v", old, info.ModTime()) // help debug when Chtimes lies about succeeding
5525 tg.setenv("TESTKEY", "x")
5527 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), []byte("#!/bin/sh\nexit 0\n"), 0755))
5528 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old, old))
5530 tg.run("test", "testcache")
5531 tg.run("test", "testcache")
5532 tg.grepStdout(`\(cached\)`, "did not cache")
5534 tg.setenv("TESTKEY", "y")
5535 tg.run("test", "testcache")
5536 tg.grepStdoutNot(`\(cached\)`, "did not notice env var change")
5537 tg.run("test", "testcache")
5538 tg.grepStdout(`\(cached\)`, "did not cache")
5540 tg.run("test", "testcache", "-run=FileSize")
5541 tg.run("test", "testcache", "-run=FileSize")
5542 tg.grepStdout(`\(cached\)`, "did not cache")
5543 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxx"), 0644))
5544 tg.run("test", "testcache", "-run=FileSize")
5545 tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5546 tg.run("test", "testcache", "-run=FileSize")
5547 tg.grepStdout(`\(cached\)`, "did not cache")
5549 tg.run("test", "testcache", "-run=Chdir")
5550 tg.run("test", "testcache", "-run=Chdir")
5551 tg.grepStdout(`\(cached\)`, "did not cache")
5552 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxxxx"), 0644))
5553 tg.run("test", "testcache", "-run=Chdir")
5554 tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5555 tg.run("test", "testcache", "-run=Chdir")
5556 tg.grepStdout(`\(cached\)`, "did not cache")
5558 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5559 tg.run("test", "testcache", "-run=FileContent")
5560 tg.run("test", "testcache", "-run=FileContent")
5561 tg.grepStdout(`\(cached\)`, "did not cache")
5562 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("yyy"), 0644))
5563 old2 := old.Add(10 * time.Second)
5564 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old2, old2))
5565 tg.run("test", "testcache", "-run=FileContent")
5566 tg.grepStdoutNot(`\(cached\)`, "did not notice file content change")
5567 tg.run("test", "testcache", "-run=FileContent")
5568 tg.grepStdout(`\(cached\)`, "did not cache")
5570 tg.run("test", "testcache", "-run=DirList")
5571 tg.run("test", "testcache", "-run=DirList")
5572 tg.grepStdout(`\(cached\)`, "did not cache")
5573 tg.must(os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt")))
5574 tg.run("test", "testcache", "-run=DirList")
5575 tg.grepStdoutNot(`\(cached\)`, "did not notice directory change")
5576 tg.run("test", "testcache", "-run=DirList")
5577 tg.grepStdout(`\(cached\)`, "did not cache")
5579 tg.tempFile("file.txt", "")
5580 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"), []byte(`package testcache
5587 func TestExternalFile(t *testing.T) {
5588 os.Open(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5589 _, err := os.Stat(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5595 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"))
5596 tg.run("test", "testcache", "-run=ExternalFile")
5597 tg.run("test", "testcache", "-run=ExternalFile")
5598 tg.grepStdout(`\(cached\)`, "did not cache")
5599 tg.must(os.Remove(filepath.Join(tg.tempdir, "file.txt")))
5600 tg.run("test", "testcache", "-run=ExternalFile")
5601 tg.grepStdout(`\(cached\)`, "did not cache")
5603 switch runtime.GOOS {
5604 case "nacl", "plan9", "windows":
5607 tg.run("test", "testcache", "-run=Exec")
5608 tg.run("test", "testcache", "-run=Exec")
5609 tg.grepStdout(`\(cached\)`, "did not cache")
5610 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old2, old2))
5611 tg.run("test", "testcache", "-run=Exec")
5612 tg.grepStdoutNot(`\(cached\)`, "did not notice script change")
5613 tg.run("test", "testcache", "-run=Exec")
5614 tg.grepStdout(`\(cached\)`, "did not cache")
5618 func TestTestVet(t *testing.T) {
5624 tg.tempFile("p1_test.go", `
5627 func Test(t *testing.T) {
5628 t.Logf("%d") // oops
5632 tg.runFail("test", tg.path("p1_test.go"))
5633 tg.grepStderr(`Logf format %d`, "did not diagnose bad Logf")
5634 tg.run("test", "-vet=off", tg.path("p1_test.go"))
5635 tg.grepStdout(`^ok`, "did not print test summary")
5637 tg.tempFile("p1.go", `
5641 fmt.Printf("%d") // oops
5644 tg.runFail("test", tg.path("p1.go"))
5645 tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5646 tg.run("test", "-x", "-vet=shift", tg.path("p1.go"))
5647 tg.grepStderr(`[\\/]vet.*-shift`, "did not run vet with -shift")
5648 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5649 tg.run("test", "-vet=off", tg.path("p1.go"))
5650 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5652 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5653 tg.run("test", "vetcycle") // must not fail; #22890
5655 tg.runFail("test", "vetfail/...")
5656 tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5657 tg.grepStdout(`ok\s+vetfail/p2`, "did not run vetfail/p2")
5659 // Use -a so that we need to recompute the vet-specific export data for
5661 tg.run("test", "-a", "vetfail/p2")
5662 tg.grepStderrNot(`invalid.*constraint`, "did diagnose bad build constraint in vetxonly mode")
5665 func TestTestSkipVetAfterFailedBuild(t *testing.T) {
5670 tg.tempFile("x_test.go", `package x
5676 tg.runFail("test", tg.path("x_test.go"))
5677 tg.grepStderrNot(`vet`, "vet should be skipped after the failed build")
5680 func TestTestVetRebuild(t *testing.T) {
5686 // golang.org/issue/23701.
5687 // b_test imports b with augmented method from export_test.go.
5688 // b_test also imports a, which imports b.
5689 // Must not accidentally see un-augmented b propagate through a to b_test.
5690 tg.tempFile("src/a/a.go", `package a
5693 func (*Type) M() b.T {return 0}
5695 tg.tempFile("src/b/b.go", `package b
5697 type I interface {M() T}
5699 tg.tempFile("src/b/export_test.go", `package b
5700 func (*T) Method() *T { return nil }
5702 tg.tempFile("src/b/b_test.go", `package b_test
5708 func TestBroken(t *testing.T) {
5715 tg.setenv("GOPATH", tg.path("."))
5720 func TestInstallDeps(t *testing.T) {
5726 tg.setenv("GOPATH", tg.tempdir)
5728 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5729 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\n")
5730 tg.tempFile("src/main1/main.go", "package main\nimport _ \"p2\"\nfunc main() {}\n")
5732 tg.run("list", "-f={{.Target}}", "p1")
5733 p1 := strings.TrimSpace(tg.getStdout())
5734 tg.run("list", "-f={{.Target}}", "p2")
5735 p2 := strings.TrimSpace(tg.getStdout())
5736 tg.run("list", "-f={{.Target}}", "main1")
5737 main1 := strings.TrimSpace(tg.getStdout())
5739 tg.run("install", "main1")
5745 tg.run("install", "p2")
5749 // don't let install -i overwrite runtime
5750 tg.wantNotStale("runtime", "", "must be non-stale before install -i")
5752 tg.run("install", "-i", "main1")
5754 tg.must(os.Remove(p1))
5756 tg.run("install", "-i", "p2")
5760 func TestFmtLoadErrors(t *testing.T) {
5763 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5764 tg.runFail("fmt", "does-not-exist")
5765 tg.run("fmt", "-n", "exclude")
5768 func TestGoTestMinusN(t *testing.T) {
5769 // Intent here is to verify that 'go test -n' works without crashing.
5770 // This reuses flag_test.go, but really any test would do.
5773 tg.run("test", "testdata/flag_test.go", "-n", "-args", "-v=7")
5776 func TestGoTestJSON(t *testing.T) {
5777 skipIfGccgo(t, "gccgo does not have standard packages")
5784 tg.setenv("GOCACHE", tg.tempdir)
5785 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5787 // It would be nice to test that the output is interlaced
5788 // but it seems to be impossible to do that in a short test
5789 // that isn't also flaky. Just check that we get JSON output.
5790 tg.run("test", "-json", "-short", "-v", "errors", "empty/pkg", "skipper")
5791 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5792 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5794 tg.grepStdout(`"Action":"output","Package":"empty/pkg","Output":".*no test files`, "did not see no test files print")
5795 tg.grepStdout(`"Action":"skip","Package":"empty/pkg"`, "did not see skip")
5797 tg.grepStdout(`"Action":"output","Package":"skipper","Test":"Test","Output":"--- SKIP:`, "did not see SKIP output")
5798 tg.grepStdout(`"Action":"skip","Package":"skipper","Test":"Test"`, "did not see skip result for Test")
5800 tg.run("test", "-json", "-short", "-v", "errors")
5801 tg.grepStdout(`"Action":"output","Package":"errors","Output":".*\(cached\)`, "did not see no cached output")
5803 tg.run("test", "-json", "-bench=NONE", "-short", "-v", "errors")
5804 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5805 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5807 tg.run("test", "-o", tg.path("errors.test.exe"), "-c", "errors")
5808 tg.run("tool", "test2json", "-p", "errors", tg.path("errors.test.exe"), "-test.v", "-test.short")
5809 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5810 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5811 tg.grepStdout(`\{"Action":"pass","Package":"errors"\}`, "did not see final pass")
5814 func TestFailFast(t *testing.T) {
5824 {"TestFailingA", true, 1},
5825 {"TestFailing[AB]", true, 1},
5826 {"TestFailing[AB]", false, 2},
5827 // mix with non-failing tests:
5828 {"TestA|TestFailing[AB]", true, 1},
5829 {"TestA|TestFailing[AB]", false, 2},
5830 // mix with parallel tests:
5831 {"TestFailingB|TestParallelFailingA", true, 2},
5832 {"TestFailingB|TestParallelFailingA", false, 2},
5833 {"TestFailingB|TestParallelFailing[AB]", true, 3},
5834 {"TestFailingB|TestParallelFailing[AB]", false, 3},
5835 // mix with parallel sub-tests
5836 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", true, 3},
5837 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", false, 5},
5838 {"TestParallelFailingSubtestsA", true, 1},
5840 {"TestParallelFailing[AB]", false, 2},
5841 // non-parallel subtests:
5842 {"TestFailingSubtestsA", true, 1},
5843 {"TestFailingSubtestsA", false, 2},
5845 {"TestFatal[CD]", true, 1},
5846 {"TestFatal[CD]", false, 2},
5849 for _, tt := range tests {
5850 t.Run(tt.run, func(t *testing.T) {
5851 tg.runFail("test", "./testdata/src/failfast_test.go", "-run="+tt.run, "-failfast="+strconv.FormatBool(tt.failfast))
5853 nfail := strings.Count(tg.getStdout(), "FAIL - ")
5855 if nfail != tt.nfail {
5856 t.Errorf("go test -run=%s -failfast=%t printed %d FAILs, want %d", tt.run, tt.failfast, nfail, tt.nfail)
5863 func TestImportPath(t *testing.T) {
5869 tg.tempFile("src/a/a.go", `
5883 tg.tempFile("src/a/a_test.go", `
5891 func TestV(t *testing.T) {
5897 tg.tempFile("src/a/p-1.0/p.go", `
5905 tg.setenv("GOPATH", tg.path("."))
5906 tg.run("build", "-o", tg.path("a.exe"), "a")
5910 func TestBadCommandLines(t *testing.T) {
5914 tg.tempFile("src/x/x.go", "package x\n")
5915 tg.setenv("GOPATH", tg.path("."))
5917 tg.run("build", "x")
5919 tg.tempFile("src/x/@y.go", "package x\n")
5920 tg.runFail("build", "x")
5921 tg.grepStderr("invalid input file name \"@y.go\"", "did not reject @y.go")
5922 tg.must(os.Remove(tg.path("src/x/@y.go")))
5924 tg.tempFile("src/x/-y.go", "package x\n")
5925 tg.runFail("build", "x")
5926 tg.grepStderr("invalid input file name \"-y.go\"", "did not reject -y.go")
5927 tg.must(os.Remove(tg.path("src/x/-y.go")))
5929 if runtime.Compiler == "gccgo" {
5930 tg.runFail("build", "-gccgoflags=all=@x", "x")
5932 tg.runFail("build", "-gcflags=all=@x", "x")
5934 tg.grepStderr("invalid command-line argument @x in command", "did not reject @x during exec")
5936 tg.tempFile("src/@x/x.go", "package x\n")
5937 tg.setenv("GOPATH", tg.path("."))
5938 tg.runFail("build", "@x")
5939 tg.grepStderr("invalid input directory name \"@x\"|cannot use path@version syntax", "did not reject @x directory")
5941 tg.tempFile("src/@x/y/y.go", "package y\n")
5942 tg.setenv("GOPATH", tg.path("."))
5943 tg.runFail("build", "@x/y")
5944 tg.grepStderr("invalid import path \"@x/y\"|cannot use path@version syntax", "did not reject @x/y import path")
5946 tg.tempFile("src/-x/x.go", "package x\n")
5947 tg.setenv("GOPATH", tg.path("."))
5948 tg.runFail("build", "--", "-x")
5949 tg.grepStderr("invalid input directory name \"-x\"", "did not reject -x directory")
5951 tg.tempFile("src/-x/y/y.go", "package y\n")
5952 tg.setenv("GOPATH", tg.path("."))
5953 tg.runFail("build", "--", "-x/y")
5954 tg.grepStderr("invalid import path \"-x/y\"", "did not reject -x/y import path")
5957 func TestBadCgoDirectives(t *testing.T) {
5965 tg.tempFile("src/x/x.go", "package x\n")
5966 tg.setenv("GOPATH", tg.path("."))
5968 if runtime.Compiler == "gc" {
5969 tg.tempFile("src/x/x.go", `package x
5971 //go:cgo_ldflag "-fplugin=foo.so"
5975 tg.runFail("build", "x")
5976 tg.grepStderr("//go:cgo_ldflag .* only allowed in cgo-generated code", "did not reject //go:cgo_ldflag directive")
5979 tg.must(os.Remove(tg.path("src/x/x.go")))
5980 tg.runFail("build", "x")
5981 tg.grepStderr("no Go files", "did not report missing source code")
5982 tg.tempFile("src/x/_cgo_yy.go", `package x
5984 //go:cgo_ldflag "-fplugin=foo.so"
5988 tg.runFail("build", "x")
5989 tg.grepStderr("no Go files", "did not report missing source code") // _* files are ignored...
5991 if runtime.Compiler == "gc" {
5992 tg.runFail("build", tg.path("src/x/_cgo_yy.go")) // ... but if forced, the comment is rejected
5993 // Actually, today there is a separate issue that _ files named
5994 // on the command line are ignored. Once that is fixed,
5995 // we want to see the cgo_ldflag error.
5996 tg.grepStderr("//go:cgo_ldflag only allowed in cgo-generated code|no Go files", "did not reject //go:cgo_ldflag directive")
5999 tg.must(os.Remove(tg.path("src/x/_cgo_yy.go")))
6001 tg.tempFile("src/x/x.go", "package x\n")
6002 tg.tempFile("src/x/y.go", `package x
6003 // #cgo CFLAGS: -fplugin=foo.so
6006 tg.runFail("build", "x")
6007 tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
6009 tg.tempFile("src/x/y.go", `package x
6010 // #cgo CFLAGS: -Ibar -fplugin=foo.so
6013 tg.runFail("build", "x")
6014 tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
6016 tg.tempFile("src/x/y.go", `package x
6017 // #cgo pkg-config: -foo
6020 tg.runFail("build", "x")
6021 tg.grepStderr("invalid pkg-config package name: -foo", "did not reject pkg-config: -foo")
6023 tg.tempFile("src/x/y.go", `package x
6024 // #cgo pkg-config: @foo
6027 tg.runFail("build", "x")
6028 tg.grepStderr("invalid pkg-config package name: @foo", "did not reject pkg-config: -foo")
6030 tg.tempFile("src/x/y.go", `package x
6031 // #cgo CFLAGS: @foo
6034 tg.runFail("build", "x")
6035 tg.grepStderr("invalid flag in #cgo CFLAGS: @foo", "did not reject @foo flag")
6037 tg.tempFile("src/x/y.go", `package x
6041 tg.runFail("build", "x")
6042 tg.grepStderr("invalid flag in #cgo CFLAGS: -D without argument", "did not reject trailing -I flag")
6044 // Note that -I @foo is allowed because we rewrite it into -I /path/to/src/@foo
6045 // before the check is applied. There's no such rewrite for -D.
6047 tg.tempFile("src/x/y.go", `package x
6048 // #cgo CFLAGS: -D @foo
6051 tg.runFail("build", "x")
6052 tg.grepStderr("invalid flag in #cgo CFLAGS: -D @foo", "did not reject -D @foo flag")
6054 tg.tempFile("src/x/y.go", `package x
6055 // #cgo CFLAGS: -D@foo
6058 tg.runFail("build", "x")
6059 tg.grepStderr("invalid flag in #cgo CFLAGS: -D@foo", "did not reject -D@foo flag")
6061 tg.setenv("CGO_CFLAGS", "-D@foo")
6062 tg.tempFile("src/x/y.go", `package x
6065 tg.run("build", "-n", "x")
6066 tg.grepStderr("-D@foo", "did not find -D@foo in commands")
6069 func TestTwoPkgConfigs(t *testing.T) {
6073 if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
6074 t.Skipf("no shell scripts on %s", runtime.GOOS)
6080 tg.tempFile("src/x/a.go", `package x
6081 // #cgo pkg-config: --static a
6084 tg.tempFile("src/x/b.go", `package x
6085 // #cgo pkg-config: --static a
6088 tg.tempFile("pkg-config.sh", `#!/bin/sh
6089 echo $* >>`+tg.path("pkg-config.out"))
6090 tg.must(os.Chmod(tg.path("pkg-config.sh"), 0755))
6091 tg.setenv("GOPATH", tg.path("."))
6092 tg.setenv("PKG_CONFIG", tg.path("pkg-config.sh"))
6093 tg.run("build", "x")
6094 out, err := ioutil.ReadFile(tg.path("pkg-config.out"))
6096 out = bytes.TrimSpace(out)
6097 want := "--cflags --static --static -- a a\n--libs --static --static -- a a"
6098 if !bytes.Equal(out, []byte(want)) {
6099 t.Errorf("got %q want %q", out, want)
6103 func TestCgoCache(t *testing.T) {
6112 tg.tempFile("src/x/a.go", `package main
6119 func main() { fmt.Println(C.val) }
6121 tg.setenv("GOPATH", tg.path("."))
6122 exe := tg.path("x.exe")
6123 tg.run("build", "-o", exe, "x")
6124 tg.setenv("CGO_LDFLAGS", "-lnosuchlibraryexists")
6125 tg.runFail("build", "-o", exe, "x")
6126 tg.grepStderr(`nosuchlibraryexists`, "did not run linker with changed CGO_LDFLAGS")
6130 func TestFilepathUnderCwdFormat(t *testing.T) {
6133 tg.run("test", "-x", "-cover", "log")
6134 tg.grepStderrNot(`\.log\.cover\.go`, "-x output should contain correctly formatted filepath under cwd")
6138 func TestDontReportRemoveOfEmptyDir(t *testing.T) {
6142 tg.tempFile("src/a/a.go", `package a`)
6143 tg.setenv("GOPATH", tg.path("."))
6144 tg.run("install", "-x", "a")
6145 tg.run("install", "-x", "a")
6146 // The second install should have printed only a WORK= line,
6148 if bytes.Count(tg.stdout.Bytes(), []byte{'\n'})+bytes.Count(tg.stderr.Bytes(), []byte{'\n'}) > 1 {
6149 t.Error("unnecessary output when installing installed package")
6154 func TestLinkerTmpDirIsDeleted(t *testing.T) {
6155 skipIfGccgo(t, "gccgo does not use cmd/link")
6157 t.Skip("skipping because cgo not enabled")
6164 tg.tempFile("a.go", `package main; import "C"; func main() {}`)
6165 tg.run("build", "-ldflags", "-v", "-o", os.DevNull, tg.path("a.go"))
6166 // Find line that has "host link:" in linker output.
6167 stderr := tg.getStderr()
6168 var hostLinkLine string
6169 for _, line := range strings.Split(stderr, "\n") {
6170 if !strings.Contains(line, "host link:") {
6176 if hostLinkLine == "" {
6177 t.Fatal(`fail to find with "host link:" string in linker output`)
6179 // Find parameter, like "/tmp/go-link-408556474/go.o" inside of
6180 // "host link:" line, and extract temp directory /tmp/go-link-408556474
6182 tmpdir := hostLinkLine
6183 i := strings.Index(tmpdir, `go.o"`)
6185 t.Fatalf(`fail to find "go.o" in "host link:" line %q`, hostLinkLine)
6187 tmpdir = tmpdir[:i-1]
6188 i = strings.LastIndex(tmpdir, `"`)
6190 t.Fatalf(`fail to find " in "host link:" line %q`, hostLinkLine)
6192 tmpdir = tmpdir[i+1:]
6193 // Verify that temp directory has been removed.
6194 _, err := os.Stat(tmpdir)
6196 t.Fatalf("temp directory %q has not been removed", tmpdir)
6198 if !os.IsNotExist(err) {
6199 t.Fatalf("Stat(%q) returns unexpected error: %v", tmpdir, err)
6203 func testCDAndGOPATHAreDifferent(tg *testgoData, cd, gopath string) {
6204 skipIfGccgo(tg.t, "gccgo does not support -ldflags -X")
6205 tg.setenv("GOPATH", gopath)
6208 exe := tg.path("dir/a.exe")
6212 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked")
6213 out, err := exec.Command(exe).CombinedOutput()
6217 if string(out) != "linkXworked\n" {
6218 tg.t.Errorf(`incorrect output with GOPATH=%q and CD=%q: expected "linkXworked\n", but have %q`, gopath, cd, string(out))
6222 func TestCDAndGOPATHAreDifferent(t *testing.T) {
6226 gopath := filepath.Join(tg.pwd(), "testdata")
6227 cd := filepath.Join(gopath, "src/my.pkg/main")
6229 testCDAndGOPATHAreDifferent(tg, cd, gopath)
6230 if runtime.GOOS == "windows" {
6231 testCDAndGOPATHAreDifferent(tg, cd, strings.ReplaceAll(gopath, `\`, `/`))
6232 testCDAndGOPATHAreDifferent(tg, cd, strings.ToUpper(gopath))
6233 testCDAndGOPATHAreDifferent(tg, cd, strings.ToLower(gopath))
6238 func TestGoTestWithoutTests(t *testing.T) {
6242 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
6243 tg.run("test", "testnorun")
6244 tg.grepStdout(`testnorun\t\[no test files\]`, "do not want test to run")
6248 func TestGoBuildDashODevNull(t *testing.T) {
6253 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
6254 tg.run("build", "-o", os.DevNull, filepath.Join(tg.pwd(), "testdata", "src", "hello", "hello.go"))
6255 tg.mustNotExist("hello")
6256 tg.mustNotExist("hello.exe")
6260 func TestCoverpkgTestOnly(t *testing.T) {
6261 skipIfGccgo(t, "gccgo has no cover tool")
6266 tg.tempFile("src/a/a.go", `package a
6270 tg.tempFile("src/atest/a_test.go", `
6272 import ( "a"; "testing" )
6273 func TestF(t *testing.T) { a.F(2) }
6275 tg.setenv("GOPATH", tg.path("."))
6276 tg.run("test", "-coverpkg=a", "atest")
6277 tg.grepStderrNot("no packages being tested depend on matches", "bad match message")
6278 tg.grepStdout("coverage: 100", "no coverage")