cmd/go: enable tests of vet tool
[official-gcc.git] / libgo / go / cmd / go / go_test.go
blob294541800afaeb5d0ae7779a4904dab14e8bff6a
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.
5 package main_test
7 import (
8 "bytes"
9 "debug/elf"
10 "debug/macho"
11 "fmt"
12 "go/format"
13 "internal/race"
14 "internal/testenv"
15 "io"
16 "io/ioutil"
17 "os"
18 "os/exec"
19 "path/filepath"
20 "regexp"
21 "runtime"
22 "strconv"
23 "strings"
24 "testing"
25 "time"
28 var (
29 canRun = true // whether we can run go or ./testgo
30 canRace = false // whether we can run the race detector
31 canCgo = false // whether we can use cgo
32 canMSan = false // whether we can run the memory sanitizer
34 exeSuffix string // ".exe" on Windows
36 skipExternal = false // skip external tests
39 func tooSlow(t *testing.T) {
40 if testing.Short() {
41 // In -short mode; skip test, except run it on the {darwin,linux,windows}/amd64 builders.
42 if testenv.Builder() != "" && runtime.GOARCH == "amd64" && (runtime.GOOS == "linux" || runtime.GOOS == "darwin" || runtime.GOOS == "windows") {
43 return
45 t.Skip("skipping test in -short mode")
49 func init() {
50 switch runtime.GOOS {
51 case "android", "nacl":
52 canRun = false
53 case "darwin":
54 switch runtime.GOARCH {
55 case "arm", "arm64":
56 canRun = false
58 case "linux":
59 switch runtime.GOARCH {
60 case "arm":
61 // many linux/arm machines are too slow to run
62 // the full set of external tests.
63 skipExternal = true
64 case "mips", "mipsle", "mips64", "mips64le":
65 // Also slow.
66 skipExternal = true
67 if testenv.Builder() != "" {
68 // On the builders, skip the cmd/go
69 // tests. They're too slow and already
70 // covered by other ports. There's
71 // nothing os/arch specific in the
72 // tests.
73 canRun = false
76 case "freebsd":
77 switch runtime.GOARCH {
78 case "arm":
79 // many freebsd/arm machines are too slow to run
80 // the full set of external tests.
81 skipExternal = true
82 canRun = false
84 case "plan9":
85 switch runtime.GOARCH {
86 case "arm":
87 // many plan9/arm machines are too slow to run
88 // the full set of external tests.
89 skipExternal = true
91 case "windows":
92 exeSuffix = ".exe"
96 // testGOROOT is the GOROOT to use when running testgo, a cmd/go binary
97 // build from this process's current GOROOT, but run from a different
98 // (temp) directory.
99 var testGOROOT string
101 var testCC string
103 // The TestMain function creates a go command for testing purposes and
104 // deletes it after the tests have been run.
105 func TestMain(m *testing.M) {
106 if os.Getenv("GO_GCFLAGS") != "" {
107 fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
108 fmt.Printf("cmd/go test is not compatible with $GO_GCFLAGS being set\n")
109 fmt.Printf("SKIP\n")
110 return
112 os.Unsetenv("GOROOT_FINAL")
114 if canRun {
115 args := []string{"build", "-tags", "testgo", "-o", "testgo" + exeSuffix}
116 if race.Enabled {
117 args = append(args, "-race")
119 gotool, err := testenv.GoTool()
120 if err != nil {
121 fmt.Fprintln(os.Stderr, err)
122 os.Exit(2)
125 goEnv := func(name string) string {
126 out, err := exec.Command(gotool, "env", name).CombinedOutput()
127 if err != nil {
128 fmt.Fprintf(os.Stderr, "go env %s: %v\n%s", name, err, out)
129 os.Exit(2)
131 return strings.TrimSpace(string(out))
133 testGOROOT = goEnv("GOROOT")
135 // The whole GOROOT/pkg tree was installed using the GOHOSTOS/GOHOSTARCH
136 // toolchain (installed in GOROOT/pkg/tool/GOHOSTOS_GOHOSTARCH).
137 // The testgo.exe we are about to create will be built for GOOS/GOARCH,
138 // which means it will use the GOOS/GOARCH toolchain
139 // (installed in GOROOT/pkg/tool/GOOS_GOARCH).
140 // If these are not the same toolchain, then the entire standard library
141 // will look out of date (the compilers in those two different tool directories
142 // are built for different architectures and have different buid IDs),
143 // which will cause many tests to do unnecessary rebuilds and some
144 // tests to attempt to overwrite the installed standard library.
145 // Bail out entirely in this case.
146 hostGOOS := goEnv("GOHOSTOS")
147 hostGOARCH := goEnv("GOHOSTARCH")
148 if hostGOOS != runtime.GOOS || hostGOARCH != runtime.GOARCH {
149 fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
150 fmt.Printf("cmd/go test is not compatible with GOOS/GOARCH != GOHOSTOS/GOHOSTARCH (%s/%s != %s/%s)\n", runtime.GOOS, runtime.GOARCH, hostGOOS, hostGOARCH)
151 fmt.Printf("SKIP\n")
152 return
155 out, err := exec.Command(gotool, args...).CombinedOutput()
156 if err != nil {
157 fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out)
158 os.Exit(2)
161 out, err = exec.Command(gotool, "env", "CC").CombinedOutput()
162 if err != nil {
163 fmt.Fprintf(os.Stderr, "could not find testing CC: %v\n%s", err, out)
164 os.Exit(2)
166 testCC = strings.TrimSpace(string(out))
168 if out, err := exec.Command("./testgo"+exeSuffix, "env", "CGO_ENABLED").Output(); err != nil {
169 fmt.Fprintf(os.Stderr, "running testgo failed: %v\n", err)
170 canRun = false
171 } else {
172 canCgo, err = strconv.ParseBool(strings.TrimSpace(string(out)))
173 if err != nil {
174 fmt.Fprintf(os.Stderr, "can't parse go env CGO_ENABLED output: %v\n", strings.TrimSpace(string(out)))
178 // As of Sept 2017, MSan is only supported on linux/amd64.
179 // https://github.com/google/sanitizers/wiki/MemorySanitizer#getting-memorysanitizer
180 canMSan = canCgo && runtime.GOOS == "linux" && runtime.GOARCH == "amd64"
182 switch runtime.GOOS {
183 case "linux", "darwin", "freebsd", "windows":
184 // The race detector doesn't work on Alpine Linux:
185 // golang.org/issue/14481
186 canRace = canCgo && runtime.GOARCH == "amd64" && !isAlpineLinux() && runtime.Compiler != "gccgo"
189 // Don't let these environment variables confuse the test.
190 os.Unsetenv("GOBIN")
191 os.Unsetenv("GOPATH")
192 os.Unsetenv("GIT_ALLOW_PROTOCOL")
193 if home, ccacheDir := os.Getenv("HOME"), os.Getenv("CCACHE_DIR"); home != "" && ccacheDir == "" {
194 // On some systems the default C compiler is ccache.
195 // Setting HOME to a non-existent directory will break
196 // those systems. Set CCACHE_DIR to cope. Issue 17668.
197 os.Setenv("CCACHE_DIR", filepath.Join(home, ".ccache"))
199 os.Setenv("HOME", "/test-go-home-does-not-exist")
200 if os.Getenv("GOCACHE") == "" {
201 os.Setenv("GOCACHE", "off") // because $HOME is gone
204 r := m.Run()
206 if canRun {
207 os.Remove("testgo" + exeSuffix)
210 os.Exit(r)
213 func isAlpineLinux() bool {
214 if runtime.GOOS != "linux" {
215 return false
217 fi, err := os.Lstat("/etc/alpine-release")
218 return err == nil && fi.Mode().IsRegular()
221 // The length of an mtime tick on this system. This is an estimate of
222 // how long we need to sleep to ensure that the mtime of two files is
223 // different.
224 // We used to try to be clever but that didn't always work (see golang.org/issue/12205).
225 var mtimeTick time.Duration = 1 * time.Second
227 // Manage a single run of the testgo binary.
228 type testgoData struct {
229 t *testing.T
230 temps []string
231 wd string
232 env []string
233 tempdir string
234 ran bool
235 inParallel bool
236 stdout, stderr bytes.Buffer
239 // skipIfGccgo skips the test if using gccgo.
240 func skipIfGccgo(t *testing.T, msg string) {
241 if runtime.Compiler == "gccgo" {
242 t.Skipf("skipping test not supported on gccgo: %s", msg)
246 // testgo sets up for a test that runs testgo.
247 func testgo(t *testing.T) *testgoData {
248 t.Helper()
249 testenv.MustHaveGoBuild(t)
251 if skipExternal {
252 t.Skipf("skipping external tests on %s/%s", runtime.GOOS, runtime.GOARCH)
255 return &testgoData{t: t}
258 // must gives a fatal error if err is not nil.
259 func (tg *testgoData) must(err error) {
260 tg.t.Helper()
261 if err != nil {
262 tg.t.Fatal(err)
266 // check gives a test non-fatal error if err is not nil.
267 func (tg *testgoData) check(err error) {
268 tg.t.Helper()
269 if err != nil {
270 tg.t.Error(err)
274 // parallel runs the test in parallel by calling t.Parallel.
275 func (tg *testgoData) parallel() {
276 tg.t.Helper()
277 if tg.ran {
278 tg.t.Fatal("internal testsuite error: call to parallel after run")
280 if tg.wd != "" {
281 tg.t.Fatal("internal testsuite error: call to parallel after cd")
283 for _, e := range tg.env {
284 if strings.HasPrefix(e, "GOROOT=") || strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
285 val := e[strings.Index(e, "=")+1:]
286 if strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata") {
287 tg.t.Fatalf("internal testsuite error: call to parallel with testdata in environment (%s)", e)
291 tg.inParallel = true
292 tg.t.Parallel()
295 // pwd returns the current directory.
296 func (tg *testgoData) pwd() string {
297 tg.t.Helper()
298 wd, err := os.Getwd()
299 if err != nil {
300 tg.t.Fatalf("could not get working directory: %v", err)
302 return wd
305 // cd changes the current directory to the named directory. Note that
306 // using this means that the test must not be run in parallel with any
307 // other tests.
308 func (tg *testgoData) cd(dir string) {
309 tg.t.Helper()
310 if tg.inParallel {
311 tg.t.Fatal("internal testsuite error: changing directory when running in parallel")
313 if tg.wd == "" {
314 tg.wd = tg.pwd()
316 abs, err := filepath.Abs(dir)
317 tg.must(os.Chdir(dir))
318 if err == nil {
319 tg.setenv("PWD", abs)
323 // sleep sleeps for one tick, where a tick is a conservative estimate
324 // of how long it takes for a file modification to get a different
325 // mtime.
326 func (tg *testgoData) sleep() {
327 time.Sleep(mtimeTick)
330 // setenv sets an environment variable to use when running the test go
331 // command.
332 func (tg *testgoData) setenv(name, val string) {
333 tg.t.Helper()
334 if tg.inParallel && (name == "GOROOT" || name == "GOPATH" || name == "GOBIN") && (strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata")) {
335 tg.t.Fatalf("internal testsuite error: call to setenv with testdata (%s=%s) after parallel", name, val)
337 tg.unsetenv(name)
338 tg.env = append(tg.env, name+"="+val)
341 // unsetenv removes an environment variable.
342 func (tg *testgoData) unsetenv(name string) {
343 if tg.env == nil {
344 tg.env = append([]string(nil), os.Environ()...)
346 for i, v := range tg.env {
347 if strings.HasPrefix(v, name+"=") {
348 tg.env = append(tg.env[:i], tg.env[i+1:]...)
349 break
354 func (tg *testgoData) goTool() string {
355 if tg.wd == "" {
356 return "./testgo" + exeSuffix
358 return filepath.Join(tg.wd, "testgo"+exeSuffix)
361 // doRun runs the test go command, recording stdout and stderr and
362 // returning exit status.
363 func (tg *testgoData) doRun(args []string) error {
364 tg.t.Helper()
365 if !canRun {
366 panic("testgoData.doRun called but canRun false")
368 if tg.inParallel {
369 for _, arg := range args {
370 if strings.HasPrefix(arg, "testdata") || strings.HasPrefix(arg, "./testdata") {
371 tg.t.Fatal("internal testsuite error: parallel run using testdata")
376 hasGoroot := false
377 for _, v := range tg.env {
378 if strings.HasPrefix(v, "GOROOT=") {
379 hasGoroot = true
380 break
383 prog := tg.goTool()
384 if !hasGoroot {
385 tg.setenv("GOROOT", testGOROOT)
388 tg.t.Logf("running testgo %v", args)
389 cmd := exec.Command(prog, args...)
390 tg.stdout.Reset()
391 tg.stderr.Reset()
392 cmd.Stdout = &tg.stdout
393 cmd.Stderr = &tg.stderr
394 cmd.Env = tg.env
395 status := cmd.Run()
396 if tg.stdout.Len() > 0 {
397 tg.t.Log("standard output:")
398 tg.t.Log(tg.stdout.String())
400 if tg.stderr.Len() > 0 {
401 tg.t.Log("standard error:")
402 tg.t.Log(tg.stderr.String())
404 tg.ran = true
405 return status
408 // run runs the test go command, and expects it to succeed.
409 func (tg *testgoData) run(args ...string) {
410 tg.t.Helper()
411 if status := tg.doRun(args); status != nil {
412 tg.t.Logf("go %v failed unexpectedly: %v", args, status)
413 tg.t.FailNow()
417 // runFail runs the test go command, and expects it to fail.
418 func (tg *testgoData) runFail(args ...string) {
419 tg.t.Helper()
420 if status := tg.doRun(args); status == nil {
421 tg.t.Fatal("testgo succeeded unexpectedly")
422 } else {
423 tg.t.Log("testgo failed as expected:", status)
427 // runGit runs a git command, and expects it to succeed.
428 func (tg *testgoData) runGit(dir string, args ...string) {
429 tg.t.Helper()
430 cmd := exec.Command("git", args...)
431 tg.stdout.Reset()
432 tg.stderr.Reset()
433 cmd.Stdout = &tg.stdout
434 cmd.Stderr = &tg.stderr
435 cmd.Dir = dir
436 cmd.Env = tg.env
437 status := cmd.Run()
438 if tg.stdout.Len() > 0 {
439 tg.t.Log("git standard output:")
440 tg.t.Log(tg.stdout.String())
442 if tg.stderr.Len() > 0 {
443 tg.t.Log("git standard error:")
444 tg.t.Log(tg.stderr.String())
446 if status != nil {
447 tg.t.Logf("git %v failed unexpectedly: %v", args, status)
448 tg.t.FailNow()
452 // getStdout returns standard output of the testgo run as a string.
453 func (tg *testgoData) getStdout() string {
454 tg.t.Helper()
455 if !tg.ran {
456 tg.t.Fatal("internal testsuite error: stdout called before run")
458 return tg.stdout.String()
461 // getStderr returns standard error of the testgo run as a string.
462 func (tg *testgoData) getStderr() string {
463 tg.t.Helper()
464 if !tg.ran {
465 tg.t.Fatal("internal testsuite error: stdout called before run")
467 return tg.stderr.String()
470 // doGrepMatch looks for a regular expression in a buffer, and returns
471 // whether it is found. The regular expression is matched against
472 // each line separately, as with the grep command.
473 func (tg *testgoData) doGrepMatch(match string, b *bytes.Buffer) bool {
474 tg.t.Helper()
475 if !tg.ran {
476 tg.t.Fatal("internal testsuite error: grep called before run")
478 re := regexp.MustCompile(match)
479 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
480 if re.Match(ln) {
481 return true
484 return false
487 // doGrep looks for a regular expression in a buffer and fails if it
488 // is not found. The name argument is the name of the output we are
489 // searching, "output" or "error". The msg argument is logged on
490 // failure.
491 func (tg *testgoData) doGrep(match string, b *bytes.Buffer, name, msg string) {
492 tg.t.Helper()
493 if !tg.doGrepMatch(match, b) {
494 tg.t.Log(msg)
495 tg.t.Logf("pattern %v not found in standard %s", match, name)
496 tg.t.FailNow()
500 // grepStdout looks for a regular expression in the test run's
501 // standard output and fails, logging msg, if it is not found.
502 func (tg *testgoData) grepStdout(match, msg string) {
503 tg.t.Helper()
504 tg.doGrep(match, &tg.stdout, "output", msg)
507 // grepStderr looks for a regular expression in the test run's
508 // standard error and fails, logging msg, if it is not found.
509 func (tg *testgoData) grepStderr(match, msg string) {
510 tg.t.Helper()
511 tg.doGrep(match, &tg.stderr, "error", msg)
514 // grepBoth looks for a regular expression in the test run's standard
515 // output or stand error and fails, logging msg, if it is not found.
516 func (tg *testgoData) grepBoth(match, msg string) {
517 tg.t.Helper()
518 if !tg.doGrepMatch(match, &tg.stdout) && !tg.doGrepMatch(match, &tg.stderr) {
519 tg.t.Log(msg)
520 tg.t.Logf("pattern %v not found in standard output or standard error", match)
521 tg.t.FailNow()
525 // doGrepNot looks for a regular expression in a buffer and fails if
526 // it is found. The name and msg arguments are as for doGrep.
527 func (tg *testgoData) doGrepNot(match string, b *bytes.Buffer, name, msg string) {
528 tg.t.Helper()
529 if tg.doGrepMatch(match, b) {
530 tg.t.Log(msg)
531 tg.t.Logf("pattern %v found unexpectedly in standard %s", match, name)
532 tg.t.FailNow()
536 // grepStdoutNot looks for a regular expression in the test run's
537 // standard output and fails, logging msg, if it is found.
538 func (tg *testgoData) grepStdoutNot(match, msg string) {
539 tg.t.Helper()
540 tg.doGrepNot(match, &tg.stdout, "output", msg)
543 // grepStderrNot looks for a regular expression in the test run's
544 // standard error and fails, logging msg, if it is found.
545 func (tg *testgoData) grepStderrNot(match, msg string) {
546 tg.t.Helper()
547 tg.doGrepNot(match, &tg.stderr, "error", msg)
550 // grepBothNot looks for a regular expression in the test run's
551 // standard output or stand error and fails, logging msg, if it is
552 // found.
553 func (tg *testgoData) grepBothNot(match, msg string) {
554 tg.t.Helper()
555 if tg.doGrepMatch(match, &tg.stdout) || tg.doGrepMatch(match, &tg.stderr) {
556 tg.t.Log(msg)
557 tg.t.Fatalf("pattern %v found unexpectedly in standard output or standard error", match)
561 // doGrepCount counts the number of times a regexp is seen in a buffer.
562 func (tg *testgoData) doGrepCount(match string, b *bytes.Buffer) int {
563 tg.t.Helper()
564 if !tg.ran {
565 tg.t.Fatal("internal testsuite error: doGrepCount called before run")
567 re := regexp.MustCompile(match)
568 c := 0
569 for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
570 if re.Match(ln) {
574 return c
577 // grepCountBoth returns the number of times a regexp is seen in both
578 // standard output and standard error.
579 func (tg *testgoData) grepCountBoth(match string) int {
580 tg.t.Helper()
581 return tg.doGrepCount(match, &tg.stdout) + tg.doGrepCount(match, &tg.stderr)
584 // creatingTemp records that the test plans to create a temporary file
585 // or directory. If the file or directory exists already, it will be
586 // removed. When the test completes, the file or directory will be
587 // removed if it exists.
588 func (tg *testgoData) creatingTemp(path string) {
589 tg.t.Helper()
590 if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) {
591 tg.t.Fatalf("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path)
593 // If we have changed the working directory, make sure we have
594 // an absolute path, because we are going to change directory
595 // back before we remove the temporary.
596 if tg.wd != "" && !filepath.IsAbs(path) {
597 path = filepath.Join(tg.pwd(), path)
599 tg.must(os.RemoveAll(path))
600 tg.temps = append(tg.temps, path)
603 // makeTempdir makes a temporary directory for a run of testgo. If
604 // the temporary directory was already created, this does nothing.
605 func (tg *testgoData) makeTempdir() {
606 tg.t.Helper()
607 if tg.tempdir == "" {
608 var err error
609 tg.tempdir, err = ioutil.TempDir("", "gotest")
610 tg.must(err)
614 // tempFile adds a temporary file for a run of testgo.
615 func (tg *testgoData) tempFile(path, contents string) {
616 tg.t.Helper()
617 tg.makeTempdir()
618 tg.must(os.MkdirAll(filepath.Join(tg.tempdir, filepath.Dir(path)), 0755))
619 bytes := []byte(contents)
620 if strings.HasSuffix(path, ".go") {
621 formatted, err := format.Source(bytes)
622 if err == nil {
623 bytes = formatted
626 tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644))
629 // tempDir adds a temporary directory for a run of testgo.
630 func (tg *testgoData) tempDir(path string) {
631 tg.t.Helper()
632 tg.makeTempdir()
633 if err := os.MkdirAll(filepath.Join(tg.tempdir, path), 0755); err != nil && !os.IsExist(err) {
634 tg.t.Fatal(err)
638 // path returns the absolute pathname to file with the temporary
639 // directory.
640 func (tg *testgoData) path(name string) string {
641 tg.t.Helper()
642 if tg.tempdir == "" {
643 tg.t.Fatalf("internal testsuite error: path(%q) with no tempdir", name)
645 if name == "." {
646 return tg.tempdir
648 return filepath.Join(tg.tempdir, name)
651 // mustExist fails if path does not exist.
652 func (tg *testgoData) mustExist(path string) {
653 tg.t.Helper()
654 if _, err := os.Stat(path); err != nil {
655 if os.IsNotExist(err) {
656 tg.t.Fatalf("%s does not exist but should", path)
658 tg.t.Fatalf("%s stat failed: %v", path, err)
662 // mustNotExist fails if path exists.
663 func (tg *testgoData) mustNotExist(path string) {
664 tg.t.Helper()
665 if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
666 tg.t.Fatalf("%s exists but should not (%v)", path, err)
670 // mustHaveContent succeeds if filePath is a path to a file,
671 // and that file is readable and not empty.
672 func (tg *testgoData) mustHaveContent(filePath string) {
673 tg.mustExist(filePath)
674 f, err := os.Stat(filePath)
675 if err != nil {
676 tg.t.Fatal(err)
678 if f.Size() == 0 {
679 tg.t.Fatalf("expected %s to have data, but is empty", filePath)
683 // wantExecutable fails with msg if path is not executable.
684 func (tg *testgoData) wantExecutable(path, msg string) {
685 tg.t.Helper()
686 if st, err := os.Stat(path); err != nil {
687 if !os.IsNotExist(err) {
688 tg.t.Log(err)
690 tg.t.Fatal(msg)
691 } else {
692 if runtime.GOOS != "windows" && st.Mode()&0111 == 0 {
693 tg.t.Fatalf("binary %s exists but is not executable", path)
698 // wantArchive fails if path is not an archive.
699 func (tg *testgoData) wantArchive(path string) {
700 tg.t.Helper()
701 f, err := os.Open(path)
702 if err != nil {
703 tg.t.Fatal(err)
705 buf := make([]byte, 100)
706 io.ReadFull(f, buf)
707 f.Close()
708 if !bytes.HasPrefix(buf, []byte("!<arch>\n")) {
709 tg.t.Fatalf("file %s exists but is not an archive", path)
713 // isStale reports whether pkg is stale, and why
714 func (tg *testgoData) isStale(pkg string) (bool, string) {
715 tg.t.Helper()
716 tg.run("list", "-f", "{{.Stale}}:{{.StaleReason}}", pkg)
717 v := strings.TrimSpace(tg.getStdout())
718 f := strings.SplitN(v, ":", 2)
719 if len(f) == 2 {
720 switch f[0] {
721 case "true":
722 return true, f[1]
723 case "false":
724 return false, f[1]
727 tg.t.Fatalf("unexpected output checking staleness of package %v: %v", pkg, v)
728 panic("unreachable")
731 // wantStale fails with msg if pkg is not stale.
732 func (tg *testgoData) wantStale(pkg, reason, msg string) {
733 tg.t.Helper()
734 stale, why := tg.isStale(pkg)
735 if !stale {
736 tg.t.Fatal(msg)
738 if reason == "" && why != "" || !strings.Contains(why, reason) {
739 tg.t.Errorf("wrong reason for Stale=true: %q, want %q", why, reason)
743 // wantNotStale fails with msg if pkg is stale.
744 func (tg *testgoData) wantNotStale(pkg, reason, msg string) {
745 tg.t.Helper()
746 stale, why := tg.isStale(pkg)
747 if stale {
748 tg.t.Fatal(msg)
750 if reason == "" && why != "" || !strings.Contains(why, reason) {
751 tg.t.Errorf("wrong reason for Stale=false: %q, want %q", why, reason)
755 // cleanup cleans up a test that runs testgo.
756 func (tg *testgoData) cleanup() {
757 tg.t.Helper()
758 if tg.wd != "" {
759 if err := os.Chdir(tg.wd); err != nil {
760 // We are unlikely to be able to continue.
761 fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err)
762 os.Exit(2)
765 for _, path := range tg.temps {
766 tg.check(os.RemoveAll(path))
768 if tg.tempdir != "" {
769 tg.check(os.RemoveAll(tg.tempdir))
773 // failSSH puts an ssh executable in the PATH that always fails.
774 // This is to stub out uses of ssh by go get.
775 func (tg *testgoData) failSSH() {
776 tg.t.Helper()
777 wd, err := os.Getwd()
778 if err != nil {
779 tg.t.Fatal(err)
781 fail := filepath.Join(wd, "testdata/failssh")
782 tg.setenv("PATH", fmt.Sprintf("%v%c%v", fail, filepath.ListSeparator, os.Getenv("PATH")))
785 func TestBuildComplex(t *testing.T) {
786 // Simple smoke test for build configuration.
787 tg := testgo(t)
788 defer tg.cleanup()
789 tg.parallel()
790 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
791 tg.run("build", "-x", "-o", os.DevNull, "complex")
793 if _, err := exec.LookPath("gccgo"); err == nil {
794 t.Skip("golang.org/issue/22472")
795 tg.run("build", "-x", "-o", os.DevNull, "-compiler=gccgo", "complex")
799 func TestFileLineInErrorMessages(t *testing.T) {
800 tg := testgo(t)
801 defer tg.cleanup()
802 tg.parallel()
803 tg.tempFile("err.go", `package main; import "bar"`)
804 path := tg.path("err.go")
805 tg.runFail("run", path)
806 shortPath := path
807 if rel, err := filepath.Rel(tg.pwd(), path); err == nil && len(rel) < len(path) {
808 shortPath = rel
810 tg.grepStderr("^"+regexp.QuoteMeta(shortPath)+":", "missing file:line in error message")
813 func TestProgramNameInCrashMessages(t *testing.T) {
814 skipIfGccgo(t, "gccgo does not use cmd/link")
815 tg := testgo(t)
816 defer tg.cleanup()
817 tg.parallel()
818 tg.tempFile("triv.go", `package main; func main() {}`)
819 tg.runFail("build", "-ldflags", "-crash_for_testing", tg.path("triv.go"))
820 tg.grepStderr(`[/\\]tool[/\\].*[/\\]link`, "missing linker name in error message")
823 func TestBrokenTestsWithoutTestFunctionsAllFail(t *testing.T) {
824 tg := testgo(t)
825 defer tg.cleanup()
826 // TODO: tg.parallel()
827 tg.runFail("test", "./testdata/src/badtest/...")
828 tg.grepBothNot("^ok", "test passed unexpectedly")
829 tg.grepBoth("FAIL.*badtest/badexec", "test did not run everything")
830 tg.grepBoth("FAIL.*badtest/badsyntax", "test did not run everything")
831 tg.grepBoth("FAIL.*badtest/badvar", "test did not run everything")
834 func TestGoBuildDashAInDevBranch(t *testing.T) {
835 if testing.Short() {
836 t.Skip("don't rebuild the standard library in short mode")
839 tg := testgo(t)
840 defer tg.cleanup()
841 tg.run("install", "math") // should be up to date already but just in case
842 tg.setenv("TESTGO_IS_GO_RELEASE", "0")
843 tg.run("build", "-v", "-a", "math")
844 tg.grepStderr("runtime", "testgo build -a math in dev branch DID NOT build runtime, but should have")
846 // Everything is out of date. Rebuild to leave things in a better state.
847 tg.run("install", "std")
850 func TestGoBuildDashAInReleaseBranch(t *testing.T) {
851 if testing.Short() {
852 t.Skip("don't rebuild the standard library in short mode")
855 tg := testgo(t)
856 defer tg.cleanup()
857 tg.run("install", "math", "net/http") // should be up to date already but just in case
858 tg.setenv("TESTGO_IS_GO_RELEASE", "1")
859 tg.run("install", "-v", "-a", "math")
860 tg.grepStderr("runtime", "testgo build -a math in release branch DID NOT build runtime, but should have")
862 // Now runtime.a is updated (newer mtime), so everything would look stale if not for being a release.
863 tg.run("build", "-v", "net/http")
864 tg.grepStderrNot("strconv", "testgo build -v net/http in release branch with newer runtime.a DID build strconv but should not have")
865 tg.grepStderrNot("golang.org/x/net/http2/hpack", "testgo build -v net/http in release branch with newer runtime.a DID build .../golang.org/x/net/http2/hpack but should not have")
866 tg.grepStderrNot("net/http", "testgo build -v net/http in release branch with newer runtime.a DID build net/http but should not have")
868 // Everything is out of date. Rebuild to leave things in a better state.
869 tg.run("install", "std")
872 func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) {
873 if testing.Short() {
874 t.Skip("don't rebuild the standard library in short mode")
877 tg := testgo(t)
878 defer tg.cleanup()
880 addNL := func(name string) (restore func()) {
881 data, err := ioutil.ReadFile(name)
882 if err != nil {
883 t.Fatal(err)
885 old := data
886 data = append(data, '\n')
887 if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil {
888 t.Fatal(err)
890 tg.sleep()
891 return func() {
892 if err := ioutil.WriteFile(name, old, 0666); err != nil {
893 t.Fatal(err)
898 tg.tempFile("d1/src/p1/p1.go", `package p1`)
899 tg.setenv("GOPATH", tg.path("d1"))
900 tg.run("install", "-a", "p1")
901 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, before any changes")
903 // Changing mtime of runtime/internal/sys/sys.go
904 // should have no effect: only the content matters.
905 // In fact this should be true even outside a release branch.
906 sys := runtime.GOROOT() + "/src/runtime/internal/sys/sys.go"
907 tg.sleep()
908 restore := addNL(sys)
909 restore()
910 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after updating mtime of runtime/internal/sys/sys.go")
912 // But changing content of any file should have an effect.
913 // Previously zversion.go was the only one that mattered;
914 // now they all matter, so keep using sys.go.
915 restore = addNL(sys)
916 defer restore()
917 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go")
918 restore()
919 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after changing back to old release")
920 addNL(sys)
921 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go again")
922 tg.run("install", "p1")
923 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with new release")
925 // Restore to "old" release.
926 restore()
927 tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after restoring sys.go")
928 tg.run("install", "p1")
929 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release")
931 // Everything is out of date. Rebuild to leave things in a better state.
932 tg.run("install", "std")
935 func TestGoListStandard(t *testing.T) {
936 skipIfGccgo(t, "gccgo does not GOROOT")
937 tooSlow(t)
938 tg := testgo(t)
939 defer tg.cleanup()
940 // TODO: tg.parallel()
941 tg.cd(runtime.GOROOT() + "/src")
942 tg.run("list", "-f", "{{if not .Standard}}{{.ImportPath}}{{end}}", "./...")
943 stdout := tg.getStdout()
944 for _, line := range strings.Split(stdout, "\n") {
945 if strings.HasPrefix(line, "_/") && strings.HasSuffix(line, "/src") {
946 // $GOROOT/src shows up if there are any .go files there.
947 // We don't care.
948 continue
950 if line == "" {
951 continue
953 t.Errorf("package in GOROOT not listed as standard: %v", line)
956 // Similarly, expanding std should include some of our vendored code.
957 tg.run("list", "std", "cmd")
958 tg.grepStdout("golang.org/x/net/http2/hpack", "list std cmd did not mention vendored hpack")
959 tg.grepStdout("golang.org/x/arch/x86/x86asm", "list std cmd did not mention vendored x86asm")
962 func TestGoInstallCleansUpAfterGoBuild(t *testing.T) {
963 tooSlow(t)
964 tg := testgo(t)
965 defer tg.cleanup()
966 // TODO: tg.parallel()
967 tg.tempFile("src/mycmd/main.go", `package main; func main(){}`)
968 tg.setenv("GOPATH", tg.path("."))
969 tg.cd(tg.path("src/mycmd"))
971 doesNotExist := func(file, msg string) {
972 if _, err := os.Stat(file); err == nil {
973 t.Fatal(msg)
974 } else if !os.IsNotExist(err) {
975 t.Fatal(msg, "error:", err)
979 tg.run("build")
980 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary")
981 tg.run("install")
982 doesNotExist("mycmd"+exeSuffix, "testgo install did not remove command binary")
983 tg.run("build")
984 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (second time)")
985 // Running install with arguments does not remove the target,
986 // even in the same directory.
987 tg.run("install", "mycmd")
988 tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary when run in mycmd")
989 tg.run("build")
990 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (third time)")
991 // And especially not outside the directory.
992 tg.cd(tg.path("."))
993 if data, err := ioutil.ReadFile("src/mycmd/mycmd" + exeSuffix); err != nil {
994 t.Fatal("could not read file:", err)
995 } else {
996 if err := ioutil.WriteFile("mycmd"+exeSuffix, data, 0555); err != nil {
997 t.Fatal("could not write file:", err)
1000 tg.run("install", "mycmd")
1001 tg.wantExecutable("src/mycmd/mycmd"+exeSuffix, "testgo install mycmd removed command binary from its source dir when run outside mycmd")
1002 tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary from current dir when run outside mycmd")
1005 func TestGoInstallRebuildsStalePackagesInOtherGOPATH(t *testing.T) {
1006 tooSlow(t)
1007 tg := testgo(t)
1008 defer tg.cleanup()
1009 tg.parallel()
1010 tg.tempFile("d1/src/p1/p1.go", `package p1
1011 import "p2"
1012 func F() { p2.F() }`)
1013 tg.tempFile("d2/src/p2/p2.go", `package p2
1014 func F() {}`)
1015 sep := string(filepath.ListSeparator)
1016 tg.setenv("GOPATH", tg.path("d1")+sep+tg.path("d2"))
1017 tg.run("install", "-i", "p1")
1018 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly")
1019 tg.wantNotStale("p2", "", "./testgo list claims p2 is stale, incorrectly")
1020 tg.sleep()
1021 if f, err := os.OpenFile(tg.path("d2/src/p2/p2.go"), os.O_WRONLY|os.O_APPEND, 0); err != nil {
1022 t.Fatal(err)
1023 } else if _, err = f.WriteString(`func G() {}`); err != nil {
1024 t.Fatal(err)
1025 } else {
1026 tg.must(f.Close())
1028 tg.wantStale("p2", "build ID mismatch", "./testgo list claims p2 is NOT stale, incorrectly")
1029 tg.wantStale("p1", "stale dependency: p2", "./testgo list claims p1 is NOT stale, incorrectly")
1031 tg.run("install", "-i", "p1")
1032 tg.wantNotStale("p2", "", "./testgo list claims p2 is stale after reinstall, incorrectly")
1033 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after reinstall, incorrectly")
1036 func TestGoInstallDetectsRemovedFiles(t *testing.T) {
1037 tg := testgo(t)
1038 defer tg.cleanup()
1039 tg.parallel()
1040 tg.tempFile("src/mypkg/x.go", `package mypkg`)
1041 tg.tempFile("src/mypkg/y.go", `package mypkg`)
1042 tg.tempFile("src/mypkg/z.go", `// +build missingtag
1044 package mypkg`)
1045 tg.setenv("GOPATH", tg.path("."))
1046 tg.run("install", "mypkg")
1047 tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale, incorrectly")
1048 // z.go was not part of the build; removing it is okay.
1049 tg.must(os.Remove(tg.path("src/mypkg/z.go")))
1050 tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale after removing z.go; should not be stale")
1051 // y.go was part of the package; removing it should be detected.
1052 tg.must(os.Remove(tg.path("src/mypkg/y.go")))
1053 tg.wantStale("mypkg", "build ID mismatch", "./testgo list mypkg claims mypkg is NOT stale after removing y.go; should be stale")
1056 func TestWildcardMatchesSyntaxErrorDirs(t *testing.T) {
1057 tg := testgo(t)
1058 defer tg.cleanup()
1059 // TODO: tg.parallel()
1060 tg.tempFile("src/mypkg/x.go", `package mypkg`)
1061 tg.tempFile("src/mypkg/y.go", `pkg mypackage`)
1062 tg.setenv("GOPATH", tg.path("."))
1063 tg.cd(tg.path("src/mypkg"))
1064 tg.runFail("list", "./...")
1065 tg.runFail("build", "./...")
1066 tg.runFail("install", "./...")
1069 func TestGoListWithTags(t *testing.T) {
1070 tg := testgo(t)
1071 defer tg.cleanup()
1072 tg.tempFile("src/mypkg/x.go", "// +build thetag\n\npackage mypkg\n")
1073 tg.setenv("GOPATH", tg.path("."))
1074 tg.cd(tg.path("./src"))
1075 tg.run("list", "-tags=thetag", "./my...")
1076 tg.grepStdout("mypkg", "did not find mypkg")
1079 func TestGoInstallErrorOnCrossCompileToBin(t *testing.T) {
1080 if testing.Short() {
1081 t.Skip("don't install into GOROOT in short mode")
1084 tg := testgo(t)
1085 defer tg.cleanup()
1086 tg.tempFile("src/mycmd/x.go", `package main
1087 func main() {}`)
1088 tg.setenv("GOPATH", tg.path("."))
1089 tg.cd(tg.path("src/mycmd"))
1091 tg.run("build", "mycmd")
1093 goarch := "386"
1094 if runtime.GOARCH == "386" {
1095 goarch = "amd64"
1097 tg.setenv("GOOS", "linux")
1098 tg.setenv("GOARCH", goarch)
1099 tg.run("install", "mycmd")
1100 tg.setenv("GOBIN", tg.path("."))
1101 tg.runFail("install", "mycmd")
1102 tg.run("install", "cmd/pack")
1105 func TestGoInstallDetectsRemovedFilesInPackageMain(t *testing.T) {
1106 tooSlow(t)
1107 tg := testgo(t)
1108 defer tg.cleanup()
1109 tg.parallel()
1110 tg.tempFile("src/mycmd/x.go", `package main
1111 func main() {}`)
1112 tg.tempFile("src/mycmd/y.go", `package main`)
1113 tg.tempFile("src/mycmd/z.go", `// +build missingtag
1115 package main`)
1116 tg.setenv("GOPATH", tg.path("."))
1117 tg.run("install", "mycmd")
1118 tg.wantNotStale("mycmd", "", "./testgo list mypkg claims mycmd is stale, incorrectly")
1119 // z.go was not part of the build; removing it is okay.
1120 tg.must(os.Remove(tg.path("src/mycmd/z.go")))
1121 tg.wantNotStale("mycmd", "", "./testgo list mycmd claims mycmd is stale after removing z.go; should not be stale")
1122 // y.go was part of the package; removing it should be detected.
1123 tg.must(os.Remove(tg.path("src/mycmd/y.go")))
1124 tg.wantStale("mycmd", "build ID mismatch", "./testgo list mycmd claims mycmd is NOT stale after removing y.go; should be stale")
1127 func testLocalRun(tg *testgoData, exepath, local, match string) {
1128 tg.t.Helper()
1129 out, err := exec.Command(exepath).Output()
1130 if err != nil {
1131 tg.t.Fatalf("error running %v: %v", exepath, err)
1133 if !regexp.MustCompile(match).Match(out) {
1134 tg.t.Log(string(out))
1135 tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local)
1139 func testLocalEasy(tg *testgoData, local string) {
1140 tg.t.Helper()
1141 exepath := "./easy" + exeSuffix
1142 tg.creatingTemp(exepath)
1143 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go"))
1144 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1147 func testLocalEasySub(tg *testgoData, local string) {
1148 tg.t.Helper()
1149 exepath := "./easysub" + exeSuffix
1150 tg.creatingTemp(exepath)
1151 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go"))
1152 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1155 func testLocalHard(tg *testgoData, local string) {
1156 tg.t.Helper()
1157 exepath := "./hard" + exeSuffix
1158 tg.creatingTemp(exepath)
1159 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go"))
1160 testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`)
1163 func testLocalInstall(tg *testgoData, local string) {
1164 tg.t.Helper()
1165 tg.runFail("install", filepath.Join("testdata", local, "easy.go"))
1168 func TestLocalImportsEasy(t *testing.T) {
1169 tg := testgo(t)
1170 defer tg.cleanup()
1171 testLocalEasy(tg, "local")
1174 func TestLocalImportsEasySub(t *testing.T) {
1175 tg := testgo(t)
1176 defer tg.cleanup()
1177 testLocalEasySub(tg, "local")
1180 func TestLocalImportsHard(t *testing.T) {
1181 tg := testgo(t)
1182 defer tg.cleanup()
1183 testLocalHard(tg, "local")
1186 func TestLocalImportsGoInstallShouldFail(t *testing.T) {
1187 tg := testgo(t)
1188 defer tg.cleanup()
1189 testLocalInstall(tg, "local")
1192 const badDirName = `#$%:, &()*;<=>?\^{}`
1194 func copyBad(tg *testgoData) {
1195 tg.t.Helper()
1196 if runtime.GOOS == "windows" {
1197 tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName)
1200 tg.must(filepath.Walk("testdata/local",
1201 func(path string, info os.FileInfo, err error) error {
1202 if err != nil {
1203 return err
1205 if info.IsDir() {
1206 return nil
1208 var data []byte
1209 data, err = ioutil.ReadFile(path)
1210 if err != nil {
1211 return err
1213 newpath := strings.Replace(path, "local", badDirName, 1)
1214 tg.tempFile(newpath, string(data))
1215 return nil
1217 tg.cd(tg.path("."))
1220 func TestBadImportsEasy(t *testing.T) {
1221 tg := testgo(t)
1222 defer tg.cleanup()
1223 // TODO: tg.parallel()
1224 copyBad(tg)
1225 testLocalEasy(tg, badDirName)
1228 func TestBadImportsEasySub(t *testing.T) {
1229 tg := testgo(t)
1230 defer tg.cleanup()
1231 copyBad(tg)
1232 testLocalEasySub(tg, badDirName)
1235 func TestBadImportsHard(t *testing.T) {
1236 tg := testgo(t)
1237 defer tg.cleanup()
1238 copyBad(tg)
1239 testLocalHard(tg, badDirName)
1242 func TestBadImportsGoInstallShouldFail(t *testing.T) {
1243 tg := testgo(t)
1244 defer tg.cleanup()
1245 copyBad(tg)
1246 testLocalInstall(tg, badDirName)
1249 func TestInternalPackagesInGOROOTAreRespected(t *testing.T) {
1250 skipIfGccgo(t, "gccgo does not have GOROOT")
1251 tg := testgo(t)
1252 defer tg.cleanup()
1253 tg.runFail("build", "-v", "./testdata/testinternal")
1254 tg.grepBoth(`testinternal(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrong error message for testdata/testinternal")
1257 func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) {
1258 tg := testgo(t)
1259 defer tg.cleanup()
1260 tg.runFail("build", "-v", "./testdata/testinternal2")
1261 tg.grepBoth(`testinternal2(\/|\\)p\.go\:3\:8\: use of internal package not allowed`, "wrote error message for testdata/testinternal2")
1264 func TestRunInternal(t *testing.T) {
1265 tg := testgo(t)
1266 defer tg.cleanup()
1267 dir := filepath.Join(tg.pwd(), "testdata")
1268 tg.setenv("GOPATH", dir)
1269 tg.run("run", filepath.Join(dir, "src/run/good.go"))
1270 tg.runFail("run", filepath.Join(dir, "src/run/bad.go"))
1271 tg.grepStderr(`testdata(\/|\\)src(\/|\\)run(\/|\\)bad\.go\:3\:8\: use of internal package not allowed`, "unexpected error for run/bad.go")
1274 func testMove(t *testing.T, vcs, url, base, config string) {
1275 testenv.MustHaveExternalNetwork(t)
1277 tg := testgo(t)
1278 defer tg.cleanup()
1279 tg.parallel()
1280 tg.tempDir("src")
1281 tg.setenv("GOPATH", tg.path("."))
1282 tg.run("get", "-d", url)
1283 tg.run("get", "-d", "-u", url)
1284 switch vcs {
1285 case "svn":
1286 // SVN doesn't believe in text files so we can't just edit the config.
1287 // Check out a different repo into the wrong place.
1288 tg.must(os.RemoveAll(tg.path("src/code.google.com/p/rsc-svn")))
1289 tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk")
1290 tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn")))
1291 default:
1292 path := tg.path(filepath.Join("src", config))
1293 data, err := ioutil.ReadFile(path)
1294 tg.must(err)
1295 data = bytes.Replace(data, []byte(base), []byte(base+"XXX"), -1)
1296 tg.must(ioutil.WriteFile(path, data, 0644))
1298 if vcs == "git" {
1299 // git will ask for a username and password when we
1300 // run go get -d -f -u. An empty username and
1301 // password will work. Prevent asking by setting
1302 // GIT_ASKPASS.
1303 tg.creatingTemp("sink" + exeSuffix)
1304 tg.tempFile("src/sink/sink.go", `package main; func main() {}`)
1305 tg.run("build", "-o", "sink"+exeSuffix, "sink")
1306 tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix))
1308 tg.runFail("get", "-d", "-u", url)
1309 tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason")
1310 tg.runFail("get", "-d", "-f", "-u", url)
1311 tg.grepStderr("validating server certificate|[nN]ot [fF]ound", "go get -d -f -u "+url+" failed for wrong reason")
1314 func TestInternalPackageErrorsAreHandled(t *testing.T) {
1315 tg := testgo(t)
1316 defer tg.cleanup()
1317 tg.run("list", "./testdata/testinternal3")
1320 func TestInternalCache(t *testing.T) {
1321 tg := testgo(t)
1322 defer tg.cleanup()
1323 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4"))
1324 tg.runFail("build", "p")
1325 tg.grepStderr("internal", "did not fail to build p")
1328 func TestMoveGit(t *testing.T) {
1329 testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config")
1332 func TestMoveHG(t *testing.T) {
1333 testMove(t, "hg", "vcs-test.golang.org/go/custom-hg-hello", "custom-hg-hello", "vcs-test.golang.org/go/custom-hg-hello/.hg/hgrc")
1336 // TODO(rsc): Set up a test case on SourceForge (?) for svn.
1337 // func testMoveSVN(t *testing.T) {
1338 // testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-")
1339 // }
1341 func TestImportCommandMatch(t *testing.T) {
1342 tg := testgo(t)
1343 defer tg.cleanup()
1344 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1345 tg.run("build", "./testdata/importcom/works.go")
1348 func TestImportCommentMismatch(t *testing.T) {
1349 tg := testgo(t)
1350 defer tg.cleanup()
1351 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1352 tg.runFail("build", "./testdata/importcom/wrongplace.go")
1353 tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import")
1356 func TestImportCommentSyntaxError(t *testing.T) {
1357 tg := testgo(t)
1358 defer tg.cleanup()
1359 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1360 tg.runFail("build", "./testdata/importcom/bad.go")
1361 tg.grepStderr("cannot parse import comment", "go build did not mention syntax error")
1364 func TestImportCommentConflict(t *testing.T) {
1365 tg := testgo(t)
1366 defer tg.cleanup()
1367 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1368 tg.runFail("build", "./testdata/importcom/conflict.go")
1369 tg.grepStderr("found import comments", "go build did not mention comment conflict")
1372 // cmd/go: custom import path checking should not apply to Go packages without import comment.
1373 func TestIssue10952(t *testing.T) {
1374 testenv.MustHaveExternalNetwork(t)
1375 if _, err := exec.LookPath("git"); err != nil {
1376 t.Skip("skipping because git binary not found")
1379 tg := testgo(t)
1380 defer tg.cleanup()
1381 tg.parallel()
1382 tg.tempDir("src")
1383 tg.setenv("GOPATH", tg.path("."))
1384 const importPath = "github.com/zombiezen/go-get-issue-10952"
1385 tg.run("get", "-d", "-u", importPath)
1386 repoDir := tg.path("src/" + importPath)
1387 tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git")
1388 tg.run("get", "-d", "-u", importPath)
1391 func TestIssue16471(t *testing.T) {
1392 testenv.MustHaveExternalNetwork(t)
1393 if _, err := exec.LookPath("git"); err != nil {
1394 t.Skip("skipping because git binary not found")
1397 tg := testgo(t)
1398 defer tg.cleanup()
1399 tg.parallel()
1400 tg.tempDir("src")
1401 tg.setenv("GOPATH", tg.path("."))
1402 tg.must(os.MkdirAll(tg.path("src/rsc.io/go-get-issue-10952"), 0755))
1403 tg.runGit(tg.path("src/rsc.io"), "clone", "https://github.com/zombiezen/go-get-issue-10952")
1404 tg.runFail("get", "-u", "rsc.io/go-get-issue-10952")
1405 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")
1408 // Test git clone URL that uses SCP-like syntax and custom import path checking.
1409 func TestIssue11457(t *testing.T) {
1410 testenv.MustHaveExternalNetwork(t)
1411 if _, err := exec.LookPath("git"); err != nil {
1412 t.Skip("skipping because git binary not found")
1415 tg := testgo(t)
1416 defer tg.cleanup()
1417 tg.parallel()
1418 tg.tempDir("src")
1419 tg.setenv("GOPATH", tg.path("."))
1420 const importPath = "rsc.io/go-get-issue-11457"
1421 tg.run("get", "-d", "-u", importPath)
1422 repoDir := tg.path("src/" + importPath)
1423 tg.runGit(repoDir, "remote", "set-url", "origin", "git@github.com:rsc/go-get-issue-11457")
1425 // At this time, custom import path checking compares remotes verbatim (rather than
1426 // just the host and path, skipping scheme and user), so we expect go get -u to fail.
1427 // However, the goal of this test is to verify that gitRemoteRepo correctly parsed
1428 // the SCP-like syntax, and we expect it to appear in the error message.
1429 tg.runFail("get", "-d", "-u", importPath)
1430 want := " is checked out from ssh://git@github.com/rsc/go-get-issue-11457"
1431 if !strings.HasSuffix(strings.TrimSpace(tg.getStderr()), want) {
1432 t.Error("expected clone URL to appear in stderr")
1436 func TestGetGitDefaultBranch(t *testing.T) {
1437 testenv.MustHaveExternalNetwork(t)
1438 if _, err := exec.LookPath("git"); err != nil {
1439 t.Skip("skipping because git binary not found")
1442 tg := testgo(t)
1443 defer tg.cleanup()
1444 tg.parallel()
1445 tg.tempDir("src")
1446 tg.setenv("GOPATH", tg.path("."))
1448 // This repo has two branches, master and another-branch.
1449 // The another-branch is the default that you get from 'git clone'.
1450 // The go get command variants should not override this.
1451 const importPath = "github.com/rsc/go-get-default-branch"
1453 tg.run("get", "-d", importPath)
1454 repoDir := tg.path("src/" + importPath)
1455 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1456 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1458 tg.run("get", "-d", "-u", importPath)
1459 tg.runGit(repoDir, "branch", "--contains", "HEAD")
1460 tg.grepStdout(`\* another-branch`, "not on correct default branch")
1463 func TestAccidentalGitCheckout(t *testing.T) {
1464 testenv.MustHaveExternalNetwork(t)
1465 if _, err := exec.LookPath("git"); err != nil {
1466 t.Skip("skipping because git binary not found")
1469 tg := testgo(t)
1470 defer tg.cleanup()
1471 tg.parallel()
1472 tg.tempDir("src")
1473 tg.setenv("GOPATH", tg.path("."))
1475 tg.runFail("get", "-u", "vcs-test.golang.org/go/test1-svn-git")
1476 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1478 tg.runFail("get", "-u", "vcs-test.golang.org/go/test2-svn-git/test2main")
1479 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1482 func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) {
1483 tg := testgo(t)
1484 defer tg.cleanup()
1485 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1486 tg.runFail("test", "syntaxerror")
1487 tg.grepStderr("FAIL", "go test did not say FAIL")
1490 func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) {
1491 tg := testgo(t)
1492 defer tg.cleanup()
1493 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1494 tg.runFail("list", "...")
1495 tg.grepBoth("badpkg", "go list ... failure does not mention badpkg")
1496 tg.run("list", "m...")
1499 func TestRelativeImportsGoTest(t *testing.T) {
1500 tg := testgo(t)
1501 defer tg.cleanup()
1502 tg.run("test", "./testdata/testimport")
1505 func TestRelativeImportsGoTestDashI(t *testing.T) {
1506 tg := testgo(t)
1507 defer tg.cleanup()
1509 // don't let test -i overwrite runtime
1510 tg.wantNotStale("runtime", "", "must be non-stale before test -i")
1512 tg.run("test", "-i", "./testdata/testimport")
1515 func TestRelativeImportsInCommandLinePackage(t *testing.T) {
1516 tg := testgo(t)
1517 defer tg.cleanup()
1518 // TODO: tg.parallel()
1519 files, err := filepath.Glob("./testdata/testimport/*.go")
1520 tg.must(err)
1521 tg.run(append([]string{"test"}, files...)...)
1524 func TestNonCanonicalImportPaths(t *testing.T) {
1525 tg := testgo(t)
1526 defer tg.cleanup()
1527 tg.parallel()
1528 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1529 tg.runFail("build", "canonical/d")
1530 tg.grepStderr("package canonical/d", "did not report canonical/d")
1531 tg.grepStderr("imports canonical/b", "did not report canonical/b")
1532 tg.grepStderr("imports canonical/a/: non-canonical", "did not report canonical/a/")
1535 func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) {
1536 tg := testgo(t)
1537 defer tg.cleanup()
1538 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1"))
1539 tg.runFail("get", "-u", "foo")
1541 // TODO(iant): We should not have to use strconv.Quote here.
1542 // The code in vcs.go should be changed so that it is not required.
1543 quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo"))
1544 quoted = quoted[1 : len(quoted)-1]
1546 tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo")
1549 func TestInstallFailsWithNoBuildableFiles(t *testing.T) {
1550 tg := testgo(t)
1551 defer tg.cleanup()
1552 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1553 tg.setenv("CGO_ENABLED", "0")
1554 tg.runFail("install", "cgotest")
1555 tg.grepStderr("build constraints exclude all Go files", "go install cgotest did not report 'build constraints exclude all Go files'")
1558 // Issue 21895
1559 func TestMSanAndRaceRequireCgo(t *testing.T) {
1560 if !canMSan && !canRace {
1561 t.Skip("skipping because both msan and the race detector are not supported")
1564 tg := testgo(t)
1565 defer tg.cleanup()
1566 tg.tempFile("triv.go", `package main; func main() {}`)
1567 tg.setenv("CGO_ENABLED", "0")
1568 if canRace {
1569 tg.runFail("install", "-race", "triv.go")
1570 tg.grepStderr("-race requires cgo", "did not correctly report that -race requires cgo")
1571 tg.grepStderrNot("-msan", "reported that -msan instead of -race requires cgo")
1573 if canMSan {
1574 tg.runFail("install", "-msan", "triv.go")
1575 tg.grepStderr("-msan requires cgo", "did not correctly report that -msan requires cgo")
1576 tg.grepStderrNot("-race", "reported that -race instead of -msan requires cgo")
1580 func TestRelativeGOBINFail(t *testing.T) {
1581 tg := testgo(t)
1582 defer tg.cleanup()
1583 tg.tempFile("triv.go", `package main; func main() {}`)
1584 tg.setenv("GOBIN", ".")
1585 tg.runFail("install")
1586 tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path")
1589 // Test that without $GOBIN set, binaries get installed
1590 // into the GOPATH bin directory.
1591 func TestInstallIntoGOPATH(t *testing.T) {
1592 tg := testgo(t)
1593 defer tg.cleanup()
1594 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1595 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1596 tg.run("install", "go-cmd-test")
1597 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1600 // Issue 12407
1601 func TestBuildOutputToDevNull(t *testing.T) {
1602 tg := testgo(t)
1603 defer tg.cleanup()
1604 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1605 tg.run("build", "-o", os.DevNull, "go-cmd-test")
1608 func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) {
1609 tooSlow(t)
1610 tg := testgo(t)
1611 defer tg.cleanup()
1612 tg.parallel()
1613 gobin := filepath.Join(tg.pwd(), "testdata", "bin")
1614 tg.creatingTemp(gobin)
1615 tg.setenv("GOBIN", gobin)
1616 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1617 tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now()))
1618 tg.sleep()
1619 tg.run("test", "main_test")
1620 tg.run("install", "main_test")
1621 tg.wantNotStale("main_test", "", "after go install, main listed as stale")
1622 tg.run("test", "main_test")
1625 func TestPackageMainTestCompilerFlags(t *testing.T) {
1626 tg := testgo(t)
1627 defer tg.cleanup()
1628 tg.parallel()
1629 tg.makeTempdir()
1630 tg.setenv("GOPATH", tg.path("."))
1631 tg.tempFile("src/p1/p1.go", "package main\n")
1632 tg.tempFile("src/p1/p1_test.go", "package main\nimport \"testing\"\nfunc Test(t *testing.T){}\n")
1633 tg.run("test", "-c", "-n", "p1")
1634 tg.grepBothNot(`([\\/]compile|gccgo).* (-p main|-fgo-pkgpath=main).*p1\.go`, "should not have run compile -p main p1.go")
1635 tg.grepStderr(`([\\/]compile|gccgo).* (-p p1|-fgo-pkgpath=p1).*p1\.go`, "should have run compile -p p1 p1.go")
1638 // The runtime version string takes one of two forms:
1639 // "go1.X[.Y]" for Go releases, and "devel +hash" at tip.
1640 // Determine whether we are in a released copy by
1641 // inspecting the version.
1642 var isGoRelease = strings.HasPrefix(runtime.Version(), "go1")
1644 // Issue 12690
1645 func TestPackageNotStaleWithTrailingSlash(t *testing.T) {
1646 skipIfGccgo(t, "gccgo does not have GOROOT")
1647 tg := testgo(t)
1648 defer tg.cleanup()
1650 // Make sure the packages below are not stale.
1651 tg.wantNotStale("runtime", "", "must be non-stale before test runs")
1652 tg.wantNotStale("os", "", "must be non-stale before test runs")
1653 tg.wantNotStale("io", "", "must be non-stale before test runs")
1655 goroot := runtime.GOROOT()
1656 tg.setenv("GOROOT", goroot+"/")
1658 tg.wantNotStale("runtime", "", "with trailing slash in GOROOT, runtime listed as stale")
1659 tg.wantNotStale("os", "", "with trailing slash in GOROOT, os listed as stale")
1660 tg.wantNotStale("io", "", "with trailing slash in GOROOT, io listed as stale")
1663 // With $GOBIN set, binaries get installed to $GOBIN.
1664 func TestInstallIntoGOBIN(t *testing.T) {
1665 tg := testgo(t)
1666 defer tg.cleanup()
1667 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1668 tg.creatingTemp(gobin)
1669 tg.setenv("GOBIN", gobin)
1670 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1671 tg.run("install", "go-cmd-test")
1672 tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test")
1675 // Issue 11065
1676 func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) {
1677 tg := testgo(t)
1678 defer tg.cleanup()
1679 pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test")
1680 tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix))
1681 tg.setenv("GOBIN", pkg)
1682 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1683 tg.cd(pkg)
1684 tg.run("install")
1685 tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory")
1688 // Without $GOBIN set, installing a program outside $GOPATH should fail
1689 // (there is nowhere to install it).
1690 func TestInstallWithoutDestinationFails(t *testing.T) {
1691 tg := testgo(t)
1692 defer tg.cleanup()
1693 tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go")
1694 tg.grepStderr("no install location for .go files listed on command line", "wrong error")
1697 // With $GOBIN set, should install there.
1698 func TestInstallToGOBINCommandLinePackage(t *testing.T) {
1699 tg := testgo(t)
1700 defer tg.cleanup()
1701 gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1702 tg.creatingTemp(gobin)
1703 tg.setenv("GOBIN", gobin)
1704 tg.run("install", "testdata/src/go-cmd-test/helloworld.go")
1705 tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld")
1708 func TestGoGetNonPkg(t *testing.T) {
1709 testenv.MustHaveExternalNetwork(t)
1711 tg := testgo(t)
1712 defer tg.cleanup()
1713 tg.tempDir("gobin")
1714 tg.setenv("GOPATH", tg.path("."))
1715 tg.setenv("GOBIN", tg.path("gobin"))
1716 tg.runFail("get", "-d", "golang.org/x/tools")
1717 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1718 tg.runFail("get", "-d", "-u", "golang.org/x/tools")
1719 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1720 tg.runFail("get", "-d", "golang.org/x/tools")
1721 tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1724 func TestGoGetTestOnlyPkg(t *testing.T) {
1725 testenv.MustHaveExternalNetwork(t)
1727 tg := testgo(t)
1728 defer tg.cleanup()
1729 tg.tempDir("gopath")
1730 tg.setenv("GOPATH", tg.path("gopath"))
1731 tg.run("get", "golang.org/x/tour/content")
1732 tg.run("get", "-t", "golang.org/x/tour/content")
1735 func TestInstalls(t *testing.T) {
1736 if testing.Short() {
1737 t.Skip("don't install into GOROOT in short mode")
1740 tg := testgo(t)
1741 defer tg.cleanup()
1742 tg.parallel()
1743 tg.tempDir("gobin")
1744 tg.setenv("GOPATH", tg.path("."))
1745 goroot := runtime.GOROOT()
1746 tg.setenv("GOROOT", goroot)
1748 // cmd/fix installs into tool
1749 tg.run("env", "GOOS")
1750 goos := strings.TrimSpace(tg.getStdout())
1751 tg.setenv("GOOS", goos)
1752 tg.run("env", "GOARCH")
1753 goarch := strings.TrimSpace(tg.getStdout())
1754 tg.setenv("GOARCH", goarch)
1755 fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix
1756 tg.must(os.RemoveAll(fixbin))
1757 tg.run("install", "cmd/fix")
1758 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool")
1759 tg.must(os.Remove(fixbin))
1760 tg.setenv("GOBIN", tg.path("gobin"))
1761 tg.run("install", "cmd/fix")
1762 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set")
1763 tg.unsetenv("GOBIN")
1765 // gopath program installs into GOBIN
1766 tg.tempFile("src/progname/p.go", `package main; func main() {}`)
1767 tg.setenv("GOBIN", tg.path("gobin"))
1768 tg.run("install", "progname")
1769 tg.unsetenv("GOBIN")
1770 tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname")
1772 // gopath program installs into GOPATH/bin
1773 tg.run("install", "progname")
1774 tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname")
1777 func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) {
1778 tg := testgo(t)
1779 defer tg.cleanup()
1780 tg.setenv("GOPATH", ".")
1781 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1782 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1785 func TestRejectRelativePathsInGOPATH(t *testing.T) {
1786 tg := testgo(t)
1787 defer tg.cleanup()
1788 sep := string(filepath.ListSeparator)
1789 tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".")
1790 tg.runFail("build", "go-cmd-test")
1791 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1794 func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) {
1795 tg := testgo(t)
1796 defer tg.cleanup()
1797 tg.setenv("GOPATH", "testdata")
1798 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1799 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1802 // Issue 21928.
1803 func TestRejectBlankPathsInGOPATH(t *testing.T) {
1804 tg := testgo(t)
1805 defer tg.cleanup()
1806 sep := string(filepath.ListSeparator)
1807 tg.setenv("GOPATH", " "+sep+filepath.Join(tg.pwd(), "testdata"))
1808 tg.runFail("build", "go-cmd-test")
1809 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1812 // Issue 21928.
1813 func TestIgnoreEmptyPathsInGOPATH(t *testing.T) {
1814 tg := testgo(t)
1815 defer tg.cleanup()
1816 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1817 sep := string(filepath.ListSeparator)
1818 tg.setenv("GOPATH", ""+sep+filepath.Join(tg.pwd(), "testdata"))
1819 tg.run("install", "go-cmd-test")
1820 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1823 // Issue 4104.
1824 func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
1825 tooSlow(t)
1826 tg := testgo(t)
1827 defer tg.cleanup()
1828 tg.parallel()
1829 tg.run("test", "errors", "errors", "errors", "errors", "errors")
1830 if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") {
1831 t.Error("go test errors errors errors errors errors tested the same package multiple times")
1835 func TestGoListHasAConsistentOrder(t *testing.T) {
1836 tooSlow(t)
1837 tg := testgo(t)
1838 defer tg.cleanup()
1839 tg.parallel()
1840 tg.run("list", "std")
1841 first := tg.getStdout()
1842 tg.run("list", "std")
1843 if first != tg.getStdout() {
1844 t.Error("go list std ordering is inconsistent")
1848 func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
1849 tooSlow(t)
1850 tg := testgo(t)
1851 defer tg.cleanup()
1852 tg.parallel()
1853 tg.run("list", "std")
1854 tg.grepStdoutNot("cmd/", "go list std shows commands")
1857 func TestGoListCmdOnlyShowsCommands(t *testing.T) {
1858 skipIfGccgo(t, "gccgo has no GOROOT")
1859 tooSlow(t)
1860 tg := testgo(t)
1861 defer tg.cleanup()
1862 tg.parallel()
1863 tg.run("list", "cmd")
1864 out := strings.TrimSpace(tg.getStdout())
1865 for _, line := range strings.Split(out, "\n") {
1866 if !strings.Contains(line, "cmd/") {
1867 t.Error("go list cmd shows non-commands")
1868 break
1873 func TestGoListDedupsPackages(t *testing.T) {
1874 tg := testgo(t)
1875 defer tg.cleanup()
1876 // TODO: tg.parallel()
1877 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1878 tg.run("list", "xtestonly", "./testdata/src/xtestonly/...")
1879 got := strings.TrimSpace(tg.getStdout())
1880 const want = "xtestonly"
1881 if got != want {
1882 t.Errorf("got %q; want %q", got, want)
1886 func TestGoListDeps(t *testing.T) {
1887 tg := testgo(t)
1888 defer tg.cleanup()
1889 tg.parallel()
1890 tg.tempDir("src/p1/p2/p3/p4")
1891 tg.setenv("GOPATH", tg.path("."))
1892 tg.tempFile("src/p1/p.go", "package p1\nimport _ \"p1/p2\"\n")
1893 tg.tempFile("src/p1/p2/p.go", "package p2\nimport _ \"p1/p2/p3\"\n")
1894 tg.tempFile("src/p1/p2/p3/p.go", "package p3\nimport _ \"p1/p2/p3/p4\"\n")
1895 tg.tempFile("src/p1/p2/p3/p4/p.go", "package p4\n")
1896 tg.run("list", "-f", "{{.Deps}}", "p1")
1897 tg.grepStdout("p1/p2/p3/p4", "Deps(p1) does not mention p4")
1900 // Issue 4096. Validate the output of unsuccessful go install foo/quxx.
1901 func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) {
1902 tg := testgo(t)
1903 defer tg.cleanup()
1904 tg.parallel()
1905 tg.runFail("install", "foo/quxx")
1906 if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 {
1907 t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`)
1911 func TestGOROOTSearchFailureReporting(t *testing.T) {
1912 tg := testgo(t)
1913 defer tg.cleanup()
1914 tg.parallel()
1915 tg.runFail("install", "foo/quxx")
1916 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 {
1917 t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`)
1921 func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) {
1922 tg := testgo(t)
1923 defer tg.cleanup()
1924 tg.parallel()
1925 sep := string(filepath.ListSeparator)
1926 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1927 tg.runFail("install", "foo/quxx")
1928 if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 {
1929 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`)
1933 // Test (from $GOPATH) annotation is reported for the first GOPATH entry,
1934 func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) {
1935 tg := testgo(t)
1936 defer tg.cleanup()
1937 tg.parallel()
1938 sep := string(filepath.ListSeparator)
1939 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1940 tg.runFail("install", "foo/quxx")
1941 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 {
1942 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`)
1946 // but not on the second.
1947 func TestMentionGOPATHNotOnSecondEntry(t *testing.T) {
1948 tg := testgo(t)
1949 defer tg.cleanup()
1950 tg.parallel()
1951 sep := string(filepath.ListSeparator)
1952 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1953 tg.runFail("install", "foo/quxx")
1954 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 {
1955 t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`)
1959 func homeEnvName() string {
1960 switch runtime.GOOS {
1961 case "windows":
1962 return "USERPROFILE"
1963 case "plan9":
1964 return "home"
1965 default:
1966 return "HOME"
1970 func TestDefaultGOPATH(t *testing.T) {
1971 tg := testgo(t)
1972 defer tg.cleanup()
1973 tg.parallel()
1974 tg.tempDir("home/go")
1975 tg.setenv(homeEnvName(), tg.path("home"))
1977 tg.run("env", "GOPATH")
1978 tg.grepStdout(regexp.QuoteMeta(tg.path("home/go")), "want GOPATH=$HOME/go")
1980 tg.setenv("GOROOT", tg.path("home/go"))
1981 tg.run("env", "GOPATH")
1982 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go")
1984 tg.setenv("GOROOT", tg.path("home/go")+"/")
1985 tg.run("env", "GOPATH")
1986 tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go/")
1989 func TestDefaultGOPATHGet(t *testing.T) {
1990 testenv.MustHaveExternalNetwork(t)
1992 tg := testgo(t)
1993 defer tg.cleanup()
1994 tg.setenv("GOPATH", "")
1995 tg.tempDir("home")
1996 tg.setenv(homeEnvName(), tg.path("home"))
1998 // warn for creating directory
1999 tg.run("get", "-v", "github.com/golang/example/hello")
2000 tg.grepStderr("created GOPATH="+regexp.QuoteMeta(tg.path("home/go"))+"; see 'go help gopath'", "did not create GOPATH")
2002 // no warning if directory already exists
2003 tg.must(os.RemoveAll(tg.path("home/go")))
2004 tg.tempDir("home/go")
2005 tg.run("get", "github.com/golang/example/hello")
2006 tg.grepStderrNot(".", "expected no output on standard error")
2008 // error if $HOME/go is a file
2009 tg.must(os.RemoveAll(tg.path("home/go")))
2010 tg.tempFile("home/go", "")
2011 tg.runFail("get", "github.com/golang/example/hello")
2012 tg.grepStderr(`mkdir .*[/\\]go: .*(not a directory|cannot find the path)`, "expected error because $HOME/go is a file")
2015 func TestDefaultGOPATHPrintedSearchList(t *testing.T) {
2016 tg := testgo(t)
2017 defer tg.cleanup()
2018 tg.setenv("GOPATH", "")
2019 tg.tempDir("home")
2020 tg.setenv(homeEnvName(), tg.path("home"))
2022 tg.runFail("install", "github.com/golang/example/hello")
2023 tg.grepStderr(regexp.QuoteMeta(tg.path("home/go/src/github.com/golang/example/hello"))+`.*from \$GOPATH`, "expected default GOPATH")
2026 // Issue 4186. go get cannot be used to download packages to $GOROOT.
2027 // Test that without GOPATH set, go get should fail.
2028 func TestGoGetIntoGOROOT(t *testing.T) {
2029 testenv.MustHaveExternalNetwork(t)
2031 tg := testgo(t)
2032 defer tg.cleanup()
2033 tg.parallel()
2034 tg.tempDir("src")
2036 // Fails because GOROOT=GOPATH
2037 tg.setenv("GOPATH", tg.path("."))
2038 tg.setenv("GOROOT", tg.path("."))
2039 tg.runFail("get", "-d", "github.com/golang/example/hello")
2040 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2041 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2043 // Fails because GOROOT=GOPATH after cleaning.
2044 tg.setenv("GOPATH", tg.path(".")+"/")
2045 tg.setenv("GOROOT", tg.path("."))
2046 tg.runFail("get", "-d", "github.com/golang/example/hello")
2047 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2048 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2050 tg.setenv("GOPATH", tg.path("."))
2051 tg.setenv("GOROOT", tg.path(".")+"/")
2052 tg.runFail("get", "-d", "github.com/golang/example/hello")
2053 tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2054 tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2056 // Fails because GOROOT=$HOME/go so default GOPATH unset.
2057 tg.tempDir("home/go")
2058 tg.setenv(homeEnvName(), tg.path("home"))
2059 tg.setenv("GOPATH", "")
2060 tg.setenv("GOROOT", tg.path("home/go"))
2061 tg.runFail("get", "-d", "github.com/golang/example/hello")
2062 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2064 tg.setenv(homeEnvName(), tg.path("home")+"/")
2065 tg.setenv("GOPATH", "")
2066 tg.setenv("GOROOT", tg.path("home/go"))
2067 tg.runFail("get", "-d", "github.com/golang/example/hello")
2068 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2070 tg.setenv(homeEnvName(), tg.path("home"))
2071 tg.setenv("GOPATH", "")
2072 tg.setenv("GOROOT", tg.path("home/go")+"/")
2073 tg.runFail("get", "-d", "github.com/golang/example/hello")
2074 tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2077 func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) {
2078 skipIfGccgo(t, "gccgo does not support -ldflags -X")
2079 tooSlow(t)
2080 tg := testgo(t)
2081 defer tg.cleanup()
2082 tg.parallel()
2083 tg.tempFile("main.go", `package main
2084 var extern string
2085 func main() {
2086 println(extern)
2088 tg.run("run", "-ldflags", `-X "main.extern=hello world"`, tg.path("main.go"))
2089 tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`)
2092 func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) {
2093 skipIfGccgo(t, "gccgo has no standard packages")
2094 tooSlow(t)
2095 tg := testgo(t)
2096 defer tg.cleanup()
2097 // TODO: tg.parallel()
2098 tg.makeTempdir()
2099 tg.cd(tg.path("."))
2100 tg.run("test", "-cpuprofile", "errors.prof", "errors")
2101 tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test")
2104 func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) {
2105 skipIfGccgo(t, "gccgo has no standard packages")
2106 tooSlow(t)
2107 tg := testgo(t)
2108 defer tg.cleanup()
2109 // TODO: tg.parallel()
2110 tg.makeTempdir()
2111 tg.cd(tg.path("."))
2112 tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2113 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test")
2116 func TestGoTestMutexprofileLeavesBinaryBehind(t *testing.T) {
2117 skipIfGccgo(t, "gccgo has no standard packages")
2118 tooSlow(t)
2119 tg := testgo(t)
2120 defer tg.cleanup()
2121 // TODO: tg.parallel()
2122 tg.makeTempdir()
2123 tg.cd(tg.path("."))
2124 tg.run("test", "-mutexprofile", "errors.prof", "errors")
2125 tg.wantExecutable("errors.test"+exeSuffix, "go test -mutexprofile did not create errors.test")
2128 func TestGoTestMutexprofileDashOControlsBinaryLocation(t *testing.T) {
2129 skipIfGccgo(t, "gccgo has no standard packages")
2130 tooSlow(t)
2131 tg := testgo(t)
2132 defer tg.cleanup()
2133 // TODO: tg.parallel()
2134 tg.makeTempdir()
2135 tg.cd(tg.path("."))
2136 tg.run("test", "-mutexprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2137 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -mutexprofile -o myerrors.test did not create myerrors.test")
2140 func TestGoBuildNonMain(t *testing.T) {
2141 tg := testgo(t)
2142 defer tg.cleanup()
2143 // TODO: tg.parallel()
2144 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2145 tg.runFail("build", "-buildmode=exe", "-o", "not_main"+exeSuffix, "not_main")
2146 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")
2147 tg.mustNotExist("not_main" + exeSuffix)
2150 func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) {
2151 skipIfGccgo(t, "gccgo has no standard packages")
2152 tooSlow(t)
2153 tg := testgo(t)
2154 defer tg.cleanup()
2155 tg.parallel()
2156 tg.makeTempdir()
2157 tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2158 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test")
2161 func TestGoTestDashOWritesBinary(t *testing.T) {
2162 skipIfGccgo(t, "gccgo has no standard packages")
2163 tooSlow(t)
2164 tg := testgo(t)
2165 defer tg.cleanup()
2166 tg.parallel()
2167 tg.makeTempdir()
2168 tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2169 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2172 func TestGoTestDashIDashOWritesBinary(t *testing.T) {
2173 skipIfGccgo(t, "gccgo has no standard packages")
2174 tooSlow(t)
2175 tg := testgo(t)
2176 defer tg.cleanup()
2177 tg.parallel()
2178 tg.makeTempdir()
2180 // don't let test -i overwrite runtime
2181 tg.wantNotStale("runtime", "", "must be non-stale before test -i")
2183 tg.run("test", "-v", "-i", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2184 tg.grepBothNot("PASS|FAIL", "test should not have run")
2185 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2188 // Issue 4568.
2189 func TestSymlinksList(t *testing.T) {
2190 testenv.MustHaveSymlink(t)
2192 tg := testgo(t)
2193 defer tg.cleanup()
2194 // TODO: tg.parallel()
2195 tg.tempDir("src")
2196 tg.must(os.Symlink(tg.path("."), tg.path("src/dir1")))
2197 tg.tempFile("src/dir1/p.go", "package p")
2198 tg.setenv("GOPATH", tg.path("."))
2199 tg.cd(tg.path("src"))
2200 tg.run("list", "-f", "{{.Root}}", "dir1")
2201 if strings.TrimSpace(tg.getStdout()) != tg.path(".") {
2202 t.Error("confused by symlinks")
2206 // Issue 14054.
2207 func TestSymlinksVendor(t *testing.T) {
2208 testenv.MustHaveSymlink(t)
2210 tg := testgo(t)
2211 defer tg.cleanup()
2212 // TODO: tg.parallel()
2213 tg.tempDir("gopath/src/dir1/vendor/v")
2214 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}")
2215 tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v")
2216 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2217 tg.setenv("GOPATH", tg.path("gopath"))
2218 tg.cd(tg.path("symdir1"))
2219 tg.run("list", "-f", "{{.Root}}", ".")
2220 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2221 t.Error("list confused by symlinks")
2224 // All of these should succeed, not die in vendor-handling code.
2225 tg.run("run", "p.go")
2226 tg.run("build")
2227 tg.run("install")
2230 // Issue 15201.
2231 func TestSymlinksVendor15201(t *testing.T) {
2232 testenv.MustHaveSymlink(t)
2234 tg := testgo(t)
2235 defer tg.cleanup()
2237 tg.tempDir("gopath/src/x/y/_vendor/src/x")
2238 tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y")))
2239 tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n")
2240 tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor")))
2241 tg.tempFile("gopath/src/x/y/z/z.go", "package z\n")
2243 tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath"))
2244 tg.cd(tg.path("gopath/src"))
2245 tg.run("list", "./...")
2248 func TestSymlinksInternal(t *testing.T) {
2249 testenv.MustHaveSymlink(t)
2251 tg := testgo(t)
2252 defer tg.cleanup()
2253 tg.tempDir("gopath/src/dir1/internal/v")
2254 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}")
2255 tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v")
2256 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2257 tg.setenv("GOPATH", tg.path("gopath"))
2258 tg.cd(tg.path("symdir1"))
2259 tg.run("list", "-f", "{{.Root}}", ".")
2260 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2261 t.Error("list confused by symlinks")
2264 // All of these should succeed, not die in internal-handling code.
2265 tg.run("run", "p.go")
2266 tg.run("build")
2267 tg.run("install")
2270 // Issue 4515.
2271 func TestInstallWithTags(t *testing.T) {
2272 tooSlow(t)
2273 tg := testgo(t)
2274 defer tg.cleanup()
2275 tg.parallel()
2276 tg.tempDir("bin")
2277 tg.tempFile("src/example/a/main.go", `package main
2278 func main() {}`)
2279 tg.tempFile("src/example/b/main.go", `// +build mytag
2281 package main
2282 func main() {}`)
2283 tg.setenv("GOPATH", tg.path("."))
2284 tg.run("install", "-tags", "mytag", "example/a", "example/b")
2285 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries")
2286 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries")
2287 tg.must(os.Remove(tg.path("bin/a" + exeSuffix)))
2288 tg.must(os.Remove(tg.path("bin/b" + exeSuffix)))
2289 tg.run("install", "-tags", "mytag", "example/...")
2290 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries")
2291 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries")
2292 tg.run("list", "-tags", "mytag", "example/b...")
2293 if strings.TrimSpace(tg.getStdout()) != "example/b" {
2294 t.Error("go list example/b did not find example/b")
2298 // Issue 4773
2299 func TestCaseCollisions(t *testing.T) {
2300 tg := testgo(t)
2301 defer tg.cleanup()
2302 tg.parallel()
2303 tg.tempDir("src/example/a/pkg")
2304 tg.tempDir("src/example/a/Pkg")
2305 tg.tempDir("src/example/b")
2306 tg.setenv("GOPATH", tg.path("."))
2307 tg.tempFile("src/example/a/a.go", `package p
2308 import (
2309 _ "example/a/pkg"
2310 _ "example/a/Pkg"
2312 tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`)
2313 tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`)
2314 tg.run("list", "-json", "example/a")
2315 tg.grepStdout("case-insensitive import collision", "go list -json example/a did not report import collision")
2316 tg.runFail("build", "example/a")
2317 tg.grepStderr("case-insensitive import collision", "go build example/a did not report import collision")
2318 tg.tempFile("src/example/b/file.go", `package b`)
2319 tg.tempFile("src/example/b/FILE.go", `package b`)
2320 f, err := os.Open(tg.path("src/example/b"))
2321 tg.must(err)
2322 names, err := f.Readdirnames(0)
2323 tg.must(err)
2324 tg.check(f.Close())
2325 args := []string{"list"}
2326 if len(names) == 2 {
2327 // case-sensitive file system, let directory read find both files
2328 args = append(args, "example/b")
2329 } else {
2330 // case-insensitive file system, list files explicitly on command line
2331 args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go"))
2333 tg.runFail(args...)
2334 tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision")
2336 tg.runFail("list", "example/a/pkg", "example/a/Pkg")
2337 tg.grepStderr("case-insensitive import collision", "go list example/a/pkg example/a/Pkg did not report import collision")
2338 tg.run("list", "-json", "-e", "example/a/pkg", "example/a/Pkg")
2339 tg.grepStdout("case-insensitive import collision", "go list -json -e example/a/pkg example/a/Pkg did not report import collision")
2340 tg.runFail("build", "example/a/pkg", "example/a/Pkg")
2341 tg.grepStderr("case-insensitive import collision", "go build example/a/pkg example/a/Pkg did not report import collision")
2344 // Issue 17451, 17662.
2345 func TestSymlinkWarning(t *testing.T) {
2346 tg := testgo(t)
2347 defer tg.cleanup()
2348 tg.parallel()
2349 tg.makeTempdir()
2350 tg.setenv("GOPATH", tg.path("."))
2352 tg.tempDir("src/example/xx")
2353 tg.tempDir("yy/zz")
2354 tg.tempFile("yy/zz/zz.go", "package zz\n")
2355 if err := os.Symlink(tg.path("yy"), tg.path("src/example/xx/yy")); err != nil {
2356 t.Skipf("symlink failed: %v", err)
2358 tg.run("list", "example/xx/z...")
2359 tg.grepStdoutNot(".", "list should not have matched anything")
2360 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2361 tg.grepStderrNot("symlink", "list should not have reported symlink")
2363 tg.run("list", "example/xx/...")
2364 tg.grepStdoutNot(".", "list should not have matched anything")
2365 tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2366 tg.grepStderr("ignoring symlink", "list should have reported symlink")
2369 // Issue 8181.
2370 func TestGoGetDashTIssue8181(t *testing.T) {
2371 testenv.MustHaveExternalNetwork(t)
2373 tg := testgo(t)
2374 defer tg.cleanup()
2375 tg.parallel()
2376 tg.makeTempdir()
2377 tg.setenv("GOPATH", tg.path("."))
2378 tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b")
2379 tg.run("list", "...")
2380 tg.grepStdout("x/build/gerrit", "missing expected x/build/gerrit")
2383 func TestIssue11307(t *testing.T) {
2384 // go get -u was not working except in checkout directory
2385 testenv.MustHaveExternalNetwork(t)
2387 tg := testgo(t)
2388 defer tg.cleanup()
2389 tg.parallel()
2390 tg.makeTempdir()
2391 tg.setenv("GOPATH", tg.path("."))
2392 tg.run("get", "github.com/rsc/go-get-issue-11307")
2393 tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing
2396 func TestShadowingLogic(t *testing.T) {
2397 skipIfGccgo(t, "gccgo has no standard packages")
2398 tg := testgo(t)
2399 defer tg.cleanup()
2400 pwd := tg.pwd()
2401 sep := string(filepath.ListSeparator)
2402 tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2"))
2404 // The math in root1 is not "math" because the standard math is.
2405 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math")
2406 pwdForwardSlash := strings.Replace(pwd, string(os.PathSeparator), "/", -1)
2407 if !strings.HasPrefix(pwdForwardSlash, "/") {
2408 pwdForwardSlash = "/" + pwdForwardSlash
2410 // The output will have makeImportValid applies, but we only
2411 // bother to deal with characters we might reasonably see.
2412 for _, r := range " :" {
2413 pwdForwardSlash = strings.Replace(pwdForwardSlash, string(r), "_", -1)
2415 want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")"
2416 if strings.TrimSpace(tg.getStdout()) != want {
2417 t.Error("shadowed math is not shadowed; looking for", want)
2420 // The foo in root1 is "foo".
2421 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo")
2422 if strings.TrimSpace(tg.getStdout()) != "(foo) ()" {
2423 t.Error("unshadowed foo is shadowed")
2426 // The foo in root2 is not "foo" because the foo in root1 got there first.
2427 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo")
2428 want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")"
2429 if strings.TrimSpace(tg.getStdout()) != want {
2430 t.Error("shadowed foo is not shadowed; looking for", want)
2433 // The error for go install should mention the conflicting directory.
2434 tg.runFail("install", "./testdata/shadow/root2/src/foo")
2435 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")
2436 if strings.TrimSpace(tg.getStderr()) != want {
2437 t.Error("wrong shadowed install error; looking for", want)
2441 // Only succeeds if source order is preserved.
2442 func TestSourceFileNameOrderPreserved(t *testing.T) {
2443 tg := testgo(t)
2444 defer tg.cleanup()
2445 tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go")
2448 // Check that coverage analysis works at all.
2449 // Don't worry about the exact numbers but require not 0.0%.
2450 func checkCoverage(tg *testgoData, data string) {
2451 tg.t.Helper()
2452 if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) {
2453 tg.t.Error("some coverage results are 0.0%")
2457 func TestCoverageRuns(t *testing.T) {
2458 skipIfGccgo(t, "gccgo has no cover tool")
2459 tooSlow(t)
2460 tg := testgo(t)
2461 defer tg.cleanup()
2462 tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp")
2463 data := tg.getStdout() + tg.getStderr()
2464 tg.run("test", "-short", "-cover", "strings", "math", "regexp")
2465 data += tg.getStdout() + tg.getStderr()
2466 checkCoverage(tg, data)
2469 func TestCoverageDotImport(t *testing.T) {
2470 skipIfGccgo(t, "gccgo has no cover tool")
2471 tg := testgo(t)
2472 defer tg.cleanup()
2473 tg.parallel()
2474 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2475 tg.run("test", "-coverpkg=coverdot1,coverdot2", "coverdot2")
2476 data := tg.getStdout() + tg.getStderr()
2477 checkCoverage(tg, data)
2480 // Check that coverage analysis uses set mode.
2481 // Also check that coverage profiles merge correctly.
2482 func TestCoverageUsesSetMode(t *testing.T) {
2483 skipIfGccgo(t, "gccgo has no cover tool")
2484 tooSlow(t)
2485 tg := testgo(t)
2486 defer tg.cleanup()
2487 tg.creatingTemp("testdata/cover.out")
2488 tg.run("test", "-short", "-cover", "encoding/binary", "errors", "-coverprofile=testdata/cover.out")
2489 data := tg.getStdout() + tg.getStderr()
2490 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2491 t.Error(err)
2492 } else {
2493 if !bytes.Contains(out, []byte("mode: set")) {
2494 t.Error("missing mode: set")
2496 if !bytes.Contains(out, []byte("errors.go")) {
2497 t.Error("missing errors.go")
2499 if !bytes.Contains(out, []byte("binary.go")) {
2500 t.Error("missing binary.go")
2502 if bytes.Count(out, []byte("mode: set")) != 1 {
2503 t.Error("too many mode: set")
2506 checkCoverage(tg, data)
2509 func TestCoverageUsesAtomicModeForRace(t *testing.T) {
2510 tooSlow(t)
2511 if !canRace {
2512 t.Skip("skipping because race detector not supported")
2514 skipIfGccgo(t, "gccgo has no cover tool")
2516 tg := testgo(t)
2517 defer tg.cleanup()
2518 tg.creatingTemp("testdata/cover.out")
2519 tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
2520 data := tg.getStdout() + tg.getStderr()
2521 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2522 t.Error(err)
2523 } else {
2524 if !bytes.Contains(out, []byte("mode: atomic")) {
2525 t.Error("missing mode: atomic")
2528 checkCoverage(tg, data)
2531 func TestCoverageSyncAtomicImport(t *testing.T) {
2532 skipIfGccgo(t, "gccgo has no cover tool")
2533 tooSlow(t)
2534 tg := testgo(t)
2535 defer tg.cleanup()
2536 tg.parallel()
2537 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2538 tg.run("test", "-short", "-cover", "-covermode=atomic", "-coverpkg=coverdep/p1", "coverdep")
2541 func TestCoverageDepLoop(t *testing.T) {
2542 tooSlow(t)
2543 tg := testgo(t)
2544 defer tg.cleanup()
2545 tg.parallel()
2546 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2547 // coverdep2/p1's xtest imports coverdep2/p2 which imports coverdep2/p1.
2548 // Make sure that coverage on coverdep2/p2 recompiles coverdep2/p2.
2549 tg.run("test", "-short", "-cover", "coverdep2/p1")
2550 tg.grepStdout("coverage: 100.0% of statements", "expected 100.0% coverage")
2553 func TestCoverageImportMainLoop(t *testing.T) {
2554 skipIfGccgo(t, "gccgo has no cover tool")
2555 tg := testgo(t)
2556 defer tg.cleanup()
2557 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2558 tg.runFail("test", "importmain/test")
2559 tg.grepStderr("not an importable package", "did not detect import main")
2560 tg.runFail("test", "-cover", "importmain/test")
2561 tg.grepStderr("not an importable package", "did not detect import main")
2564 func TestCoveragePattern(t *testing.T) {
2565 skipIfGccgo(t, "gccgo has no cover tool")
2566 tooSlow(t)
2567 tg := testgo(t)
2568 defer tg.cleanup()
2569 tg.parallel()
2570 tg.makeTempdir()
2571 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2573 // If coverpkg=sleepy... expands by package loading
2574 // (as opposed to pattern matching on deps)
2575 // then it will try to load sleepybad, which does not compile,
2576 // and the test command will fail.
2577 tg.run("test", "-coverprofile="+tg.path("cover.out"), "-coverpkg=sleepy...", "-run=^$", "sleepy1")
2580 func TestCoverageErrorLine(t *testing.T) {
2581 skipIfGccgo(t, "gccgo has no cover tool")
2582 tooSlow(t)
2583 tg := testgo(t)
2584 defer tg.cleanup()
2585 tg.parallel()
2586 tg.makeTempdir()
2587 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2588 tg.setenv("GOTMPDIR", tg.tempdir)
2590 tg.runFail("test", "coverbad")
2591 tg.grepStderr(`coverbad[\\/]p\.go:4`, "did not find coverbad/p.go:4")
2592 if canCgo {
2593 tg.grepStderr(`coverbad[\\/]p1\.go:6`, "did not find coverbad/p1.go:6")
2595 tg.grepStderrNot(regexp.QuoteMeta(tg.tempdir), "found temporary directory in error")
2596 stderr := tg.getStderr()
2598 tg.runFail("test", "-cover", "coverbad")
2599 stderr2 := tg.getStderr()
2601 // It's OK that stderr2 drops the character position in the error,
2602 // because of the //line directive (see golang.org/issue/22662).
2603 stderr = strings.Replace(stderr, "p.go:4:2:", "p.go:4:", -1)
2604 if stderr != stderr2 {
2605 t.Logf("test -cover changed error messages:\nbefore:\n%s\n\nafter:\n%s", stderr, stderr2)
2606 t.Skip("golang.org/issue/22660")
2607 t.FailNow()
2611 func TestTestBuildFailureOutput(t *testing.T) {
2612 tooSlow(t)
2614 tg := testgo(t)
2615 defer tg.cleanup()
2616 tg.parallel()
2617 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2619 // Doesn't build, -x output should not claim to run test.
2620 tg.runFail("test", "-x", "coverbad")
2621 tg.grepStderrNot(`[\\/]coverbad\.test( |$)`, "claimed to run test")
2624 func TestCoverageFunc(t *testing.T) {
2625 skipIfGccgo(t, "gccgo has no cover tool")
2626 tooSlow(t)
2627 tg := testgo(t)
2628 defer tg.cleanup()
2629 tg.parallel()
2630 tg.makeTempdir()
2631 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2633 tg.run("test", "-outputdir="+tg.tempdir, "-coverprofile=cover.out", "coverasm")
2634 tg.run("tool", "cover", "-func="+tg.path("cover.out"))
2635 tg.grepStdout(`\tg\t*100.0%`, "did not find g 100% covered")
2636 tg.grepStdoutNot(`\tf\t*[0-9]`, "reported coverage for assembly function f")
2639 func TestPluginNonMain(t *testing.T) {
2640 wd, err := os.Getwd()
2641 if err != nil {
2642 t.Fatal(err)
2645 pkg := filepath.Join(wd, "testdata", "testdep", "p2")
2647 tg := testgo(t)
2648 defer tg.cleanup()
2650 tg.runFail("build", "-buildmode=plugin", pkg)
2653 func TestTestEmpty(t *testing.T) {
2654 if !canRace {
2655 t.Skip("no race detector")
2658 wd, _ := os.Getwd()
2659 testdata := filepath.Join(wd, "testdata")
2660 for _, dir := range []string{"pkg", "test", "xtest", "pkgtest", "pkgxtest", "pkgtestxtest", "testxtest"} {
2661 t.Run(dir, func(t *testing.T) {
2662 tg := testgo(t)
2663 defer tg.cleanup()
2664 tg.setenv("GOPATH", testdata)
2665 tg.cd(filepath.Join(testdata, "src/empty/"+dir))
2666 tg.run("test", "-cover", "-coverpkg=.", "-race")
2668 if testing.Short() {
2669 break
2674 func TestNoGoError(t *testing.T) {
2675 wd, _ := os.Getwd()
2676 testdata := filepath.Join(wd, "testdata")
2677 for _, dir := range []string{"empty/test", "empty/xtest", "empty/testxtest", "exclude", "exclude/ignore", "exclude/empty"} {
2678 t.Run(dir, func(t *testing.T) {
2679 tg := testgo(t)
2680 defer tg.cleanup()
2681 tg.setenv("GOPATH", testdata)
2682 tg.cd(filepath.Join(testdata, "src"))
2683 tg.runFail("build", "./"+dir)
2684 var want string
2685 if strings.Contains(dir, "test") {
2686 want = "no non-test Go files in "
2687 } else if dir == "exclude" {
2688 want = "build constraints exclude all Go files in "
2689 } else {
2690 want = "no Go files in "
2692 tg.grepStderr(want, "wrong reason for failure")
2697 func TestTestRaceInstall(t *testing.T) {
2698 if !canRace {
2699 t.Skip("no race detector")
2701 tooSlow(t)
2703 tg := testgo(t)
2704 defer tg.cleanup()
2705 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2707 tg.tempDir("pkg")
2708 pkgdir := tg.path("pkg")
2709 tg.run("install", "-race", "-pkgdir="+pkgdir, "std")
2710 tg.run("test", "-race", "-pkgdir="+pkgdir, "-i", "-v", "empty/pkg")
2711 if tg.getStderr() != "" {
2712 t.Error("go test -i -race: rebuilds cached packages")
2716 func TestBuildDryRunWithCgo(t *testing.T) {
2717 if !canCgo {
2718 t.Skip("skipping because cgo not enabled")
2721 tg := testgo(t)
2722 defer tg.cleanup()
2723 tg.tempFile("foo.go", `package main
2726 #include <limits.h>
2728 import "C"
2730 func main() {
2731 println(C.INT_MAX)
2733 tg.run("build", "-n", tg.path("foo.go"))
2734 tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file")
2737 func TestCoverageWithCgo(t *testing.T) {
2738 skipIfGccgo(t, "gccgo has no cover tool")
2739 tooSlow(t)
2740 if !canCgo {
2741 t.Skip("skipping because cgo not enabled")
2744 for _, dir := range []string{"cgocover", "cgocover2", "cgocover3", "cgocover4"} {
2745 t.Run(dir, func(t *testing.T) {
2746 tg := testgo(t)
2747 tg.parallel()
2748 defer tg.cleanup()
2749 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2750 tg.run("test", "-short", "-cover", dir)
2751 data := tg.getStdout() + tg.getStderr()
2752 checkCoverage(tg, data)
2757 func TestCgoAsmError(t *testing.T) {
2758 if !canCgo {
2759 t.Skip("skipping because cgo not enabled")
2762 tg := testgo(t)
2763 tg.parallel()
2764 defer tg.cleanup()
2765 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2766 tg.runFail("build", "cgoasm")
2767 tg.grepBoth("package using cgo has Go assembly file", "did not detect Go assembly file")
2770 func TestCgoDependsOnSyscall(t *testing.T) {
2771 if testing.Short() {
2772 t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode")
2774 if !canCgo {
2775 t.Skip("skipping because cgo not enabled")
2777 if !canRace {
2778 t.Skip("skipping because race detector not supported")
2781 tg := testgo(t)
2782 defer tg.cleanup()
2783 files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race"))
2784 tg.must(err)
2785 for _, file := range files {
2786 tg.check(os.RemoveAll(file))
2788 tg.tempFile("src/foo/foo.go", `
2789 package foo
2790 //#include <stdio.h>
2791 import "C"`)
2792 tg.setenv("GOPATH", tg.path("."))
2793 tg.run("build", "-race", "foo")
2796 func TestCgoShowsFullPathNames(t *testing.T) {
2797 if !canCgo {
2798 t.Skip("skipping because cgo not enabled")
2801 tg := testgo(t)
2802 defer tg.cleanup()
2803 tg.parallel()
2804 tg.tempFile("src/x/y/dirname/foo.go", `
2805 package foo
2806 import "C"
2807 func f() {`)
2808 tg.setenv("GOPATH", tg.path("."))
2809 tg.runFail("build", "x/y/dirname")
2810 tg.grepBoth("x/y/dirname", "error did not use full path")
2813 func TestCgoHandlesWlORIGIN(t *testing.T) {
2814 tooSlow(t)
2815 if !canCgo {
2816 t.Skip("skipping because cgo not enabled")
2819 tg := testgo(t)
2820 defer tg.cleanup()
2821 tg.parallel()
2822 tg.tempFile("src/origin/origin.go", `package origin
2823 // #cgo !darwin LDFLAGS: -Wl,-rpath,$ORIGIN
2824 // void f(void) {}
2825 import "C"
2826 func f() { C.f() }`)
2827 tg.setenv("GOPATH", tg.path("."))
2828 tg.run("build", "origin")
2831 func TestCgoPkgConfig(t *testing.T) {
2832 tooSlow(t)
2833 if !canCgo {
2834 t.Skip("skipping because cgo not enabled")
2836 tg := testgo(t)
2837 defer tg.cleanup()
2838 tg.parallel()
2840 tg.run("env", "PKG_CONFIG")
2841 pkgConfig := strings.TrimSpace(tg.getStdout())
2842 if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil {
2843 t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out)
2846 // OpenBSD's pkg-config is strict about whitespace and only
2847 // supports backslash-escaped whitespace. It does not support
2848 // quotes, which the normal freedesktop.org pkg-config does
2849 // support. See http://man.openbsd.org/pkg-config.1
2850 tg.tempFile("foo.pc", `
2851 Name: foo
2852 Description: The foo library
2853 Version: 1.0.0
2854 Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world
2856 tg.tempFile("foo.go", `package main
2859 #cgo pkg-config: foo
2860 int value() {
2861 return DEFINED_FROM_PKG_CONFIG;
2864 import "C"
2865 import "os"
2867 func main() {
2868 if C.value() != 42 {
2869 println("value() =", C.value(), "wanted 42")
2870 os.Exit(1)
2874 tg.setenv("PKG_CONFIG_PATH", tg.path("."))
2875 tg.run("run", tg.path("foo.go"))
2878 // "go test -c -test.bench=XXX errors" should not hang.
2879 // "go test -c" should also produce reproducible binaries.
2880 // "go test -c" should also appear to write a new binary every time,
2881 // even if it's really just updating the mtime on an existing up-to-date binary.
2882 func TestIssue6480(t *testing.T) {
2883 skipIfGccgo(t, "gccgo has no standard packages")
2884 tooSlow(t)
2885 tg := testgo(t)
2886 defer tg.cleanup()
2887 // TODO: tg.parallel()
2888 tg.makeTempdir()
2889 tg.cd(tg.path("."))
2890 tg.run("test", "-c", "-test.bench=XXX", "errors")
2891 tg.run("test", "-c", "-o", "errors2.test", "errors")
2893 data1, err := ioutil.ReadFile("errors.test" + exeSuffix)
2894 tg.must(err)
2895 data2, err := ioutil.ReadFile("errors2.test") // no exeSuffix because -o above doesn't have it
2896 tg.must(err)
2897 if !bytes.Equal(data1, data2) {
2898 t.Fatalf("go test -c errors produced different binaries when run twice")
2901 start := time.Now()
2902 tg.run("test", "-x", "-c", "-test.bench=XXX", "errors")
2903 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
2904 info, err := os.Stat("errors.test" + exeSuffix)
2905 if err != nil {
2906 t.Fatal(err)
2908 start = truncateLike(start, info.ModTime())
2909 if info.ModTime().Before(start) {
2910 t.Fatalf("mtime of errors.test predates test -c command (%v < %v)", info.ModTime(), start)
2913 start = time.Now()
2914 tg.run("test", "-x", "-c", "-o", "errors2.test", "errors")
2915 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
2916 info, err = os.Stat("errors2.test")
2917 if err != nil {
2918 t.Fatal(err)
2920 start = truncateLike(start, info.ModTime())
2921 if info.ModTime().Before(start) {
2922 t.Fatalf("mtime of errors2.test predates test -c command (%v < %v)", info.ModTime(), start)
2926 // truncateLike returns the result of truncating t to the apparent precision of p.
2927 func truncateLike(t, p time.Time) time.Time {
2928 nano := p.UnixNano()
2929 d := 1 * time.Nanosecond
2930 for nano%int64(d) == 0 && d < 1*time.Second {
2931 d *= 10
2933 for nano%int64(d) == 0 && d < 2*time.Second {
2934 d *= 2
2936 return t.Truncate(d)
2939 // cmd/cgo: undefined reference when linking a C-library using gccgo
2940 func TestIssue7573(t *testing.T) {
2941 if !canCgo {
2942 t.Skip("skipping because cgo not enabled")
2944 if _, err := exec.LookPath("gccgo"); err != nil {
2945 t.Skip("skipping because no gccgo compiler found")
2947 t.Skip("golang.org/issue/22472")
2949 tg := testgo(t)
2950 defer tg.cleanup()
2951 tg.parallel()
2952 tg.tempFile("src/cgoref/cgoref.go", `
2953 package main
2954 // #cgo LDFLAGS: -L alibpath -lalib
2955 // void f(void) {}
2956 import "C"
2958 func main() { C.f() }`)
2959 tg.setenv("GOPATH", tg.path("."))
2960 tg.run("build", "-n", "-compiler", "gccgo", "cgoref")
2961 tg.grepStderr(`gccgo.*\-L [^ ]*alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`)
2964 func TestListTemplateContextFunction(t *testing.T) {
2965 t.Parallel()
2966 for _, tt := range []struct {
2967 v string
2968 want string
2970 {"GOARCH", runtime.GOARCH},
2971 {"GOOS", runtime.GOOS},
2972 {"GOROOT", filepath.Clean(runtime.GOROOT())},
2973 {"GOPATH", os.Getenv("GOPATH")},
2974 {"CgoEnabled", ""},
2975 {"UseAllFiles", ""},
2976 {"Compiler", ""},
2977 {"BuildTags", ""},
2978 {"ReleaseTags", ""},
2979 {"InstallSuffix", ""},
2981 tt := tt
2982 t.Run(tt.v, func(t *testing.T) {
2983 tg := testgo(t)
2984 tg.parallel()
2985 defer tg.cleanup()
2986 tmpl := "{{context." + tt.v + "}}"
2987 tg.run("list", "-f", tmpl)
2988 if tt.want == "" {
2989 return
2991 if got := strings.TrimSpace(tg.getStdout()); got != tt.want {
2992 t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want)
2998 // cmd/go: "go test" should fail if package does not build
2999 func TestIssue7108(t *testing.T) {
3000 tg := testgo(t)
3001 defer tg.cleanup()
3002 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3003 tg.runFail("test", "notest")
3006 // cmd/go: go test -a foo does not rebuild regexp.
3007 func TestIssue6844(t *testing.T) {
3008 if testing.Short() {
3009 t.Skip("don't rebuild the standard library in short mode")
3012 tg := testgo(t)
3013 defer tg.cleanup()
3014 tg.creatingTemp("deps.test" + exeSuffix)
3015 tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go")
3016 tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp")
3019 func TestBuildDashIInstallsDependencies(t *testing.T) {
3020 tooSlow(t)
3022 tg := testgo(t)
3023 defer tg.cleanup()
3024 tg.parallel()
3025 tg.tempFile("src/x/y/foo/foo.go", `package foo
3026 func F() {}`)
3027 tg.tempFile("src/x/y/bar/bar.go", `package bar
3028 import "x/y/foo"
3029 func F() { foo.F() }`)
3030 tg.setenv("GOPATH", tg.path("."))
3032 // don't let build -i overwrite runtime
3033 tg.wantNotStale("runtime", "", "must be non-stale before build -i")
3035 checkbar := func(desc string) {
3036 tg.run("build", "-v", "-i", "x/y/bar")
3037 tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo")
3038 tg.run("build", "-v", "-i", "x/y/bar")
3039 tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo")
3041 checkbar("pkg")
3043 tg.creatingTemp("bar" + exeSuffix)
3044 tg.sleep()
3045 tg.tempFile("src/x/y/foo/foo.go", `package foo
3046 func F() { F() }`)
3047 tg.tempFile("src/x/y/bar/bar.go", `package main
3048 import "x/y/foo"
3049 func main() { foo.F() }`)
3050 checkbar("cmd")
3053 func TestGoBuildInTestOnlyDirectoryFailsWithAGoodError(t *testing.T) {
3054 tg := testgo(t)
3055 defer tg.cleanup()
3056 tg.runFail("build", "./testdata/testonly")
3057 tg.grepStderr("no non-test Go files in", "go build ./testdata/testonly produced unexpected error")
3060 func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) {
3061 tg := testgo(t)
3062 defer tg.cleanup()
3063 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3064 tg.runFail("test", "-c", "testcycle/p3")
3065 tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error")
3067 tg.runFail("test", "-c", "testcycle/q1")
3068 tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error")
3071 func TestGoTestFooTestWorks(t *testing.T) {
3072 tg := testgo(t)
3073 defer tg.cleanup()
3074 tg.run("test", "testdata/standalone_test.go")
3077 // Issue 22388
3078 func TestGoTestMainWithWrongSignature(t *testing.T) {
3079 tg := testgo(t)
3080 defer tg.cleanup()
3081 tg.runFail("test", "testdata/standalone_main_wrong_test.go")
3082 tg.grepStderr(`wrong signature for TestMain, must be: func TestMain\(m \*testing.M\)`, "detected wrong error message")
3085 func TestGoTestMainAsNormalTest(t *testing.T) {
3086 tg := testgo(t)
3087 defer tg.cleanup()
3088 tg.run("test", "testdata/standalone_main_normal_test.go")
3089 tg.grepBoth(okPattern, "go test did not say ok")
3092 func TestGoTestMainTwice(t *testing.T) {
3093 tg := testgo(t)
3094 defer tg.cleanup()
3095 tg.makeTempdir()
3096 tg.setenv("GOCACHE", tg.tempdir)
3097 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3098 tg.run("test", "-v", "multimain")
3099 if strings.Count(tg.getStdout(), "notwithstanding") != 2 {
3100 t.Fatal("tests did not run twice")
3104 func TestGoTestFlagsAfterPackage(t *testing.T) {
3105 tooSlow(t)
3106 tg := testgo(t)
3107 defer tg.cleanup()
3108 tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags.
3109 tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags.
3112 func TestGoTestXtestonlyWorks(t *testing.T) {
3113 tg := testgo(t)
3114 defer tg.cleanup()
3115 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3116 tg.run("clean", "-i", "xtestonly")
3117 tg.run("test", "xtestonly")
3120 func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) {
3121 tg := testgo(t)
3122 defer tg.cleanup()
3123 tg.run("test", "-v", "./testdata/norunexample")
3124 tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built")
3127 func TestGoGenerateHandlesSimpleCommand(t *testing.T) {
3128 if runtime.GOOS == "windows" {
3129 t.Skip("skipping because windows has no echo command")
3132 tg := testgo(t)
3133 defer tg.cleanup()
3134 tg.run("generate", "./testdata/generate/test1.go")
3135 tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output")
3138 func TestGoGenerateHandlesCommandAlias(t *testing.T) {
3139 if runtime.GOOS == "windows" {
3140 t.Skip("skipping because windows has no echo command")
3143 tg := testgo(t)
3144 defer tg.cleanup()
3145 tg.run("generate", "./testdata/generate/test2.go")
3146 tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output")
3149 func TestGoGenerateVariableSubstitution(t *testing.T) {
3150 if runtime.GOOS == "windows" {
3151 t.Skip("skipping because windows has no echo command")
3154 tg := testgo(t)
3155 defer tg.cleanup()
3156 tg.run("generate", "./testdata/generate/test3.go")
3157 tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output")
3160 func TestGoGenerateRunFlag(t *testing.T) {
3161 if runtime.GOOS == "windows" {
3162 t.Skip("skipping because windows has no echo command")
3165 tg := testgo(t)
3166 defer tg.cleanup()
3167 tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go")
3168 tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes")
3169 tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no")
3172 func TestGoGenerateEnv(t *testing.T) {
3173 switch runtime.GOOS {
3174 case "plan9", "windows":
3175 t.Skipf("skipping because %s does not have the env command", runtime.GOOS)
3177 tg := testgo(t)
3178 defer tg.cleanup()
3179 tg.parallel()
3180 tg.tempFile("env.go", "package main\n\n//go:generate env")
3181 tg.run("generate", tg.path("env.go"))
3182 for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} {
3183 tg.grepStdout("^"+v+"=", "go generate environment missing "+v)
3187 func TestGoGenerateBadImports(t *testing.T) {
3188 if runtime.GOOS == "windows" {
3189 t.Skip("skipping because windows has no echo command")
3192 // This package has an invalid import causing an import cycle,
3193 // but go generate is supposed to still run.
3194 tg := testgo(t)
3195 defer tg.cleanup()
3196 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3197 tg.run("generate", "gencycle")
3198 tg.grepStdout("hello world", "go generate gencycle did not run generator")
3201 func TestGoGetCustomDomainWildcard(t *testing.T) {
3202 testenv.MustHaveExternalNetwork(t)
3204 tg := testgo(t)
3205 defer tg.cleanup()
3206 tg.makeTempdir()
3207 tg.setenv("GOPATH", tg.path("."))
3208 tg.run("get", "-u", "rsc.io/pdf/...")
3209 tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd")
3212 func TestGoGetInternalWildcard(t *testing.T) {
3213 testenv.MustHaveExternalNetwork(t)
3215 tg := testgo(t)
3216 defer tg.cleanup()
3217 tg.makeTempdir()
3218 tg.setenv("GOPATH", tg.path("."))
3219 // used to fail with errors about internal packages
3220 tg.run("get", "github.com/rsc/go-get-issue-11960/...")
3223 func TestGoVetWithExternalTests(t *testing.T) {
3224 tg := testgo(t)
3225 defer tg.cleanup()
3226 tg.makeTempdir()
3227 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3228 tg.runFail("vet", "vetpkg")
3229 tg.grepBoth("Printf", "go vet vetpkg did not find missing argument for Printf")
3232 func TestGoVetWithTags(t *testing.T) {
3233 tg := testgo(t)
3234 defer tg.cleanup()
3235 tg.makeTempdir()
3236 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3237 tg.runFail("vet", "-tags", "tagtest", "vetpkg")
3238 tg.grepBoth(`c\.go.*Printf`, "go vet vetpkg did not run scan tagged file")
3241 func TestGoVetWithFlagsOn(t *testing.T) {
3242 tg := testgo(t)
3243 defer tg.cleanup()
3244 tg.makeTempdir()
3245 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3246 tg.runFail("vet", "-printf", "vetpkg")
3247 tg.grepBoth("Printf", "go vet -printf vetpkg did not find missing argument for Printf")
3250 func TestGoVetWithFlagsOff(t *testing.T) {
3251 tg := testgo(t)
3252 defer tg.cleanup()
3253 tg.makeTempdir()
3254 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3255 tg.run("vet", "-printf=false", "vetpkg")
3258 // Issue 23395.
3259 func TestGoVetWithOnlyTestFiles(t *testing.T) {
3260 tg := testgo(t)
3261 defer tg.cleanup()
3262 tg.parallel()
3263 tg.tempFile("src/p/p_test.go", "package p; import \"testing\"; func TestMe(*testing.T) {}")
3264 tg.setenv("GOPATH", tg.path("."))
3265 tg.run("vet", "p")
3268 // Issue 9767, 19769.
3269 func TestGoGetDotSlashDownload(t *testing.T) {
3270 testenv.MustHaveExternalNetwork(t)
3272 tg := testgo(t)
3273 defer tg.cleanup()
3274 tg.tempDir("src/rsc.io")
3275 tg.setenv("GOPATH", tg.path("."))
3276 tg.cd(tg.path("src/rsc.io"))
3277 tg.run("get", "./pprof_mac_fix")
3280 // Issue 13037: Was not parsing <meta> tags in 404 served over HTTPS
3281 func TestGoGetHTTPS404(t *testing.T) {
3282 testenv.MustHaveExternalNetwork(t)
3283 switch runtime.GOOS {
3284 case "darwin", "linux", "freebsd":
3285 default:
3286 t.Skipf("test case does not work on %s", runtime.GOOS)
3289 tg := testgo(t)
3290 defer tg.cleanup()
3291 tg.tempDir("src")
3292 tg.setenv("GOPATH", tg.path("."))
3293 tg.run("get", "bazil.org/fuse/fs/fstestutil")
3296 // Test that you cannot import a main package.
3297 // See golang.org/issue/4210 and golang.org/issue/17475.
3298 func TestImportMain(t *testing.T) {
3299 tooSlow(t)
3301 tg := testgo(t)
3302 tg.parallel()
3303 defer tg.cleanup()
3305 // Importing package main from that package main's test should work.
3306 tg.tempFile("src/x/main.go", `package main
3307 var X int
3308 func main() {}`)
3309 tg.tempFile("src/x/main_test.go", `package main_test
3310 import xmain "x"
3311 import "testing"
3312 var _ = xmain.X
3313 func TestFoo(t *testing.T) {}
3315 tg.setenv("GOPATH", tg.path("."))
3316 tg.creatingTemp("x" + exeSuffix)
3317 tg.run("build", "x")
3318 tg.run("test", "x")
3320 // Importing package main from another package should fail.
3321 tg.tempFile("src/p1/p.go", `package p1
3322 import xmain "x"
3323 var _ = xmain.X
3325 tg.runFail("build", "p1")
3326 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3328 // ... even in that package's test.
3329 tg.tempFile("src/p2/p.go", `package p2
3331 tg.tempFile("src/p2/p_test.go", `package p2
3332 import xmain "x"
3333 import "testing"
3334 var _ = xmain.X
3335 func TestFoo(t *testing.T) {}
3337 tg.run("build", "p2")
3338 tg.runFail("test", "p2")
3339 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3341 // ... even if that package's test is an xtest.
3342 tg.tempFile("src/p3/p.go", `package p
3344 tg.tempFile("src/p3/p_test.go", `package p_test
3345 import xmain "x"
3346 import "testing"
3347 var _ = xmain.X
3348 func TestFoo(t *testing.T) {}
3350 tg.run("build", "p3")
3351 tg.runFail("test", "p3")
3352 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3354 // ... even if that package is a package main
3355 tg.tempFile("src/p4/p.go", `package main
3356 func main() {}
3358 tg.tempFile("src/p4/p_test.go", `package main
3359 import xmain "x"
3360 import "testing"
3361 var _ = xmain.X
3362 func TestFoo(t *testing.T) {}
3364 tg.creatingTemp("p4" + exeSuffix)
3365 tg.run("build", "p4")
3366 tg.runFail("test", "p4")
3367 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3369 // ... even if that package is a package main using an xtest.
3370 tg.tempFile("src/p5/p.go", `package main
3371 func main() {}
3373 tg.tempFile("src/p5/p_test.go", `package main_test
3374 import xmain "x"
3375 import "testing"
3376 var _ = xmain.X
3377 func TestFoo(t *testing.T) {}
3379 tg.creatingTemp("p5" + exeSuffix)
3380 tg.run("build", "p5")
3381 tg.runFail("test", "p5")
3382 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3385 // Test that you cannot use a local import in a package
3386 // accessed by a non-local import (found in a GOPATH/GOROOT).
3387 // See golang.org/issue/17475.
3388 func TestImportLocal(t *testing.T) {
3389 tooSlow(t)
3391 tg := testgo(t)
3392 tg.parallel()
3393 defer tg.cleanup()
3395 tg.tempFile("src/dir/x/x.go", `package x
3396 var X int
3398 tg.setenv("GOPATH", tg.path("."))
3399 tg.run("build", "dir/x")
3401 // Ordinary import should work.
3402 tg.tempFile("src/dir/p0/p.go", `package p0
3403 import "dir/x"
3404 var _ = x.X
3406 tg.run("build", "dir/p0")
3408 // Relative import should not.
3409 tg.tempFile("src/dir/p1/p.go", `package p1
3410 import "../x"
3411 var _ = x.X
3413 tg.runFail("build", "dir/p1")
3414 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3416 // ... even in a test.
3417 tg.tempFile("src/dir/p2/p.go", `package p2
3419 tg.tempFile("src/dir/p2/p_test.go", `package p2
3420 import "../x"
3421 import "testing"
3422 var _ = x.X
3423 func TestFoo(t *testing.T) {}
3425 tg.run("build", "dir/p2")
3426 tg.runFail("test", "dir/p2")
3427 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3429 // ... even in an xtest.
3430 tg.tempFile("src/dir/p2/p_test.go", `package p2_test
3431 import "../x"
3432 import "testing"
3433 var _ = x.X
3434 func TestFoo(t *testing.T) {}
3436 tg.run("build", "dir/p2")
3437 tg.runFail("test", "dir/p2")
3438 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3440 // Relative import starting with ./ should not work either.
3441 tg.tempFile("src/dir/d.go", `package dir
3442 import "./x"
3443 var _ = x.X
3445 tg.runFail("build", "dir")
3446 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3448 // ... even in a test.
3449 tg.tempFile("src/dir/d.go", `package dir
3451 tg.tempFile("src/dir/d_test.go", `package dir
3452 import "./x"
3453 import "testing"
3454 var _ = x.X
3455 func TestFoo(t *testing.T) {}
3457 tg.run("build", "dir")
3458 tg.runFail("test", "dir")
3459 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3461 // ... even in an xtest.
3462 tg.tempFile("src/dir/d_test.go", `package dir_test
3463 import "./x"
3464 import "testing"
3465 var _ = x.X
3466 func TestFoo(t *testing.T) {}
3468 tg.run("build", "dir")
3469 tg.runFail("test", "dir")
3470 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3472 // Relative import plain ".." should not work.
3473 tg.tempFile("src/dir/x/y/y.go", `package dir
3474 import ".."
3475 var _ = x.X
3477 tg.runFail("build", "dir/x/y")
3478 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3480 // ... even in a test.
3481 tg.tempFile("src/dir/x/y/y.go", `package y
3483 tg.tempFile("src/dir/x/y/y_test.go", `package y
3484 import ".."
3485 import "testing"
3486 var _ = x.X
3487 func TestFoo(t *testing.T) {}
3489 tg.run("build", "dir/x/y")
3490 tg.runFail("test", "dir/x/y")
3491 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3493 // ... even in an x test.
3494 tg.tempFile("src/dir/x/y/y_test.go", `package y_test
3495 import ".."
3496 import "testing"
3497 var _ = x.X
3498 func TestFoo(t *testing.T) {}
3500 tg.run("build", "dir/x/y")
3501 tg.runFail("test", "dir/x/y")
3502 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3504 // Relative import "." should not work.
3505 tg.tempFile("src/dir/x/xx.go", `package x
3506 import "."
3507 var _ = x.X
3509 tg.runFail("build", "dir/x")
3510 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3512 // ... even in a test.
3513 tg.tempFile("src/dir/x/xx.go", `package x
3515 tg.tempFile("src/dir/x/xx_test.go", `package x
3516 import "."
3517 import "testing"
3518 var _ = x.X
3519 func TestFoo(t *testing.T) {}
3521 tg.run("build", "dir/x")
3522 tg.runFail("test", "dir/x")
3523 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3525 // ... even in an xtest.
3526 tg.tempFile("src/dir/x/xx.go", `package x
3528 tg.tempFile("src/dir/x/xx_test.go", `package x_test
3529 import "."
3530 import "testing"
3531 var _ = x.X
3532 func TestFoo(t *testing.T) {}
3534 tg.run("build", "dir/x")
3535 tg.runFail("test", "dir/x")
3536 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3539 func TestGoGetInsecure(t *testing.T) {
3540 testenv.MustHaveExternalNetwork(t)
3542 tg := testgo(t)
3543 defer tg.cleanup()
3544 tg.makeTempdir()
3545 tg.setenv("GOPATH", tg.path("."))
3546 tg.failSSH()
3548 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3550 // Try go get -d of HTTP-only repo (should fail).
3551 tg.runFail("get", "-d", repo)
3553 // Try again with -insecure (should succeed).
3554 tg.run("get", "-d", "-insecure", repo)
3556 // Try updating without -insecure (should fail).
3557 tg.runFail("get", "-d", "-u", "-f", repo)
3560 func TestGoGetUpdateInsecure(t *testing.T) {
3561 testenv.MustHaveExternalNetwork(t)
3563 tg := testgo(t)
3564 defer tg.cleanup()
3565 tg.makeTempdir()
3566 tg.setenv("GOPATH", tg.path("."))
3568 const repo = "github.com/golang/example"
3570 // Clone the repo via HTTP manually.
3571 cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
3572 if out, err := cmd.CombinedOutput(); err != nil {
3573 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3576 // Update without -insecure should fail.
3577 // Update with -insecure should succeed.
3578 // We need -f to ignore import comments.
3579 const pkg = repo + "/hello"
3580 tg.runFail("get", "-d", "-u", "-f", pkg)
3581 tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
3584 func TestGoGetInsecureCustomDomain(t *testing.T) {
3585 testenv.MustHaveExternalNetwork(t)
3587 tg := testgo(t)
3588 defer tg.cleanup()
3589 tg.makeTempdir()
3590 tg.setenv("GOPATH", tg.path("."))
3592 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3593 tg.runFail("get", "-d", repo)
3594 tg.run("get", "-d", "-insecure", repo)
3597 func TestGoRunDirs(t *testing.T) {
3598 tg := testgo(t)
3599 defer tg.cleanup()
3600 tg.cd("testdata/rundir")
3601 tg.runFail("run", "x.go", "sub/sub.go")
3602 tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
3603 tg.runFail("run", "sub/sub.go", "x.go")
3604 tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
3607 func TestGoInstallPkgdir(t *testing.T) {
3608 skipIfGccgo(t, "gccgo has no standard packages")
3609 tooSlow(t)
3611 tg := testgo(t)
3612 tg.parallel()
3613 defer tg.cleanup()
3614 tg.makeTempdir()
3615 pkg := tg.path(".")
3616 tg.run("install", "-pkgdir", pkg, "sync")
3617 tg.mustExist(filepath.Join(pkg, "sync.a"))
3618 tg.mustNotExist(filepath.Join(pkg, "sync/atomic.a"))
3619 tg.run("install", "-i", "-pkgdir", pkg, "sync")
3620 tg.mustExist(filepath.Join(pkg, "sync.a"))
3621 tg.mustExist(filepath.Join(pkg, "sync/atomic.a"))
3624 func TestGoTestRaceInstallCgo(t *testing.T) {
3625 if !canRace {
3626 t.Skip("skipping because race detector not supported")
3629 // golang.org/issue/10500.
3630 // This used to install a race-enabled cgo.
3631 tg := testgo(t)
3632 defer tg.cleanup()
3633 tg.run("tool", "-n", "cgo")
3634 cgo := strings.TrimSpace(tg.stdout.String())
3635 old, err := os.Stat(cgo)
3636 tg.must(err)
3637 tg.run("test", "-race", "-i", "runtime/race")
3638 new, err := os.Stat(cgo)
3639 tg.must(err)
3640 if !new.ModTime().Equal(old.ModTime()) {
3641 t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
3645 func TestGoTestRaceFailures(t *testing.T) {
3646 tooSlow(t)
3648 if !canRace {
3649 t.Skip("skipping because race detector not supported")
3652 tg := testgo(t)
3653 tg.parallel()
3654 defer tg.cleanup()
3655 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3657 tg.run("test", "testrace")
3659 tg.runFail("test", "-race", "testrace")
3660 tg.grepStdout("FAIL: TestRace", "TestRace did not fail")
3661 tg.grepBothNot("PASS", "something passed")
3663 tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".")
3664 tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail")
3665 tg.grepBothNot("PASS", "something passed")
3668 func TestGoTestImportErrorStack(t *testing.T) {
3669 const out = `package testdep/p1 (test)
3670 imports testdep/p2
3671 imports testdep/p3: build constraints exclude all Go files `
3673 tg := testgo(t)
3674 defer tg.cleanup()
3675 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3676 tg.runFail("test", "testdep/p1")
3677 if !strings.Contains(tg.stderr.String(), out) {
3678 t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String())
3682 func TestGoGetUpdate(t *testing.T) {
3683 // golang.org/issue/9224.
3684 // The recursive updating was trying to walk to
3685 // former dependencies, not current ones.
3687 testenv.MustHaveExternalNetwork(t)
3689 tg := testgo(t)
3690 defer tg.cleanup()
3691 tg.makeTempdir()
3692 tg.setenv("GOPATH", tg.path("."))
3694 rewind := func() {
3695 tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
3696 cmd := exec.Command("git", "reset", "--hard", "HEAD~")
3697 cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
3698 out, err := cmd.CombinedOutput()
3699 if err != nil {
3700 t.Fatalf("git: %v\n%s", err, out)
3704 rewind()
3705 tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3707 // Again with -d -u.
3708 rewind()
3709 tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3712 // Issue #20512.
3713 func TestGoGetRace(t *testing.T) {
3714 testenv.MustHaveExternalNetwork(t)
3715 if !canRace {
3716 t.Skip("skipping because race detector not supported")
3719 tg := testgo(t)
3720 defer tg.cleanup()
3721 tg.makeTempdir()
3722 tg.setenv("GOPATH", tg.path("."))
3723 tg.run("get", "-race", "github.com/rsc/go-get-issue-9224-cmd")
3726 func TestGoGetDomainRoot(t *testing.T) {
3727 // golang.org/issue/9357.
3728 // go get foo.io (not foo.io/subdir) was not working consistently.
3730 testenv.MustHaveExternalNetwork(t)
3732 tg := testgo(t)
3733 defer tg.cleanup()
3734 tg.makeTempdir()
3735 tg.setenv("GOPATH", tg.path("."))
3737 // go-get-issue-9357.appspot.com is running
3738 // the code at github.com/rsc/go-get-issue-9357,
3739 // a trivial Go on App Engine app that serves a
3740 // <meta> tag for the domain root.
3741 tg.run("get", "-d", "go-get-issue-9357.appspot.com")
3742 tg.run("get", "go-get-issue-9357.appspot.com")
3743 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3745 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3746 tg.run("get", "go-get-issue-9357.appspot.com")
3748 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3749 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3752 func TestGoInstallShadowedGOPATH(t *testing.T) {
3753 // golang.org/issue/3652.
3754 // go get foo.io (not foo.io/subdir) was not working consistently.
3756 testenv.MustHaveExternalNetwork(t)
3758 tg := testgo(t)
3759 defer tg.cleanup()
3760 tg.makeTempdir()
3761 tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
3763 tg.tempDir("gopath1/src/test")
3764 tg.tempDir("gopath2/src/test")
3765 tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
3767 tg.cd(tg.path("gopath2/src/test"))
3768 tg.runFail("install")
3769 tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
3772 func TestGoBuildGOPATHOrder(t *testing.T) {
3773 // golang.org/issue/14176#issuecomment-179895769
3774 // golang.org/issue/14192
3775 // -I arguments to compiler could end up not in GOPATH order,
3776 // leading to unexpected import resolution in the compiler.
3777 // This is still not a complete fix (see golang.org/issue/14271 and next test)
3778 // but it is clearly OK and enough to fix both of the two reported
3779 // instances of the underlying problem. It will have to do for now.
3781 tg := testgo(t)
3782 defer tg.cleanup()
3783 tg.makeTempdir()
3784 tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2"))
3786 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3787 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3788 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3789 tg.tempFile("p1/src/bar/bar.go", `
3790 package bar
3791 import _ "baz"
3792 import _ "foo"
3795 tg.run("install", "-x", "bar")
3798 func TestGoBuildGOPATHOrderBroken(t *testing.T) {
3799 // This test is known not to work.
3800 // See golang.org/issue/14271.
3801 t.Skip("golang.org/issue/14271")
3803 tg := testgo(t)
3804 defer tg.cleanup()
3805 tg.makeTempdir()
3807 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3808 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3809 tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n")
3810 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3811 tg.tempFile("p1/src/bar/bar.go", `
3812 package bar
3813 import _ "baz"
3814 import _ "foo"
3817 colon := string(filepath.ListSeparator)
3818 tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2"))
3819 tg.run("install", "-x", "bar")
3821 tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1"))
3822 tg.run("install", "-x", "bar")
3825 func TestIssue11709(t *testing.T) {
3826 tg := testgo(t)
3827 defer tg.cleanup()
3828 tg.tempFile("run.go", `
3829 package main
3830 import "os"
3831 func main() {
3832 if os.Getenv("TERM") != "" {
3833 os.Exit(1)
3836 tg.unsetenv("TERM")
3837 tg.run("run", tg.path("run.go"))
3840 func TestIssue12096(t *testing.T) {
3841 tg := testgo(t)
3842 defer tg.cleanup()
3843 tg.tempFile("test_test.go", `
3844 package main
3845 import ("os"; "testing")
3846 func TestEnv(t *testing.T) {
3847 if os.Getenv("TERM") != "" {
3848 t.Fatal("TERM is set")
3851 tg.unsetenv("TERM")
3852 tg.run("test", tg.path("test_test.go"))
3855 func TestGoBuildOutput(t *testing.T) {
3856 skipIfGccgo(t, "gccgo has no standard packages")
3857 tooSlow(t)
3858 tg := testgo(t)
3859 defer tg.cleanup()
3861 tg.makeTempdir()
3862 tg.cd(tg.path("."))
3864 nonExeSuffix := ".exe"
3865 if exeSuffix == ".exe" {
3866 nonExeSuffix = ""
3869 tg.tempFile("x.go", "package main\nfunc main(){}\n")
3870 tg.run("build", "x.go")
3871 tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
3872 tg.must(os.Remove(tg.path("x" + exeSuffix)))
3873 tg.mustNotExist("x" + nonExeSuffix)
3875 tg.run("build", "-o", "myprog", "x.go")
3876 tg.mustNotExist("x")
3877 tg.mustNotExist("x.exe")
3878 tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
3879 tg.mustNotExist("myprog.exe")
3881 tg.tempFile("p.go", "package p\n")
3882 tg.run("build", "p.go")
3883 tg.mustNotExist("p")
3884 tg.mustNotExist("p.a")
3885 tg.mustNotExist("p.o")
3886 tg.mustNotExist("p.exe")
3888 tg.run("build", "-o", "p.a", "p.go")
3889 tg.wantArchive("p.a")
3891 tg.run("build", "cmd/gofmt")
3892 tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
3893 tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
3894 tg.mustNotExist("gofmt" + nonExeSuffix)
3896 tg.run("build", "-o", "mygofmt", "cmd/gofmt")
3897 tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
3898 tg.mustNotExist("mygofmt.exe")
3899 tg.mustNotExist("gofmt")
3900 tg.mustNotExist("gofmt.exe")
3902 tg.run("build", "sync/atomic")
3903 tg.mustNotExist("atomic")
3904 tg.mustNotExist("atomic.exe")
3906 tg.run("build", "-o", "myatomic.a", "sync/atomic")
3907 tg.wantArchive("myatomic.a")
3908 tg.mustNotExist("atomic")
3909 tg.mustNotExist("atomic.a")
3910 tg.mustNotExist("atomic.exe")
3912 tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
3913 tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
3916 func TestGoBuildARM(t *testing.T) {
3917 if testing.Short() {
3918 t.Skip("skipping cross-compile in short mode")
3921 tg := testgo(t)
3922 defer tg.cleanup()
3924 tg.makeTempdir()
3925 tg.cd(tg.path("."))
3927 tg.setenv("GOARCH", "arm")
3928 tg.setenv("GOOS", "linux")
3929 tg.setenv("GOARM", "5")
3930 tg.tempFile("hello.go", `package main
3931 func main() {}`)
3932 tg.run("build", "hello.go")
3933 tg.grepStderrNot("unable to find math.a", "did not build math.a correctly")
3936 // For issue 14337.
3937 func TestParallelTest(t *testing.T) {
3938 tooSlow(t)
3939 tg := testgo(t)
3940 tg.parallel()
3941 defer tg.cleanup()
3942 tg.makeTempdir()
3943 const testSrc = `package package_test
3944 import (
3945 "testing"
3947 func TestTest(t *testing.T) {
3949 tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
3950 tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
3951 tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
3952 tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
3953 tg.setenv("GOPATH", tg.path("."))
3954 tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
3957 func TestCgoConsistentResults(t *testing.T) {
3958 tooSlow(t)
3959 if !canCgo {
3960 t.Skip("skipping because cgo not enabled")
3962 switch runtime.GOOS {
3963 case "freebsd":
3964 testenv.SkipFlaky(t, 15405)
3965 case "solaris":
3966 testenv.SkipFlaky(t, 13247)
3969 tg := testgo(t)
3970 defer tg.cleanup()
3971 tg.parallel()
3972 tg.makeTempdir()
3973 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3974 exe1 := tg.path("cgotest1" + exeSuffix)
3975 exe2 := tg.path("cgotest2" + exeSuffix)
3976 tg.run("build", "-o", exe1, "cgotest")
3977 tg.run("build", "-x", "-o", exe2, "cgotest")
3978 b1, err := ioutil.ReadFile(exe1)
3979 tg.must(err)
3980 b2, err := ioutil.ReadFile(exe2)
3981 tg.must(err)
3983 if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) {
3984 t.Skip("skipping because C compiler does not support -fdebug-prefix-map")
3986 if !bytes.Equal(b1, b2) {
3987 t.Error("building cgotest twice did not produce the same output")
3991 // Issue 14444: go get -u .../ duplicate loads errors
3992 func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) {
3993 testenv.MustHaveExternalNetwork(t)
3995 tg := testgo(t)
3996 defer tg.cleanup()
3997 tg.makeTempdir()
3998 tg.setenv("GOPATH", tg.path("."))
3999 tg.run("get", "-u", ".../")
4000 tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache")
4003 // Issue 17119 more duplicate load errors
4004 func TestIssue17119(t *testing.T) {
4005 testenv.MustHaveExternalNetwork(t)
4007 tg := testgo(t)
4008 defer tg.cleanup()
4009 tg.parallel()
4010 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4011 tg.runFail("build", "dupload")
4012 tg.grepBothNot("duplicate load|internal error", "internal error")
4015 func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) {
4016 tg := testgo(t)
4017 defer tg.cleanup()
4018 // TODO: tg.parallel()
4019 tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal")
4020 tg.grepBothNot("^ok", "test passed unexpectedly")
4021 tg.grepBoth("FAIL.*benchfatal", "test did not run everything")
4024 func TestBinaryOnlyPackages(t *testing.T) {
4025 tooSlow(t)
4027 tg := testgo(t)
4028 defer tg.cleanup()
4029 tg.parallel()
4030 tg.makeTempdir()
4031 tg.setenv("GOPATH", tg.path("."))
4033 tg.tempFile("src/p1/p1.go", `//go:binary-only-package
4035 package p1
4037 tg.wantStale("p1", "missing or invalid binary-only package", "p1 is binary-only but has no binary, should be stale")
4038 tg.runFail("install", "p1")
4039 tg.grepStderr("missing or invalid binary-only package", "did not report attempt to compile binary-only package")
4041 tg.tempFile("src/p1/p1.go", `
4042 package p1
4043 import "fmt"
4044 func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } }
4046 tg.run("install", "p1")
4047 os.Remove(tg.path("src/p1/p1.go"))
4048 tg.mustNotExist(tg.path("src/p1/p1.go"))
4050 tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great
4052 package p2
4053 import "p1"
4054 func F() { p1.F(true) }
4056 tg.runFail("install", "p2")
4057 tg.grepStderr("no Go files", "did not complain about missing sources")
4059 tg.tempFile("src/p1/missing.go", `//go:binary-only-package
4061 package p1
4062 import _ "fmt"
4063 func G()
4065 tg.wantNotStale("p1", "binary-only package", "should NOT want to rebuild p1 (first)")
4066 tg.run("install", "-x", "p1") // no-op, up to date
4067 tg.grepBothNot(`[\\/]compile`, "should not have run compiler")
4068 tg.run("install", "p2") // does not rebuild p1 (or else p2 will fail)
4069 tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
4071 // changes to the non-source-code do not matter,
4072 // and only one file needs the special comment.
4073 tg.tempFile("src/p1/missing2.go", `
4074 package p1
4075 func H()
4077 tg.wantNotStale("p1", "binary-only package", "should NOT want to rebuild p1 (second)")
4078 tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
4080 tg.tempFile("src/p3/p3.go", `
4081 package main
4082 import (
4083 "p1"
4084 "p2"
4086 func main() {
4087 p1.F(false)
4088 p2.F()
4091 tg.run("install", "p3")
4093 tg.run("run", tg.path("src/p3/p3.go"))
4094 tg.grepStdout("hello from p1", "did not see message from p1")
4096 tg.tempFile("src/p4/p4.go", `package main`)
4097 // The odd string split below avoids vet complaining about
4098 // a // +build line appearing too late in this source file.
4099 tg.tempFile("src/p4/p4not.go", `//go:binary-only-package
4101 /`+`/ +build asdf
4103 package main
4105 tg.run("list", "-f", "{{.BinaryOnly}}", "p4")
4106 tg.grepStdout("false", "did not see BinaryOnly=false for p4")
4109 // Issue 16050.
4110 func TestAlwaysLinkSysoFiles(t *testing.T) {
4111 tg := testgo(t)
4112 defer tg.cleanup()
4113 tg.parallel()
4114 tg.tempDir("src/syso")
4115 tg.tempFile("src/syso/a.syso", ``)
4116 tg.tempFile("src/syso/b.go", `package syso`)
4117 tg.setenv("GOPATH", tg.path("."))
4119 // We should see the .syso file regardless of the setting of
4120 // CGO_ENABLED.
4122 tg.setenv("CGO_ENABLED", "1")
4123 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4124 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1")
4126 tg.setenv("CGO_ENABLED", "0")
4127 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4128 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0")
4131 // Issue 16120.
4132 func TestGenerateUsesBuildContext(t *testing.T) {
4133 if runtime.GOOS == "windows" {
4134 t.Skip("this test won't run under Windows")
4137 tg := testgo(t)
4138 defer tg.cleanup()
4139 tg.parallel()
4140 tg.tempDir("src/gen")
4141 tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n")
4142 tg.setenv("GOPATH", tg.path("."))
4144 tg.setenv("GOOS", "linux")
4145 tg.setenv("GOARCH", "amd64")
4146 tg.run("generate", "gen")
4147 tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination")
4149 tg.setenv("GOOS", "darwin")
4150 tg.setenv("GOARCH", "386")
4151 tg.run("generate", "gen")
4152 tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination")
4155 // Issue 14450: go get -u .../ tried to import not downloaded package
4156 func TestGoGetUpdateWithWildcard(t *testing.T) {
4157 testenv.MustHaveExternalNetwork(t)
4159 tg := testgo(t)
4160 defer tg.cleanup()
4161 tg.parallel()
4162 tg.makeTempdir()
4163 tg.setenv("GOPATH", tg.path("."))
4164 const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a"
4165 tg.run("get", aPkgImportPath)
4166 tg.run("get", "-u", ".../")
4167 tg.grepStderrNot("cannot find package", "did not update packages given wildcard path")
4169 var expectedPkgPaths = []string{
4170 "src/github.com/tmwh/go-get-issue-14450/b",
4171 "src/github.com/tmwh/go-get-issue-14450-b-dependency/c",
4172 "src/github.com/tmwh/go-get-issue-14450-b-dependency/d",
4175 for _, importPath := range expectedPkgPaths {
4176 _, err := os.Stat(tg.path(importPath))
4177 tg.must(err)
4179 const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e"
4180 tg.mustNotExist(tg.path(notExpectedPkgPath))
4183 func TestGoEnv(t *testing.T) {
4184 tg := testgo(t)
4185 tg.parallel()
4186 defer tg.cleanup()
4187 tg.setenv("GOOS", "freebsd") // to avoid invalid pair errors
4188 tg.setenv("GOARCH", "arm")
4189 tg.run("env", "GOARCH")
4190 tg.grepStdout("^arm$", "GOARCH not honored")
4192 tg.run("env", "GCCGO")
4193 tg.grepStdout(".", "GCCGO unexpectedly empty")
4195 tg.run("env", "CGO_CFLAGS")
4196 tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty")
4198 tg.setenv("CGO_CFLAGS", "-foobar")
4199 tg.run("env", "CGO_CFLAGS")
4200 tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored")
4202 tg.setenv("CC", "gcc -fmust -fgo -ffaster")
4203 tg.run("env", "CC")
4204 tg.grepStdout("gcc", "CC not found")
4205 tg.run("env", "GOGCCFLAGS")
4206 tg.grepStdout("-ffaster", "CC arguments not found")
4209 const (
4210 noMatchesPattern = `(?m)^ok.*\[no tests to run\]`
4211 okPattern = `(?m)^ok`
4214 func TestMatchesNoTests(t *testing.T) {
4215 tg := testgo(t)
4216 defer tg.cleanup()
4217 // TODO: tg.parallel()
4218 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go")
4219 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4222 func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) {
4223 tg := testgo(t)
4224 defer tg.cleanup()
4225 tg.parallel()
4226 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4227 tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror")
4228 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4229 tg.grepBoth("FAIL", "go test did not say FAIL")
4232 func TestMatchesNoBenchmarksIsOK(t *testing.T) {
4233 tg := testgo(t)
4234 defer tg.cleanup()
4235 // TODO: tg.parallel()
4236 tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go")
4237 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4238 tg.grepBoth(okPattern, "go test did not say ok")
4241 func TestMatchesOnlyExampleIsOK(t *testing.T) {
4242 tg := testgo(t)
4243 defer tg.cleanup()
4244 // TODO: tg.parallel()
4245 tg.run("test", "-run", "Example", "testdata/example1_test.go")
4246 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4247 tg.grepBoth(okPattern, "go test did not say ok")
4250 func TestMatchesOnlyBenchmarkIsOK(t *testing.T) {
4251 tg := testgo(t)
4252 defer tg.cleanup()
4253 // TODO: tg.parallel()
4254 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4255 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4256 tg.grepBoth(okPattern, "go test did not say ok")
4259 func TestBenchmarkLabels(t *testing.T) {
4260 tg := testgo(t)
4261 defer tg.cleanup()
4262 // TODO: tg.parallel()
4263 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4264 tg.run("test", "-run", "^$", "-bench", ".", "bench")
4265 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4266 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4267 tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench")
4268 tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times")
4271 func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) {
4272 tg := testgo(t)
4273 defer tg.cleanup()
4274 // TODO: tg.parallel()
4275 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4276 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4277 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4278 tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:")
4281 func TestMatchesOnlyTestIsOK(t *testing.T) {
4282 tg := testgo(t)
4283 defer tg.cleanup()
4284 // TODO: tg.parallel()
4285 tg.run("test", "-run", "Test", "testdata/standalone_test.go")
4286 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4287 tg.grepBoth(okPattern, "go test did not say ok")
4290 func TestMatchesNoTestsWithSubtests(t *testing.T) {
4291 tg := testgo(t)
4292 defer tg.cleanup()
4293 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go")
4294 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4297 func TestMatchesNoSubtestsMatch(t *testing.T) {
4298 tg := testgo(t)
4299 defer tg.cleanup()
4300 tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go")
4301 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4304 func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) {
4305 tg := testgo(t)
4306 defer tg.cleanup()
4307 tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go")
4308 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4309 tg.grepBoth("FAIL", "go test did not say FAIL")
4312 func TestMatchesOnlySubtestIsOK(t *testing.T) {
4313 tg := testgo(t)
4314 defer tg.cleanup()
4315 tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go")
4316 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4317 tg.grepBoth(okPattern, "go test did not say ok")
4320 func TestMatchesNoSubtestsParallel(t *testing.T) {
4321 tg := testgo(t)
4322 defer tg.cleanup()
4323 tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go")
4324 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4327 func TestMatchesOnlySubtestParallelIsOK(t *testing.T) {
4328 tg := testgo(t)
4329 defer tg.cleanup()
4330 tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go")
4331 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4332 tg.grepBoth(okPattern, "go test did not say ok")
4335 // Issue 18845
4336 func TestBenchTimeout(t *testing.T) {
4337 tooSlow(t)
4338 tg := testgo(t)
4339 defer tg.cleanup()
4340 tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go")
4343 // Issue 19394
4344 func TestWriteProfilesOnTimeout(t *testing.T) {
4345 tooSlow(t)
4346 tg := testgo(t)
4347 defer tg.cleanup()
4348 tg.tempDir("profiling")
4349 tg.tempFile("profiling/timeouttest_test.go", `package timeouttest_test
4350 import "testing"
4351 import "time"
4352 func TestSleep(t *testing.T) { time.Sleep(time.Second) }`)
4353 tg.cd(tg.path("profiling"))
4354 tg.runFail(
4355 "test",
4356 "-cpuprofile", tg.path("profiling/cpu.pprof"), "-memprofile", tg.path("profiling/mem.pprof"),
4357 "-timeout", "1ms")
4358 tg.mustHaveContent(tg.path("profiling/cpu.pprof"))
4359 tg.mustHaveContent(tg.path("profiling/mem.pprof"))
4362 func TestLinkXImportPathEscape(t *testing.T) {
4363 // golang.org/issue/16710
4364 skipIfGccgo(t, "gccgo does not support -ldflags -X")
4365 tg := testgo(t)
4366 defer tg.cleanup()
4367 tg.parallel()
4368 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4369 exe := "./linkx" + exeSuffix
4370 tg.creatingTemp(exe)
4371 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main")
4372 out, err := exec.Command(exe).CombinedOutput()
4373 if err != nil {
4374 tg.t.Fatal(err)
4376 if string(out) != "linkXworked\n" {
4377 tg.t.Log(string(out))
4378 tg.t.Fatal(`incorrect output: expected "linkXworked\n"`)
4382 // Issue 18044.
4383 func TestLdBindNow(t *testing.T) {
4384 tg := testgo(t)
4385 defer tg.cleanup()
4386 tg.parallel()
4387 tg.setenv("LD_BIND_NOW", "1")
4388 tg.run("help")
4391 // Issue 18225.
4392 // This is really a cmd/asm issue but this is a convenient place to test it.
4393 func TestConcurrentAsm(t *testing.T) {
4394 skipIfGccgo(t, "gccgo does not use cmd/asm")
4395 tg := testgo(t)
4396 defer tg.cleanup()
4397 tg.parallel()
4398 asm := `DATA ·constants<>+0x0(SB)/8,$0
4399 GLOBL ·constants<>(SB),8,$8
4401 tg.tempFile("go/src/p/a.s", asm)
4402 tg.tempFile("go/src/p/b.s", asm)
4403 tg.tempFile("go/src/p/p.go", `package p`)
4404 tg.setenv("GOPATH", tg.path("go"))
4405 tg.run("build", "p")
4408 // Issue 18778.
4409 func TestDotDotDotOutsideGOPATH(t *testing.T) {
4410 tg := testgo(t)
4411 defer tg.cleanup()
4413 tg.tempFile("pkgs/a.go", `package x`)
4414 tg.tempFile("pkgs/a_test.go", `package x_test
4415 import "testing"
4416 func TestX(t *testing.T) {}`)
4418 tg.tempFile("pkgs/a/a.go", `package a`)
4419 tg.tempFile("pkgs/a/a_test.go", `package a_test
4420 import "testing"
4421 func TestA(t *testing.T) {}`)
4423 tg.cd(tg.path("pkgs"))
4424 tg.run("build", "./...")
4425 tg.run("test", "./...")
4426 tg.run("list", "./...")
4427 tg.grepStdout("pkgs$", "expected package not listed")
4428 tg.grepStdout("pkgs/a", "expected package not listed")
4431 // Issue 18975.
4432 func TestFFLAGS(t *testing.T) {
4433 if !canCgo {
4434 t.Skip("skipping because cgo not enabled")
4437 tg := testgo(t)
4438 defer tg.cleanup()
4439 tg.parallel()
4441 tg.tempFile("p/src/p/main.go", `package main
4442 // #cgo FFLAGS: -no-such-fortran-flag
4443 import "C"
4444 func main() {}
4446 tg.tempFile("p/src/p/a.f", `! comment`)
4447 tg.setenv("GOPATH", tg.path("p"))
4449 // This should normally fail because we are passing an unknown flag,
4450 // but issue #19080 points to Fortran compilers that succeed anyhow.
4451 // To work either way we call doRun directly rather than run or runFail.
4452 tg.doRun([]string{"build", "-x", "p"})
4454 tg.grepStderr("no-such-fortran-flag", `missing expected "-no-such-fortran-flag"`)
4457 // Issue 19198.
4458 // This is really a cmd/link issue but this is a convenient place to test it.
4459 func TestDuplicateGlobalAsmSymbols(t *testing.T) {
4460 skipIfGccgo(t, "gccgo does not use cmd/asm")
4461 tooSlow(t)
4462 if runtime.GOARCH != "386" && runtime.GOARCH != "amd64" {
4463 t.Skipf("skipping test on %s", runtime.GOARCH)
4465 if !canCgo {
4466 t.Skip("skipping because cgo not enabled")
4469 tg := testgo(t)
4470 defer tg.cleanup()
4471 tg.parallel()
4473 asm := `
4474 #include "textflag.h"
4476 DATA sym<>+0x0(SB)/8,$0
4477 GLOBL sym<>(SB),(NOPTR+RODATA),$8
4479 TEXT ·Data(SB),NOSPLIT,$0
4480 MOVB sym<>(SB), AX
4481 MOVB AX, ret+0(FP)
4484 tg.tempFile("go/src/a/a.s", asm)
4485 tg.tempFile("go/src/a/a.go", `package a; func Data() uint8`)
4486 tg.tempFile("go/src/b/b.s", asm)
4487 tg.tempFile("go/src/b/b.go", `package b; func Data() uint8`)
4488 tg.tempFile("go/src/p/p.go", `
4489 package main
4490 import "a"
4491 import "b"
4492 import "C"
4493 func main() {
4494 _ = a.Data() + b.Data()
4497 tg.setenv("GOPATH", tg.path("go"))
4498 exe := tg.path("p.exe")
4499 tg.creatingTemp(exe)
4500 tg.run("build", "-o", exe, "p")
4503 func TestBuildTagsNoComma(t *testing.T) {
4504 skipIfGccgo(t, "gccgo has no standard packages")
4505 tg := testgo(t)
4506 defer tg.cleanup()
4507 tg.makeTempdir()
4508 tg.setenv("GOPATH", tg.path("go"))
4509 tg.run("build", "-tags", "tag1 tag2", "math")
4510 tg.runFail("build", "-tags", "tag1,tag2", "math")
4511 tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
4514 func copyFile(src, dst string, perm os.FileMode) error {
4515 sf, err := os.Open(src)
4516 if err != nil {
4517 return err
4519 defer sf.Close()
4521 df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
4522 if err != nil {
4523 return err
4526 _, err = io.Copy(df, sf)
4527 err2 := df.Close()
4528 if err != nil {
4529 return err
4531 return err2
4534 func TestExecutableGOROOT(t *testing.T) {
4535 skipIfGccgo(t, "gccgo has no GOROOT")
4536 if runtime.GOOS == "openbsd" {
4537 t.Skipf("test case does not work on %s, missing os.Executable", runtime.GOOS)
4540 // Env with no GOROOT.
4541 var env []string
4542 for _, e := range os.Environ() {
4543 if !strings.HasPrefix(e, "GOROOT=") {
4544 env = append(env, e)
4548 check := func(t *testing.T, exe, want string) {
4549 cmd := exec.Command(exe, "env", "GOROOT")
4550 cmd.Env = env
4551 out, err := cmd.CombinedOutput()
4552 if err != nil {
4553 t.Fatalf("%s env GOROOT: %v, %s", exe, err, out)
4555 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4556 if err != nil {
4557 t.Fatal(err)
4559 want, err = filepath.EvalSymlinks(want)
4560 if err != nil {
4561 t.Fatal(err)
4563 if !strings.EqualFold(goroot, want) {
4564 t.Errorf("go env GOROOT:\nhave %s\nwant %s", goroot, want)
4565 } else {
4566 t.Logf("go env GOROOT: %s", goroot)
4570 // Note: Must not call tg methods inside subtests: tg is attached to outer t.
4571 tg := testgo(t)
4572 defer tg.cleanup()
4574 tg.makeTempdir()
4575 tg.tempDir("new/bin")
4576 newGoTool := tg.path("new/bin/go" + exeSuffix)
4577 tg.must(copyFile(tg.goTool(), newGoTool, 0775))
4578 newRoot := tg.path("new")
4580 t.Run("RelocatedExe", func(t *testing.T) {
4581 // Should fall back to default location in binary,
4582 // which is the GOROOT we used when building testgo.exe.
4583 check(t, newGoTool, testGOROOT)
4586 // If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT,
4587 // so it should find the new tree.
4588 tg.tempDir("new/pkg/tool")
4589 t.Run("RelocatedTree", func(t *testing.T) {
4590 check(t, newGoTool, newRoot)
4593 tg.tempDir("other/bin")
4594 symGoTool := tg.path("other/bin/go" + exeSuffix)
4596 // Symlink into go tree should still find go tree.
4597 t.Run("SymlinkedExe", func(t *testing.T) {
4598 testenv.MustHaveSymlink(t)
4599 if err := os.Symlink(newGoTool, symGoTool); err != nil {
4600 t.Fatal(err)
4602 check(t, symGoTool, newRoot)
4605 tg.must(os.RemoveAll(tg.path("new/pkg")))
4607 // Binaries built in the new tree should report the
4608 // new tree when they call runtime.GOROOT.
4609 t.Run("RuntimeGoroot", func(t *testing.T) {
4610 // Build a working GOROOT the easy way, with symlinks.
4611 testenv.MustHaveSymlink(t)
4612 if err := os.Symlink(filepath.Join(testGOROOT, "src"), tg.path("new/src")); err != nil {
4613 t.Fatal(err)
4615 if err := os.Symlink(filepath.Join(testGOROOT, "pkg"), tg.path("new/pkg")); err != nil {
4616 t.Fatal(err)
4619 cmd := exec.Command(newGoTool, "run", "testdata/print_goroot.go")
4620 cmd.Env = env
4621 out, err := cmd.CombinedOutput()
4622 if err != nil {
4623 t.Fatalf("%s run testdata/print_goroot.go: %v, %s", newGoTool, err, out)
4625 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4626 if err != nil {
4627 t.Fatal(err)
4629 want, err := filepath.EvalSymlinks(tg.path("new"))
4630 if err != nil {
4631 t.Fatal(err)
4633 if !strings.EqualFold(goroot, want) {
4634 t.Errorf("go run testdata/print_goroot.go:\nhave %s\nwant %s", goroot, want)
4635 } else {
4636 t.Logf("go run testdata/print_goroot.go: %s", goroot)
4641 func TestNeedVersion(t *testing.T) {
4642 skipIfGccgo(t, "gccgo does not use cmd/compile")
4643 tg := testgo(t)
4644 defer tg.cleanup()
4645 tg.parallel()
4646 tg.tempFile("goversion.go", `package main; func main() {}`)
4647 path := tg.path("goversion.go")
4648 tg.setenv("TESTGO_VERSION", "go1.testgo")
4649 tg.runFail("run", path)
4650 tg.grepStderr("compile", "does not match go tool version")
4653 // Test that user can override default code generation flags.
4654 func TestUserOverrideFlags(t *testing.T) {
4655 skipIfGccgo(t, "gccgo does not use -gcflags")
4656 if !canCgo {
4657 t.Skip("skipping because cgo not enabled")
4659 if runtime.GOOS != "linux" {
4660 // We are testing platform-independent code, so it's
4661 // OK to skip cases that work differently.
4662 t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS)
4665 tg := testgo(t)
4666 defer tg.cleanup()
4667 // Don't call tg.parallel, as creating override.h and override.a may
4668 // confuse other tests.
4669 tg.tempFile("override.go", `package main
4671 import "C"
4673 //export GoFunc
4674 func GoFunc() {}
4676 func main() {}`)
4677 tg.creatingTemp("override.a")
4678 tg.creatingTemp("override.h")
4679 tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=all=-shared=false", tg.path("override.go"))
4680 tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag")
4683 func TestCgoFlagContainsSpace(t *testing.T) {
4684 tooSlow(t)
4685 if !canCgo {
4686 t.Skip("skipping because cgo not enabled")
4688 tg := testgo(t)
4689 defer tg.cleanup()
4691 tg.makeTempdir()
4692 tg.cd(tg.path("."))
4693 tg.tempFile("main.go", `package main
4694 // #cgo CFLAGS: -I"c flags"
4695 // #cgo LDFLAGS: -L"ld flags"
4696 import "C"
4697 func main() {}
4699 tg.run("run", "-x", "main.go")
4700 tg.grepStderr(`"-I[^"]+c flags"`, "did not find quoted c flags")
4701 tg.grepStderrNot(`"-I[^"]+c flags".*"-I[^"]+c flags"`, "found too many quoted c flags")
4702 tg.grepStderr(`"-L[^"]+ld flags"`, "did not find quoted ld flags")
4703 tg.grepStderrNot(`"-L[^"]+c flags".*"-L[^"]+c flags"`, "found too many quoted ld flags")
4706 // Issue #20435.
4707 func TestGoTestRaceCoverModeFailures(t *testing.T) {
4708 tooSlow(t)
4709 if !canRace {
4710 t.Skip("skipping because race detector not supported")
4713 tg := testgo(t)
4714 tg.parallel()
4715 defer tg.cleanup()
4716 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4718 tg.run("test", "testrace")
4720 tg.runFail("test", "-race", "-covermode=set", "testrace")
4721 tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed")
4722 tg.grepBothNot("PASS", "something passed")
4725 // Issue 9737: verify that GOARM and GO386 affect the computed build ID.
4726 func TestBuildIDContainsArchModeEnv(t *testing.T) {
4727 if testing.Short() {
4728 t.Skip("skipping in short mode")
4731 var tg *testgoData
4732 testWith := func(before, after func()) func(*testing.T) {
4733 return func(t *testing.T) {
4734 tg = testgo(t)
4735 defer tg.cleanup()
4736 tg.tempFile("src/mycmd/x.go", `package main
4737 func main() {}`)
4738 tg.setenv("GOPATH", tg.path("."))
4740 tg.cd(tg.path("src/mycmd"))
4741 tg.setenv("GOOS", "linux")
4742 before()
4743 tg.run("install", "mycmd")
4744 after()
4745 tg.wantStale("mycmd", "stale dependency: runtime/internal/sys", "should be stale after environment variable change")
4749 t.Run("386", testWith(func() {
4750 tg.setenv("GOARCH", "386")
4751 tg.setenv("GO386", "387")
4752 }, func() {
4753 tg.setenv("GO386", "sse2")
4756 t.Run("arm", testWith(func() {
4757 tg.setenv("GOARCH", "arm")
4758 tg.setenv("GOARM", "5")
4759 }, func() {
4760 tg.setenv("GOARM", "7")
4764 func TestTestRegexps(t *testing.T) {
4765 tg := testgo(t)
4766 defer tg.cleanup()
4767 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4768 tg.run("test", "-cpu=1", "-run=X/Y", "-bench=X/Y", "-count=2", "-v", "testregexp")
4769 var lines []string
4770 for _, line := range strings.SplitAfter(tg.getStdout(), "\n") {
4771 if strings.Contains(line, "=== RUN") || strings.Contains(line, "--- BENCH") || strings.Contains(line, "LOG") {
4772 lines = append(lines, line)
4776 // Important parts:
4777 // TestX is run, twice
4778 // TestX/Y is run, twice
4779 // TestXX is run, twice
4780 // TestZ is not run
4781 // BenchmarkX is run but only with N=1, once
4782 // BenchmarkXX is run but only with N=1, once
4783 // BenchmarkX/Y is run in full, twice
4784 want := `=== RUN TestX
4785 === RUN TestX/Y
4786 x_test.go:6: LOG: X running
4787 x_test.go:8: LOG: Y running
4788 === RUN TestXX
4789 z_test.go:10: LOG: XX running
4790 === RUN TestX
4791 === RUN TestX/Y
4792 x_test.go:6: LOG: X running
4793 x_test.go:8: LOG: Y running
4794 === RUN TestXX
4795 z_test.go:10: LOG: XX running
4796 --- BENCH: BenchmarkX/Y
4797 x_test.go:15: LOG: Y running N=1
4798 x_test.go:15: LOG: Y running N=100
4799 x_test.go:15: LOG: Y running N=10000
4800 x_test.go:15: LOG: Y running N=1000000
4801 x_test.go:15: LOG: Y running N=100000000
4802 x_test.go:15: LOG: Y running N=2000000000
4803 --- BENCH: BenchmarkX/Y
4804 x_test.go:15: LOG: Y running N=1
4805 x_test.go:15: LOG: Y running N=100
4806 x_test.go:15: LOG: Y running N=10000
4807 x_test.go:15: LOG: Y running N=1000000
4808 x_test.go:15: LOG: Y running N=100000000
4809 x_test.go:15: LOG: Y running N=2000000000
4810 --- BENCH: BenchmarkX
4811 x_test.go:13: LOG: X running N=1
4812 --- BENCH: BenchmarkXX
4813 z_test.go:18: LOG: XX running N=1
4816 have := strings.Join(lines, "")
4817 if have != want {
4818 t.Errorf("reduced output:<<<\n%s>>> want:<<<\n%s>>>", have, want)
4822 func TestListTests(t *testing.T) {
4823 tooSlow(t)
4824 var tg *testgoData
4825 testWith := func(listName, expected string) func(*testing.T) {
4826 return func(t *testing.T) {
4827 tg = testgo(t)
4828 defer tg.cleanup()
4829 tg.run("test", "./testdata/src/testlist/...", fmt.Sprintf("-list=%s", listName))
4830 tg.grepStdout(expected, fmt.Sprintf("-test.list=%s returned %q, expected %s", listName, tg.getStdout(), expected))
4834 t.Run("Test", testWith("Test", "TestSimple"))
4835 t.Run("Bench", testWith("Benchmark", "BenchmarkSimple"))
4836 t.Run("Example1", testWith("Example", "ExampleSimple"))
4837 t.Run("Example2", testWith("Example", "ExampleWithEmptyOutput"))
4840 func TestBuildmodePIE(t *testing.T) {
4841 if testing.Short() && testenv.Builder() == "" {
4842 t.Skipf("skipping in -short mode on non-builder")
4845 platform := fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
4846 switch platform {
4847 case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x",
4848 "android/amd64", "android/arm", "android/arm64", "android/386":
4849 case "darwin/amd64":
4850 default:
4851 t.Skipf("skipping test because buildmode=pie is not supported on %s", platform)
4854 tg := testgo(t)
4855 defer tg.cleanup()
4857 tg.tempFile("main.go", `package main; func main() { print("hello") }`)
4858 src := tg.path("main.go")
4859 obj := tg.path("main")
4860 tg.run("build", "-buildmode=pie", "-o", obj, src)
4862 switch runtime.GOOS {
4863 case "linux", "android":
4864 f, err := elf.Open(obj)
4865 if err != nil {
4866 t.Fatal(err)
4868 defer f.Close()
4869 if f.Type != elf.ET_DYN {
4870 t.Errorf("PIE type must be ET_DYN, but %s", f.Type)
4872 case "darwin":
4873 f, err := macho.Open(obj)
4874 if err != nil {
4875 t.Fatal(err)
4877 defer f.Close()
4878 if f.Flags&macho.FlagDyldLink == 0 {
4879 t.Error("PIE must have DyldLink flag, but not")
4881 if f.Flags&macho.FlagPIE == 0 {
4882 t.Error("PIE must have PIE flag, but not")
4884 default:
4885 panic("unreachable")
4888 out, err := exec.Command(obj).CombinedOutput()
4889 if err != nil {
4890 t.Fatal(err)
4893 if string(out) != "hello" {
4894 t.Errorf("got %q; want %q", out, "hello")
4898 func TestExecBuildX(t *testing.T) {
4899 tooSlow(t)
4900 if !canCgo {
4901 t.Skip("skipping because cgo not enabled")
4904 if runtime.GOOS == "plan9" || runtime.GOOS == "windows" {
4905 t.Skipf("skipping because unix shell is not supported on %s", runtime.GOOS)
4908 tg := testgo(t)
4909 defer tg.cleanup()
4911 tg.setenv("GOCACHE", "off")
4913 tg.tempFile("main.go", `package main; import "C"; func main() { print("hello") }`)
4914 src := tg.path("main.go")
4915 obj := tg.path("main")
4916 tg.run("build", "-x", "-o", obj, src)
4917 sh := tg.path("test.sh")
4918 err := ioutil.WriteFile(sh, []byte("set -e\n"+tg.getStderr()), 0666)
4919 if err != nil {
4920 t.Fatal(err)
4923 out, err := exec.Command(obj).CombinedOutput()
4924 if err != nil {
4925 t.Fatal(err)
4927 if string(out) != "hello" {
4928 t.Fatalf("got %q; want %q", out, "hello")
4931 err = os.Remove(obj)
4932 if err != nil {
4933 t.Fatal(err)
4936 out, err = exec.Command("/usr/bin/env", "bash", "-x", sh).CombinedOutput()
4937 if err != nil {
4938 t.Fatalf("/bin/sh %s: %v\n%s", sh, err, out)
4940 t.Logf("shell output:\n%s", out)
4942 out, err = exec.Command(obj).CombinedOutput()
4943 if err != nil {
4944 t.Fatal(err)
4946 if string(out) != "hello" {
4947 t.Fatalf("got %q; want %q", out, "hello")
4951 func TestParallelNumber(t *testing.T) {
4952 tooSlow(t)
4953 for _, n := range [...]string{"-1", "0"} {
4954 t.Run(n, func(t *testing.T) {
4955 tg := testgo(t)
4956 defer tg.cleanup()
4957 tg.runFail("test", "-parallel", n, "testdata/standalone_parallel_sub_test.go")
4958 tg.grepBoth("-parallel can only be given", "go test -parallel with N<1 did not error")
4963 func TestWrongGOOSErrorBeforeLoadError(t *testing.T) {
4964 skipIfGccgo(t, "gccgo assumes cross-compilation is always possible")
4965 tg := testgo(t)
4966 defer tg.cleanup()
4967 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4968 tg.setenv("GOOS", "windwos")
4969 tg.runFail("build", "exclude")
4970 tg.grepStderr("unsupported GOOS/GOARCH pair", "GOOS=windwos go build exclude did not report 'unsupported GOOS/GOARCH pair'")
4973 func TestUpxCompression(t *testing.T) {
4974 if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
4975 t.Skipf("skipping upx test on %s/%s", runtime.GOOS, runtime.GOARCH)
4978 out, err := exec.Command("upx", "--version").CombinedOutput()
4979 if err != nil {
4980 t.Skip("skipping because upx is not available")
4983 // upx --version prints `upx <version>` in the first line of output:
4984 // upx 3.94
4985 // [...]
4986 re := regexp.MustCompile(`([[:digit:]]+)\.([[:digit:]]+)`)
4987 upxVersion := re.FindStringSubmatch(string(out))
4988 if len(upxVersion) != 3 {
4989 t.Errorf("bad upx version string: %s", upxVersion)
4992 major, err1 := strconv.Atoi(upxVersion[1])
4993 minor, err2 := strconv.Atoi(upxVersion[2])
4994 if err1 != nil || err2 != nil {
4995 t.Errorf("bad upx version string: %s", upxVersion[0])
4998 // Anything below 3.94 is known not to work with go binaries
4999 if (major < 3) || (major == 3 && minor < 94) {
5000 t.Skipf("skipping because upx version %v.%v is too old", major, minor)
5003 tg := testgo(t)
5004 defer tg.cleanup()
5006 tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello upx") }`)
5007 src := tg.path("main.go")
5008 obj := tg.path("main")
5009 tg.run("build", "-o", obj, src)
5011 out, err = exec.Command("upx", obj).CombinedOutput()
5012 if err != nil {
5013 t.Logf("executing upx\n%s\n", out)
5014 t.Fatalf("upx failed with %v", err)
5017 out, err = exec.Command(obj).CombinedOutput()
5018 if err != nil {
5019 t.Logf("%s", out)
5020 t.Fatalf("running compressed go binary failed with error %s", err)
5022 if string(out) != "hello upx" {
5023 t.Fatalf("bad output from compressed go binary:\ngot %q; want %q", out, "hello upx")
5027 func TestGOTMPDIR(t *testing.T) {
5028 tg := testgo(t)
5029 defer tg.cleanup()
5030 tg.parallel()
5031 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5032 tg.makeTempdir()
5033 tg.setenv("GOTMPDIR", tg.tempdir)
5034 tg.setenv("GOCACHE", "off")
5036 // complex/x is a trivial non-main package.
5037 tg.run("build", "-work", "-x", "complex/w")
5038 tg.grepStderr("WORK="+regexp.QuoteMeta(tg.tempdir), "did not work in $GOTMPDIR")
5041 func TestBuildCache(t *testing.T) {
5042 tooSlow(t)
5043 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5044 t.Skip("GODEBUG gocacheverify")
5046 tg := testgo(t)
5047 defer tg.cleanup()
5048 tg.parallel()
5049 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5050 tg.makeTempdir()
5051 tg.setenv("GOCACHE", tg.tempdir)
5053 // complex/w is a trivial non-main package.
5054 // It imports nothing, so there should be no Deps.
5055 tg.run("list", "-f={{join .Deps \" \"}}", "complex/w")
5056 tg.grepStdoutNot(".+", "complex/w depends on unexpected packages")
5058 tg.run("build", "-x", "complex/w")
5059 tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler")
5061 tg.run("build", "-x", "complex/w")
5062 tg.grepStderrNot(`[\\/]compile|gccgo`, "ran compiler incorrectly")
5064 tg.run("build", "-a", "-x", "complex/w")
5065 tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler with -a")
5067 // complex is a non-trivial main package.
5068 // the link step should not be cached.
5069 tg.run("build", "-o", os.DevNull, "-x", "complex")
5070 tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
5072 tg.run("build", "-o", os.DevNull, "-x", "complex")
5073 tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
5076 func TestCacheOutput(t *testing.T) {
5077 // Test that command output is cached and replayed too.
5078 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5079 t.Skip("GODEBUG gocacheverify")
5081 tg := testgo(t)
5082 defer tg.cleanup()
5083 tg.parallel()
5084 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5085 tg.makeTempdir()
5086 tg.setenv("GOCACHE", tg.tempdir)
5088 tg.run("build", "-gcflags=-m", "errors")
5089 stdout1 := tg.getStdout()
5090 stderr1 := tg.getStderr()
5092 tg.run("build", "-gcflags=-m", "errors")
5093 stdout2 := tg.getStdout()
5094 stderr2 := tg.getStderr()
5096 if stdout2 != stdout1 || stderr2 != stderr1 {
5097 t.Errorf("cache did not reproduce output:\n\nstdout1:\n%s\n\nstdout2:\n%s\n\nstderr1:\n%s\n\nstderr2:\n%s",
5098 stdout1, stdout2, stderr1, stderr2)
5102 func TestCacheCoverage(t *testing.T) {
5103 tooSlow(t)
5105 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5106 t.Skip("GODEBUG gocacheverify")
5109 tg := testgo(t)
5110 defer tg.cleanup()
5111 tg.parallel()
5112 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5113 tg.makeTempdir()
5115 tg.setenv("GOCACHE", tg.path("c1"))
5116 tg.run("test", "-cover", "-short", "strings")
5117 tg.run("test", "-cover", "-short", "math", "strings")
5120 func TestIssue22588(t *testing.T) {
5121 // Don't get confused by stderr coming from tools.
5122 tg := testgo(t)
5123 defer tg.cleanup()
5124 tg.parallel()
5126 if _, err := os.Stat("/usr/bin/time"); err != nil {
5127 t.Skip(err)
5130 tg.run("list", "-f={{.Stale}}", "runtime")
5131 tg.run("list", "-toolexec=/usr/bin/time", "-f={{.Stale}}", "runtime")
5132 tg.grepStdout("false", "incorrectly reported runtime as stale")
5135 func TestIssue22531(t *testing.T) {
5136 tooSlow(t)
5137 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5138 t.Skip("GODEBUG gocacheverify")
5140 tg := testgo(t)
5141 defer tg.cleanup()
5142 tg.parallel()
5143 tg.makeTempdir()
5144 tg.setenv("GOPATH", tg.tempdir)
5145 tg.setenv("GOCACHE", tg.path("cache"))
5146 tg.tempFile("src/m/main.go", "package main /* c1 */; func main() {}\n")
5147 tg.run("install", "-x", "m")
5148 tg.run("list", "-f", "{{.Stale}}", "m")
5149 tg.grepStdout("false", "reported m as stale after install")
5150 tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5152 // The link action ID did not include the full main build ID,
5153 // even though the full main build ID is written into the
5154 // eventual binary. That caused the following install to
5155 // be a no-op, thinking the gofmt binary was up-to-date,
5156 // even though .Stale could see it was not.
5157 tg.tempFile("src/m/main.go", "package main /* c2 */; func main() {}\n")
5158 tg.run("install", "-x", "m")
5159 tg.run("list", "-f", "{{.Stale}}", "m")
5160 tg.grepStdout("false", "reported m as stale after reinstall")
5161 tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5164 func TestIssue22596(t *testing.T) {
5165 tooSlow(t)
5166 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5167 t.Skip("GODEBUG gocacheverify")
5169 tg := testgo(t)
5170 defer tg.cleanup()
5171 tg.parallel()
5172 tg.makeTempdir()
5173 tg.setenv("GOCACHE", tg.path("cache"))
5174 tg.tempFile("gopath1/src/p/p.go", "package p; func F(){}\n")
5175 tg.tempFile("gopath2/src/p/p.go", "package p; func F(){}\n")
5177 tg.setenv("GOPATH", tg.path("gopath1"))
5178 tg.run("list", "-f={{.Target}}", "p")
5179 target1 := strings.TrimSpace(tg.getStdout())
5180 tg.run("install", "p")
5181 tg.wantNotStale("p", "", "p stale after install")
5183 tg.setenv("GOPATH", tg.path("gopath2"))
5184 tg.run("list", "-f={{.Target}}", "p")
5185 target2 := strings.TrimSpace(tg.getStdout())
5186 tg.must(os.MkdirAll(filepath.Dir(target2), 0777))
5187 tg.must(copyFile(target1, target2, 0666))
5188 tg.wantStale("p", "build ID mismatch", "p not stale after copy from gopath1")
5189 tg.run("install", "p")
5190 tg.wantNotStale("p", "", "p stale after install2")
5193 func TestTestCache(t *testing.T) {
5194 tooSlow(t)
5196 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5197 t.Skip("GODEBUG gocacheverify")
5199 tg := testgo(t)
5200 defer tg.cleanup()
5201 tg.parallel()
5202 tg.makeTempdir()
5203 tg.setenv("GOPATH", tg.tempdir)
5204 tg.setenv("GOCACHE", tg.path("cache"))
5206 if runtime.Compiler != "gccgo" {
5207 // timeout here should not affect result being cached
5208 // or being retrieved later.
5209 tg.run("test", "-x", "-timeout=10s", "errors")
5210 tg.grepStderr(`[\\/](compile|gccgo) `, "did not run compiler")
5211 tg.grepStderr(`[\\/](link|gccgo) `, "did not run linker")
5212 tg.grepStderr(`errors\.test`, "did not run test")
5214 tg.run("test", "-x", "errors")
5215 tg.grepStdout(`ok \terrors\t\(cached\)`, "did not report cached result")
5216 tg.grepStderrNot(`[\\/](compile|gccgo) `, "incorrectly ran compiler")
5217 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5218 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5219 tg.grepStderrNot("DO NOT USE", "poisoned action status leaked")
5221 // Even very low timeouts do not disqualify cached entries.
5222 tg.run("test", "-timeout=1ns", "-x", "errors")
5223 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5225 tg.run("clean", "-testcache")
5226 tg.run("test", "-x", "errors")
5227 tg.grepStderr(`errors\.test`, "did not run test")
5230 // The -p=1 in the commands below just makes the -x output easier to read.
5232 t.Log("\n\nINITIAL\n\n")
5234 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5235 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\nvar X = 1\n")
5236 tg.tempFile("src/t/t1/t1_test.go", "package t\nimport \"testing\"\nfunc Test1(*testing.T) {}\n")
5237 tg.tempFile("src/t/t2/t2_test.go", "package t\nimport _ \"p1\"\nimport \"testing\"\nfunc Test2(*testing.T) {}\n")
5238 tg.tempFile("src/t/t3/t3_test.go", "package t\nimport \"p1\"\nimport \"testing\"\nfunc Test3(t *testing.T) {t.Log(p1.X)}\n")
5239 tg.tempFile("src/t/t4/t4_test.go", "package t\nimport \"p2\"\nimport \"testing\"\nfunc Test4(t *testing.T) {t.Log(p2.X)}")
5240 tg.run("test", "-x", "-v", "-short", "t/...")
5242 t.Log("\n\nREPEAT\n\n")
5244 tg.run("test", "-x", "-v", "-short", "t/...")
5245 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5246 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5247 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5248 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5249 tg.grepStderrNot(`[\\/](compile|gccgo) `, "incorrectly ran compiler")
5250 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5251 tg.grepStderrNot(`p[0-9]\.test`, "incorrectly ran test")
5253 t.Log("\n\nCOMMENT\n\n")
5255 // Changing the program text without affecting the compiled package
5256 // should result in the package being rebuilt but nothing more.
5257 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 01\n")
5258 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5259 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5260 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5261 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5262 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5263 tg.grepStderrNot(`([\\/](compile|gccgo) ).*t[0-9]_test\.go`, "incorrectly ran compiler")
5264 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5265 tg.grepStderrNot(`t[0-9]\.test.*test\.short`, "incorrectly ran test")
5267 t.Log("\n\nCHANGE\n\n")
5269 // Changing the actual package should have limited effects.
5270 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 02\n")
5271 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5273 // p2 should have been rebuilt.
5274 tg.grepStderr(`([\\/]compile|gccgo).*p2.go`, "did not recompile p2")
5276 // t1 does not import anything, should not have been rebuilt.
5277 tg.grepStderrNot(`([\\/]compile|gccgo).*t1_test.go`, "incorrectly recompiled t1")
5278 tg.grepStderrNot(`([\\/]link|gccgo).*t1_test`, "incorrectly relinked t1_test")
5279 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t/t1")
5281 // t2 imports p1 and must be rebuilt and relinked,
5282 // but the change should not have any effect on the test binary,
5283 // so the test should not have been rerun.
5284 tg.grepStderr(`([\\/]compile|gccgo).*t2_test.go`, "did not recompile t2")
5285 tg.grepStderr(`([\\/]link|gccgo).*t2\.test`, "did not relink t2_test")
5286 // This check does not currently work with gccgo, as garbage
5287 // collection of unused variables is not turned on by default.
5288 if runtime.Compiler != "gccgo" {
5289 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t/t2")
5292 // t3 imports p1, and changing X changes t3's test binary.
5293 tg.grepStderr(`([\\/]compile|gccgo).*t3_test.go`, "did not recompile t3")
5294 tg.grepStderr(`([\\/]link|gccgo).*t3\.test`, "did not relink t3_test")
5295 tg.grepStderr(`t3\.test.*-test.short`, "did not rerun t3_test")
5296 tg.grepStdoutNot(`ok \tt/t3\t\(cached\)`, "reported cached t3_test result")
5298 // t4 imports p2, but p2 did not change, so t4 should be relinked, not recompiled,
5299 // and not rerun.
5300 tg.grepStderrNot(`([\\/]compile|gccgo).*t4_test.go`, "incorrectly recompiled t4")
5301 tg.grepStderr(`([\\/]link|gccgo).*t4\.test`, "did not relink t4_test")
5302 // This check does not currently work with gccgo, as garbage
5303 // collection of unused variables is not turned on by default.
5304 if runtime.Compiler != "gccgo" {
5305 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t/t4")
5309 func TestTestCacheInputs(t *testing.T) {
5310 tooSlow(t)
5312 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5313 t.Skip("GODEBUG gocacheverify")
5315 tg := testgo(t)
5316 defer tg.cleanup()
5317 tg.parallel()
5318 tg.makeTempdir()
5319 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5320 tg.setenv("GOCACHE", tg.path("cache"))
5322 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5323 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"))
5324 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("x"), 0644))
5325 old := time.Now().Add(-1 * time.Minute)
5326 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5327 info, err := os.Stat(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5328 if err != nil {
5329 t.Fatal(err)
5331 t.Logf("file.txt: old=%v, info.ModTime=%v", old, info.ModTime()) // help debug when Chtimes lies about succeeding
5332 tg.setenv("TESTKEY", "x")
5334 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), []byte("#!/bin/sh\nexit 0\n"), 0755))
5335 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old, old))
5337 tg.run("test", "testcache")
5338 tg.run("test", "testcache")
5339 tg.grepStdout(`\(cached\)`, "did not cache")
5341 tg.setenv("TESTKEY", "y")
5342 tg.run("test", "testcache")
5343 tg.grepStdoutNot(`\(cached\)`, "did not notice env var change")
5344 tg.run("test", "testcache")
5345 tg.grepStdout(`\(cached\)`, "did not cache")
5347 tg.run("test", "testcache", "-run=FileSize")
5348 tg.run("test", "testcache", "-run=FileSize")
5349 tg.grepStdout(`\(cached\)`, "did not cache")
5350 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxx"), 0644))
5351 tg.run("test", "testcache", "-run=FileSize")
5352 tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5353 tg.run("test", "testcache", "-run=FileSize")
5354 tg.grepStdout(`\(cached\)`, "did not cache")
5356 tg.run("test", "testcache", "-run=Chdir")
5357 tg.run("test", "testcache", "-run=Chdir")
5358 tg.grepStdout(`\(cached\)`, "did not cache")
5359 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxxxx"), 0644))
5360 tg.run("test", "testcache", "-run=Chdir")
5361 tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5362 tg.run("test", "testcache", "-run=Chdir")
5363 tg.grepStdout(`\(cached\)`, "did not cache")
5365 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5366 tg.run("test", "testcache", "-run=FileContent")
5367 tg.run("test", "testcache", "-run=FileContent")
5368 tg.grepStdout(`\(cached\)`, "did not cache")
5369 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("yyy"), 0644))
5370 old2 := old.Add(10 * time.Second)
5371 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old2, old2))
5372 tg.run("test", "testcache", "-run=FileContent")
5373 tg.grepStdoutNot(`\(cached\)`, "did not notice file content change")
5374 tg.run("test", "testcache", "-run=FileContent")
5375 tg.grepStdout(`\(cached\)`, "did not cache")
5377 tg.run("test", "testcache", "-run=DirList")
5378 tg.run("test", "testcache", "-run=DirList")
5379 tg.grepStdout(`\(cached\)`, "did not cache")
5380 tg.must(os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt")))
5381 tg.run("test", "testcache", "-run=DirList")
5382 tg.grepStdoutNot(`\(cached\)`, "did not notice directory change")
5383 tg.run("test", "testcache", "-run=DirList")
5384 tg.grepStdout(`\(cached\)`, "did not cache")
5386 tg.tempFile("file.txt", "")
5387 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"), []byte(`package testcache
5389 import (
5390 "os"
5391 "testing"
5394 func TestExternalFile(t *testing.T) {
5395 os.Open(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5396 _, err := os.Stat(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5397 if err != nil {
5398 t.Fatal(err)
5401 `), 0666))
5402 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"))
5403 tg.run("test", "testcache", "-run=ExternalFile")
5404 tg.run("test", "testcache", "-run=ExternalFile")
5405 tg.grepStdout(`\(cached\)`, "did not cache")
5406 tg.must(os.Remove(filepath.Join(tg.tempdir, "file.txt")))
5407 tg.run("test", "testcache", "-run=ExternalFile")
5408 tg.grepStdout(`\(cached\)`, "did not cache")
5410 switch runtime.GOOS {
5411 case "nacl", "plan9", "windows":
5412 // no shell scripts
5413 default:
5414 tg.run("test", "testcache", "-run=Exec")
5415 tg.run("test", "testcache", "-run=Exec")
5416 tg.grepStdout(`\(cached\)`, "did not cache")
5417 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old2, old2))
5418 tg.run("test", "testcache", "-run=Exec")
5419 tg.grepStdoutNot(`\(cached\)`, "did not notice script change")
5420 tg.run("test", "testcache", "-run=Exec")
5421 tg.grepStdout(`\(cached\)`, "did not cache")
5425 func TestNoCache(t *testing.T) {
5426 switch runtime.GOOS {
5427 case "windows":
5428 t.Skipf("no unwritable directories on %s", runtime.GOOS)
5430 if os.Getuid() == 0 {
5431 t.Skip("skipping test because running as root")
5434 tg := testgo(t)
5435 defer tg.cleanup()
5436 tg.parallel()
5437 tg.tempFile("triv.go", `package main; func main() {}`)
5438 tg.must(os.MkdirAll(tg.path("unwritable"), 0555))
5439 home := "HOME"
5440 if runtime.GOOS == "plan9" {
5441 home = "home"
5443 tg.setenv(home, tg.path(filepath.Join("unwritable", "home")))
5444 tg.unsetenv("GOCACHE")
5445 tg.run("build", "-o", tg.path("triv"), tg.path("triv.go"))
5446 tg.grepStderr("disabling cache", "did not disable cache")
5449 func TestTestVet(t *testing.T) {
5450 tooSlow(t)
5451 tg := testgo(t)
5452 defer tg.cleanup()
5453 tg.parallel()
5455 tg.tempFile("p1_test.go", `
5456 package p
5457 import "testing"
5458 func Test(t *testing.T) {
5459 t.Logf("%d") // oops
5463 tg.runFail("test", tg.path("p1_test.go"))
5464 tg.grepStderr(`Logf format %d`, "did not diagnose bad Logf")
5465 tg.run("test", "-vet=off", tg.path("p1_test.go"))
5466 tg.grepStdout(`^ok`, "did not print test summary")
5468 tg.tempFile("p1.go", `
5469 package p
5470 import "fmt"
5471 func F() {
5472 fmt.Printf("%d") // oops
5475 tg.runFail("test", tg.path("p1.go"))
5476 tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5477 tg.run("test", "-x", "-vet=shift", tg.path("p1.go"))
5478 tg.grepStderr(`[\\/]vet.*-shift`, "did not run vet with -shift")
5479 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5480 tg.run("test", "-vet=off", tg.path("p1.go"))
5481 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5483 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5484 tg.run("test", "vetcycle") // must not fail; #22890
5486 tg.runFail("test", "vetfail/...")
5487 tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5488 tg.grepStdout(`ok\s+vetfail/p2`, "did not run vetfail/p2")
5491 func TestTestRebuild(t *testing.T) {
5492 tg := testgo(t)
5493 defer tg.cleanup()
5494 tg.parallel()
5496 // golang.org/issue/23701.
5497 // b_test imports b with augmented method from export_test.go.
5498 // b_test also imports a, which imports b.
5499 // Must not accidentally see un-augmented b propagate through a to b_test.
5500 tg.tempFile("src/a/a.go", `package a
5501 import "b"
5502 type Type struct{}
5503 func (*Type) M() b.T {return 0}
5505 tg.tempFile("src/b/b.go", `package b
5506 type T int
5507 type I interface {M() T}
5509 tg.tempFile("src/b/export_test.go", `package b
5510 func (*T) Method() *T { return nil }
5512 tg.tempFile("src/b/b_test.go", `package b_test
5513 import (
5514 "testing"
5516 . "b"
5518 func TestBroken(t *testing.T) {
5519 x := new(T)
5520 x.Method()
5521 _ = new(a.Type)
5525 tg.setenv("GOPATH", tg.path("."))
5526 tg.run("test", "b")
5529 func TestInstallDeps(t *testing.T) {
5530 tooSlow(t)
5531 tg := testgo(t)
5532 defer tg.cleanup()
5533 tg.parallel()
5534 tg.makeTempdir()
5535 tg.setenv("GOPATH", tg.tempdir)
5537 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5538 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\n")
5539 tg.tempFile("src/main1/main.go", "package main\nimport _ \"p2\"\nfunc main() {}\n")
5541 tg.run("list", "-f={{.Target}}", "p1")
5542 p1 := strings.TrimSpace(tg.getStdout())
5543 tg.run("list", "-f={{.Target}}", "p2")
5544 p2 := strings.TrimSpace(tg.getStdout())
5545 tg.run("list", "-f={{.Target}}", "main1")
5546 main1 := strings.TrimSpace(tg.getStdout())
5548 tg.run("install", "main1")
5550 tg.mustExist(main1)
5551 tg.mustNotExist(p2)
5552 tg.mustNotExist(p1)
5554 tg.run("install", "p2")
5555 tg.mustExist(p2)
5556 tg.mustNotExist(p1)
5558 // don't let install -i overwrite runtime
5559 tg.wantNotStale("runtime", "", "must be non-stale before install -i")
5561 tg.run("install", "-i", "main1")
5562 tg.mustExist(p1)
5563 tg.must(os.Remove(p1))
5565 tg.run("install", "-i", "p2")
5566 tg.mustExist(p1)
5569 func TestFmtLoadErrors(t *testing.T) {
5570 tg := testgo(t)
5571 defer tg.cleanup()
5572 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5573 tg.runFail("fmt", "does-not-exist")
5574 tg.run("fmt", "-n", "exclude")
5577 func TestRelativePkgdir(t *testing.T) {
5578 tooSlow(t)
5579 tg := testgo(t)
5580 defer tg.cleanup()
5581 tg.makeTempdir()
5582 tg.setenv("GOCACHE", "off")
5583 tg.cd(tg.tempdir)
5585 tg.run("build", "-i", "-pkgdir=.", "runtime")
5588 func TestGcflagsPatterns(t *testing.T) {
5589 skipIfGccgo(t, "gccgo has no standard packages")
5590 tg := testgo(t)
5591 defer tg.cleanup()
5592 tg.setenv("GOPATH", "")
5593 tg.setenv("GOCACHE", "off")
5595 tg.run("build", "-n", "-v", "-gcflags= \t\r\n -e", "fmt")
5596 tg.grepStderr("^# fmt", "did not rebuild fmt")
5597 tg.grepStderrNot("^# reflect", "incorrectly rebuilt reflect")
5599 tg.run("build", "-n", "-v", "-gcflags=-e", "fmt", "reflect")
5600 tg.grepStderr("^# fmt", "did not rebuild fmt")
5601 tg.grepStderr("^# reflect", "did not rebuild reflect")
5602 tg.grepStderrNot("^# runtime", "incorrectly rebuilt runtime")
5604 tg.run("build", "-n", "-x", "-v", "-gcflags= \t\r\n reflect \t\r\n = \t\r\n -N", "fmt")
5605 tg.grepStderr("^# fmt", "did not rebuild fmt")
5606 tg.grepStderr("^# reflect", "did not rebuild reflect")
5607 tg.grepStderr("compile.* -N .*-p reflect", "did not build reflect with -N flag")
5608 tg.grepStderrNot("compile.* -N .*-p fmt", "incorrectly built fmt with -N flag")
5610 tg.run("test", "-c", "-n", "-gcflags=-N", "-ldflags=-X=x.y=z", "strings")
5611 tg.grepStderr("compile.* -N .*compare_test.go", "did not compile strings_test package with -N flag")
5612 tg.grepStderr("link.* -X=x.y=z", "did not link strings.test binary with -X flag")
5614 tg.run("test", "-c", "-n", "-gcflags=strings=-N", "-ldflags=strings=-X=x.y=z", "strings")
5615 tg.grepStderr("compile.* -N .*compare_test.go", "did not compile strings_test package with -N flag")
5616 tg.grepStderr("link.* -X=x.y=z", "did not link strings.test binary with -X flag")
5619 func TestGoTestMinusN(t *testing.T) {
5620 // Intent here is to verify that 'go test -n' works without crashing.
5621 // This reuses flag_test.go, but really any test would do.
5622 tg := testgo(t)
5623 defer tg.cleanup()
5624 tg.run("test", "testdata/flag_test.go", "-n", "-args", "-v=7")
5627 func TestGoTestJSON(t *testing.T) {
5628 skipIfGccgo(t, "gccgo does not have standard packages")
5629 tooSlow(t)
5631 tg := testgo(t)
5632 defer tg.cleanup()
5633 tg.parallel()
5634 tg.makeTempdir()
5635 tg.setenv("GOCACHE", tg.tempdir)
5636 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5638 // It would be nice to test that the output is interlaced
5639 // but it seems to be impossible to do that in a short test
5640 // that isn't also flaky. Just check that we get JSON output.
5641 tg.run("test", "-json", "-short", "-v", "errors", "empty/pkg", "skipper")
5642 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5643 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5645 tg.grepStdout(`"Action":"output","Package":"empty/pkg","Output":".*no test files`, "did not see no test files print")
5646 tg.grepStdout(`"Action":"skip","Package":"empty/pkg"`, "did not see skip")
5648 tg.grepStdout(`"Action":"output","Package":"skipper","Test":"Test","Output":"--- SKIP:`, "did not see SKIP output")
5649 tg.grepStdout(`"Action":"skip","Package":"skipper","Test":"Test"`, "did not see skip result for Test")
5651 tg.run("test", "-json", "-short", "-v", "errors")
5652 tg.grepStdout(`"Action":"output","Package":"errors","Output":".*\(cached\)`, "did not see no cached output")
5654 tg.run("test", "-json", "-bench=NONE", "-short", "-v", "errors")
5655 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5656 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5658 tg.run("test", "-o", tg.path("errors.test.exe"), "-c", "errors")
5659 tg.run("tool", "test2json", "-p", "errors", tg.path("errors.test.exe"), "-test.v", "-test.short")
5660 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5661 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5662 tg.grepStdout(`\{"Action":"pass","Package":"errors"\}`, "did not see final pass")
5665 func TestFailFast(t *testing.T) {
5666 tooSlow(t)
5667 tg := testgo(t)
5668 defer tg.cleanup()
5670 tests := []struct {
5671 run string
5672 failfast bool
5673 nfail int
5675 {"TestFailingA", true, 1},
5676 {"TestFailing[AB]", true, 1},
5677 {"TestFailing[AB]", false, 2},
5678 // mix with non-failing tests:
5679 {"TestA|TestFailing[AB]", true, 1},
5680 {"TestA|TestFailing[AB]", false, 2},
5681 // mix with parallel tests:
5682 {"TestFailingB|TestParallelFailingA", true, 2},
5683 {"TestFailingB|TestParallelFailingA", false, 2},
5684 {"TestFailingB|TestParallelFailing[AB]", true, 3},
5685 {"TestFailingB|TestParallelFailing[AB]", false, 3},
5686 // mix with parallel sub-tests
5687 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", true, 3},
5688 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", false, 5},
5689 {"TestParallelFailingSubtestsA", true, 1},
5690 // only parallels:
5691 {"TestParallelFailing[AB]", false, 2},
5692 // non-parallel subtests:
5693 {"TestFailingSubtestsA", true, 1},
5694 {"TestFailingSubtestsA", false, 2},
5697 for _, tt := range tests {
5698 t.Run(tt.run, func(t *testing.T) {
5699 tg.runFail("test", "./testdata/src/failfast_test.go", "-run="+tt.run, "-failfast="+strconv.FormatBool(tt.failfast))
5701 nfail := strings.Count(tg.getStdout(), "FAIL - ")
5703 if nfail != tt.nfail {
5704 t.Errorf("go test -run=%s -failfast=%t printed %d FAILs, want %d", tt.run, tt.failfast, nfail, tt.nfail)
5710 // Issue 22986.
5711 func TestImportPath(t *testing.T) {
5712 tooSlow(t)
5713 tg := testgo(t)
5714 defer tg.cleanup()
5715 tg.parallel()
5717 tg.tempFile("src/a/a.go", `
5718 package main
5720 import (
5721 "log"
5722 p "a/p-1.0"
5725 func main() {
5726 if !p.V {
5727 log.Fatal("false")
5731 tg.tempFile("src/a/a_test.go", `
5732 package main_test
5734 import (
5735 p "a/p-1.0"
5736 "testing"
5739 func TestV(t *testing.T) {
5740 if !p.V {
5741 t.Fatal("false")
5745 tg.tempFile("src/a/p-1.0/p.go", `
5746 package p
5748 var V = true
5750 func init() {}
5753 tg.setenv("GOPATH", tg.path("."))
5754 tg.run("build", "-o", tg.path("a.exe"), "a")
5755 tg.run("test", "a")
5758 // Issue 23150.
5759 func TestCpuprofileTwice(t *testing.T) {
5760 tg := testgo(t)
5761 defer tg.cleanup()
5762 tg.parallel()
5763 tg.tempFile("prof/src/x/x_test.go", `
5764 package x_test
5765 import (
5766 "testing"
5767 "time"
5769 func TestSleep(t *testing.T) { time.Sleep(10 * time.Millisecond) }`)
5770 tg.setenv("GOPATH", tg.path("prof"))
5771 bin := tg.path("x.test")
5772 out := tg.path("cpu.out")
5773 tg.run("test", "-o="+bin, "-cpuprofile="+out, "x")
5774 tg.must(os.Remove(out))
5775 tg.run("test", "-o="+bin, "-cpuprofile="+out, "x")
5776 tg.mustExist(out)
5779 // Issue 23694.
5780 func TestAtomicCoverpkgAll(t *testing.T) {
5781 skipIfGccgo(t, "gccgo has no cover tool")
5782 tg := testgo(t)
5783 defer tg.cleanup()
5784 tg.parallel()
5786 tg.tempFile("src/x/x.go", `package x; import _ "sync/atomic"; func F() {}`)
5787 tg.tempFile("src/x/x_test.go", `package x; import "testing"; func TestF(t *testing.T) { F() }`)
5788 tg.setenv("GOPATH", tg.path("."))
5789 tg.run("test", "-coverpkg=all", "-covermode=atomic", "x")
5790 if canRace {
5791 tg.run("test", "-coverpkg=all", "-race", "x")
5795 func TestBadCommandLines(t *testing.T) {
5796 tg := testgo(t)
5797 defer tg.cleanup()
5799 tg.tempFile("src/x/x.go", "package x\n")
5800 tg.setenv("GOPATH", tg.path("."))
5802 tg.run("build", "x")
5804 tg.tempFile("src/x/@y.go", "package x\n")
5805 tg.runFail("build", "x")
5806 tg.grepStderr("invalid input file name \"@y.go\"", "did not reject @y.go")
5807 tg.must(os.Remove(tg.path("src/x/@y.go")))
5809 tg.tempFile("src/x/-y.go", "package x\n")
5810 tg.runFail("build", "x")
5811 tg.grepStderr("invalid input file name \"-y.go\"", "did not reject -y.go")
5812 tg.must(os.Remove(tg.path("src/x/-y.go")))
5814 if runtime.Compiler == "gccgo" {
5815 tg.runFail("build", "-gccgoflags=all=@x", "x")
5816 } else {
5817 tg.runFail("build", "-gcflags=all=@x", "x")
5819 tg.grepStderr("invalid command-line argument @x in command", "did not reject @x during exec")
5821 tg.tempFile("src/@x/x.go", "package x\n")
5822 tg.setenv("GOPATH", tg.path("."))
5823 tg.runFail("build", "@x")
5824 tg.grepStderr("invalid input directory name \"@x\"", "did not reject @x directory")
5826 tg.tempFile("src/@x/y/y.go", "package y\n")
5827 tg.setenv("GOPATH", tg.path("."))
5828 tg.runFail("build", "@x/y")
5829 tg.grepStderr("invalid import path \"@x/y\"", "did not reject @x/y import path")
5831 tg.tempFile("src/-x/x.go", "package x\n")
5832 tg.setenv("GOPATH", tg.path("."))
5833 tg.runFail("build", "--", "-x")
5834 tg.grepStderr("invalid input directory name \"-x\"", "did not reject -x directory")
5836 tg.tempFile("src/-x/y/y.go", "package y\n")
5837 tg.setenv("GOPATH", tg.path("."))
5838 tg.runFail("build", "--", "-x/y")
5839 tg.grepStderr("invalid import path \"-x/y\"", "did not reject -x/y import path")
5842 func TestBadCgoDirectives(t *testing.T) {
5843 if !canCgo {
5844 t.Skip("no cgo")
5846 tg := testgo(t)
5847 defer tg.cleanup()
5849 tg.tempFile("src/x/x.go", "package x\n")
5850 tg.setenv("GOPATH", tg.path("."))
5852 if runtime.Compiler == "gc" {
5853 tg.tempFile("src/x/x.go", `package x
5855 //go:cgo_ldflag "-fplugin=foo.so"
5857 import "C"
5859 tg.runFail("build", "x")
5860 tg.grepStderr("//go:cgo_ldflag .* only allowed in cgo-generated code", "did not reject //go:cgo_ldflag directive")
5863 tg.must(os.Remove(tg.path("src/x/x.go")))
5864 tg.runFail("build", "x")
5865 tg.grepStderr("no Go files", "did not report missing source code")
5866 tg.tempFile("src/x/_cgo_yy.go", `package x
5868 //go:cgo_ldflag "-fplugin=foo.so"
5870 import "C"
5872 tg.runFail("build", "x")
5873 tg.grepStderr("no Go files", "did not report missing source code") // _* files are ignored...
5875 if runtime.Compiler == "gc" {
5876 tg.runFail("build", tg.path("src/x/_cgo_yy.go")) // ... but if forced, the comment is rejected
5877 // Actually, today there is a separate issue that _ files named
5878 // on the command-line are ignored. Once that is fixed,
5879 // we want to see the cgo_ldflag error.
5880 tg.grepStderr("//go:cgo_ldflag only allowed in cgo-generated code|no Go files", "did not reject //go:cgo_ldflag directive")
5883 tg.must(os.Remove(tg.path("src/x/_cgo_yy.go")))
5885 tg.tempFile("src/x/x.go", "package x\n")
5886 tg.tempFile("src/x/y.go", `package x
5887 // #cgo CFLAGS: -fplugin=foo.so
5888 import "C"
5890 tg.runFail("build", "x")
5891 tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
5893 tg.tempFile("src/x/y.go", `package x
5894 // #cgo CFLAGS: -Ibar -fplugin=foo.so
5895 import "C"
5897 tg.runFail("build", "x")
5898 tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
5900 tg.tempFile("src/x/y.go", `package x
5901 // #cgo pkg-config: -foo
5902 import "C"
5904 tg.runFail("build", "x")
5905 tg.grepStderr("invalid pkg-config package name: -foo", "did not reject pkg-config: -foo")
5907 tg.tempFile("src/x/y.go", `package x
5908 // #cgo pkg-config: @foo
5909 import "C"
5911 tg.runFail("build", "x")
5912 tg.grepStderr("invalid pkg-config package name: @foo", "did not reject pkg-config: -foo")
5914 tg.tempFile("src/x/y.go", `package x
5915 // #cgo CFLAGS: @foo
5916 import "C"
5918 tg.runFail("build", "x")
5919 tg.grepStderr("invalid flag in #cgo CFLAGS: @foo", "did not reject @foo flag")
5921 tg.tempFile("src/x/y.go", `package x
5922 // #cgo CFLAGS: -D
5923 import "C"
5925 tg.runFail("build", "x")
5926 tg.grepStderr("invalid flag in #cgo CFLAGS: -D without argument", "did not reject trailing -I flag")
5928 // Note that -I @foo is allowed because we rewrite it into -I /path/to/src/@foo
5929 // before the check is applied. There's no such rewrite for -D.
5931 tg.tempFile("src/x/y.go", `package x
5932 // #cgo CFLAGS: -D @foo
5933 import "C"
5935 tg.runFail("build", "x")
5936 tg.grepStderr("invalid flag in #cgo CFLAGS: -D @foo", "did not reject -D @foo flag")
5938 tg.tempFile("src/x/y.go", `package x
5939 // #cgo CFLAGS: -D@foo
5940 import "C"
5942 tg.runFail("build", "x")
5943 tg.grepStderr("invalid flag in #cgo CFLAGS: -D@foo", "did not reject -D@foo flag")
5945 tg.setenv("CGO_CFLAGS", "-D@foo")
5946 tg.tempFile("src/x/y.go", `package x
5947 import "C"
5949 tg.run("build", "-n", "x")
5950 tg.grepStderr("-D@foo", "did not find -D@foo in commands")