cmd/go: run tests that require package build IDs
[official-gcc.git] / libgo / go / cmd / go / go_test.go
blobf5228541372c97ecf644d381c36cbd271757f000
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 skipIfGccgo(t, "gccgo does not have vet")
3225 tg := testgo(t)
3226 defer tg.cleanup()
3227 tg.makeTempdir()
3228 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3229 tg.runFail("vet", "vetpkg")
3230 tg.grepBoth("Printf", "go vet vetpkg did not find missing argument for Printf")
3233 func TestGoVetWithTags(t *testing.T) {
3234 skipIfGccgo(t, "gccgo does not have vet")
3235 tg := testgo(t)
3236 defer tg.cleanup()
3237 tg.makeTempdir()
3238 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3239 tg.runFail("vet", "-tags", "tagtest", "vetpkg")
3240 tg.grepBoth(`c\.go.*Printf`, "go vet vetpkg did not run scan tagged file")
3243 func TestGoVetWithFlagsOn(t *testing.T) {
3244 skipIfGccgo(t, "gccgo does not have vet")
3245 tg := testgo(t)
3246 defer tg.cleanup()
3247 tg.makeTempdir()
3248 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3249 tg.runFail("vet", "-printf", "vetpkg")
3250 tg.grepBoth("Printf", "go vet -printf vetpkg did not find missing argument for Printf")
3253 func TestGoVetWithFlagsOff(t *testing.T) {
3254 skipIfGccgo(t, "gccgo does not have vet")
3255 tg := testgo(t)
3256 defer tg.cleanup()
3257 tg.makeTempdir()
3258 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3259 tg.run("vet", "-printf=false", "vetpkg")
3262 // Issue 23395.
3263 func TestGoVetWithOnlyTestFiles(t *testing.T) {
3264 tg := testgo(t)
3265 defer tg.cleanup()
3266 tg.parallel()
3267 tg.tempFile("src/p/p_test.go", "package p; import \"testing\"; func TestMe(*testing.T) {}")
3268 tg.setenv("GOPATH", tg.path("."))
3269 tg.run("vet", "p")
3272 // Issue 9767, 19769.
3273 func TestGoGetDotSlashDownload(t *testing.T) {
3274 testenv.MustHaveExternalNetwork(t)
3276 tg := testgo(t)
3277 defer tg.cleanup()
3278 tg.tempDir("src/rsc.io")
3279 tg.setenv("GOPATH", tg.path("."))
3280 tg.cd(tg.path("src/rsc.io"))
3281 tg.run("get", "./pprof_mac_fix")
3284 // Issue 13037: Was not parsing <meta> tags in 404 served over HTTPS
3285 func TestGoGetHTTPS404(t *testing.T) {
3286 testenv.MustHaveExternalNetwork(t)
3287 switch runtime.GOOS {
3288 case "darwin", "linux", "freebsd":
3289 default:
3290 t.Skipf("test case does not work on %s", runtime.GOOS)
3293 tg := testgo(t)
3294 defer tg.cleanup()
3295 tg.tempDir("src")
3296 tg.setenv("GOPATH", tg.path("."))
3297 tg.run("get", "bazil.org/fuse/fs/fstestutil")
3300 // Test that you cannot import a main package.
3301 // See golang.org/issue/4210 and golang.org/issue/17475.
3302 func TestImportMain(t *testing.T) {
3303 tooSlow(t)
3305 tg := testgo(t)
3306 tg.parallel()
3307 defer tg.cleanup()
3309 // Importing package main from that package main's test should work.
3310 tg.tempFile("src/x/main.go", `package main
3311 var X int
3312 func main() {}`)
3313 tg.tempFile("src/x/main_test.go", `package main_test
3314 import xmain "x"
3315 import "testing"
3316 var _ = xmain.X
3317 func TestFoo(t *testing.T) {}
3319 tg.setenv("GOPATH", tg.path("."))
3320 tg.creatingTemp("x" + exeSuffix)
3321 tg.run("build", "x")
3322 tg.run("test", "x")
3324 // Importing package main from another package should fail.
3325 tg.tempFile("src/p1/p.go", `package p1
3326 import xmain "x"
3327 var _ = xmain.X
3329 tg.runFail("build", "p1")
3330 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3332 // ... even in that package's test.
3333 tg.tempFile("src/p2/p.go", `package p2
3335 tg.tempFile("src/p2/p_test.go", `package p2
3336 import xmain "x"
3337 import "testing"
3338 var _ = xmain.X
3339 func TestFoo(t *testing.T) {}
3341 tg.run("build", "p2")
3342 tg.runFail("test", "p2")
3343 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3345 // ... even if that package's test is an xtest.
3346 tg.tempFile("src/p3/p.go", `package p
3348 tg.tempFile("src/p3/p_test.go", `package p_test
3349 import xmain "x"
3350 import "testing"
3351 var _ = xmain.X
3352 func TestFoo(t *testing.T) {}
3354 tg.run("build", "p3")
3355 tg.runFail("test", "p3")
3356 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3358 // ... even if that package is a package main
3359 tg.tempFile("src/p4/p.go", `package main
3360 func main() {}
3362 tg.tempFile("src/p4/p_test.go", `package main
3363 import xmain "x"
3364 import "testing"
3365 var _ = xmain.X
3366 func TestFoo(t *testing.T) {}
3368 tg.creatingTemp("p4" + exeSuffix)
3369 tg.run("build", "p4")
3370 tg.runFail("test", "p4")
3371 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3373 // ... even if that package is a package main using an xtest.
3374 tg.tempFile("src/p5/p.go", `package main
3375 func main() {}
3377 tg.tempFile("src/p5/p_test.go", `package main_test
3378 import xmain "x"
3379 import "testing"
3380 var _ = xmain.X
3381 func TestFoo(t *testing.T) {}
3383 tg.creatingTemp("p5" + exeSuffix)
3384 tg.run("build", "p5")
3385 tg.runFail("test", "p5")
3386 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3389 // Test that you cannot use a local import in a package
3390 // accessed by a non-local import (found in a GOPATH/GOROOT).
3391 // See golang.org/issue/17475.
3392 func TestImportLocal(t *testing.T) {
3393 tooSlow(t)
3395 tg := testgo(t)
3396 tg.parallel()
3397 defer tg.cleanup()
3399 tg.tempFile("src/dir/x/x.go", `package x
3400 var X int
3402 tg.setenv("GOPATH", tg.path("."))
3403 tg.run("build", "dir/x")
3405 // Ordinary import should work.
3406 tg.tempFile("src/dir/p0/p.go", `package p0
3407 import "dir/x"
3408 var _ = x.X
3410 tg.run("build", "dir/p0")
3412 // Relative import should not.
3413 tg.tempFile("src/dir/p1/p.go", `package p1
3414 import "../x"
3415 var _ = x.X
3417 tg.runFail("build", "dir/p1")
3418 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3420 // ... even in a test.
3421 tg.tempFile("src/dir/p2/p.go", `package p2
3423 tg.tempFile("src/dir/p2/p_test.go", `package p2
3424 import "../x"
3425 import "testing"
3426 var _ = x.X
3427 func TestFoo(t *testing.T) {}
3429 tg.run("build", "dir/p2")
3430 tg.runFail("test", "dir/p2")
3431 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3433 // ... even in an xtest.
3434 tg.tempFile("src/dir/p2/p_test.go", `package p2_test
3435 import "../x"
3436 import "testing"
3437 var _ = x.X
3438 func TestFoo(t *testing.T) {}
3440 tg.run("build", "dir/p2")
3441 tg.runFail("test", "dir/p2")
3442 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3444 // Relative import starting with ./ should not work either.
3445 tg.tempFile("src/dir/d.go", `package dir
3446 import "./x"
3447 var _ = x.X
3449 tg.runFail("build", "dir")
3450 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3452 // ... even in a test.
3453 tg.tempFile("src/dir/d.go", `package dir
3455 tg.tempFile("src/dir/d_test.go", `package dir
3456 import "./x"
3457 import "testing"
3458 var _ = x.X
3459 func TestFoo(t *testing.T) {}
3461 tg.run("build", "dir")
3462 tg.runFail("test", "dir")
3463 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3465 // ... even in an xtest.
3466 tg.tempFile("src/dir/d_test.go", `package dir_test
3467 import "./x"
3468 import "testing"
3469 var _ = x.X
3470 func TestFoo(t *testing.T) {}
3472 tg.run("build", "dir")
3473 tg.runFail("test", "dir")
3474 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3476 // Relative import plain ".." should not work.
3477 tg.tempFile("src/dir/x/y/y.go", `package dir
3478 import ".."
3479 var _ = x.X
3481 tg.runFail("build", "dir/x/y")
3482 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3484 // ... even in a test.
3485 tg.tempFile("src/dir/x/y/y.go", `package y
3487 tg.tempFile("src/dir/x/y/y_test.go", `package y
3488 import ".."
3489 import "testing"
3490 var _ = x.X
3491 func TestFoo(t *testing.T) {}
3493 tg.run("build", "dir/x/y")
3494 tg.runFail("test", "dir/x/y")
3495 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3497 // ... even in an x test.
3498 tg.tempFile("src/dir/x/y/y_test.go", `package y_test
3499 import ".."
3500 import "testing"
3501 var _ = x.X
3502 func TestFoo(t *testing.T) {}
3504 tg.run("build", "dir/x/y")
3505 tg.runFail("test", "dir/x/y")
3506 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3508 // Relative import "." should not work.
3509 tg.tempFile("src/dir/x/xx.go", `package x
3510 import "."
3511 var _ = x.X
3513 tg.runFail("build", "dir/x")
3514 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3516 // ... even in a test.
3517 tg.tempFile("src/dir/x/xx.go", `package x
3519 tg.tempFile("src/dir/x/xx_test.go", `package x
3520 import "."
3521 import "testing"
3522 var _ = x.X
3523 func TestFoo(t *testing.T) {}
3525 tg.run("build", "dir/x")
3526 tg.runFail("test", "dir/x")
3527 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3529 // ... even in an xtest.
3530 tg.tempFile("src/dir/x/xx.go", `package x
3532 tg.tempFile("src/dir/x/xx_test.go", `package x_test
3533 import "."
3534 import "testing"
3535 var _ = x.X
3536 func TestFoo(t *testing.T) {}
3538 tg.run("build", "dir/x")
3539 tg.runFail("test", "dir/x")
3540 tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3543 func TestGoGetInsecure(t *testing.T) {
3544 testenv.MustHaveExternalNetwork(t)
3546 tg := testgo(t)
3547 defer tg.cleanup()
3548 tg.makeTempdir()
3549 tg.setenv("GOPATH", tg.path("."))
3550 tg.failSSH()
3552 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3554 // Try go get -d of HTTP-only repo (should fail).
3555 tg.runFail("get", "-d", repo)
3557 // Try again with -insecure (should succeed).
3558 tg.run("get", "-d", "-insecure", repo)
3560 // Try updating without -insecure (should fail).
3561 tg.runFail("get", "-d", "-u", "-f", repo)
3564 func TestGoGetUpdateInsecure(t *testing.T) {
3565 testenv.MustHaveExternalNetwork(t)
3567 tg := testgo(t)
3568 defer tg.cleanup()
3569 tg.makeTempdir()
3570 tg.setenv("GOPATH", tg.path("."))
3572 const repo = "github.com/golang/example"
3574 // Clone the repo via HTTP manually.
3575 cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
3576 if out, err := cmd.CombinedOutput(); err != nil {
3577 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3580 // Update without -insecure should fail.
3581 // Update with -insecure should succeed.
3582 // We need -f to ignore import comments.
3583 const pkg = repo + "/hello"
3584 tg.runFail("get", "-d", "-u", "-f", pkg)
3585 tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
3588 func TestGoGetInsecureCustomDomain(t *testing.T) {
3589 testenv.MustHaveExternalNetwork(t)
3591 tg := testgo(t)
3592 defer tg.cleanup()
3593 tg.makeTempdir()
3594 tg.setenv("GOPATH", tg.path("."))
3596 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3597 tg.runFail("get", "-d", repo)
3598 tg.run("get", "-d", "-insecure", repo)
3601 func TestGoRunDirs(t *testing.T) {
3602 tg := testgo(t)
3603 defer tg.cleanup()
3604 tg.cd("testdata/rundir")
3605 tg.runFail("run", "x.go", "sub/sub.go")
3606 tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
3607 tg.runFail("run", "sub/sub.go", "x.go")
3608 tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
3611 func TestGoInstallPkgdir(t *testing.T) {
3612 skipIfGccgo(t, "gccgo has no standard packages")
3613 tooSlow(t)
3615 tg := testgo(t)
3616 tg.parallel()
3617 defer tg.cleanup()
3618 tg.makeTempdir()
3619 pkg := tg.path(".")
3620 tg.run("install", "-pkgdir", pkg, "sync")
3621 tg.mustExist(filepath.Join(pkg, "sync.a"))
3622 tg.mustNotExist(filepath.Join(pkg, "sync/atomic.a"))
3623 tg.run("install", "-i", "-pkgdir", pkg, "sync")
3624 tg.mustExist(filepath.Join(pkg, "sync.a"))
3625 tg.mustExist(filepath.Join(pkg, "sync/atomic.a"))
3628 func TestGoTestRaceInstallCgo(t *testing.T) {
3629 if !canRace {
3630 t.Skip("skipping because race detector not supported")
3633 // golang.org/issue/10500.
3634 // This used to install a race-enabled cgo.
3635 tg := testgo(t)
3636 defer tg.cleanup()
3637 tg.run("tool", "-n", "cgo")
3638 cgo := strings.TrimSpace(tg.stdout.String())
3639 old, err := os.Stat(cgo)
3640 tg.must(err)
3641 tg.run("test", "-race", "-i", "runtime/race")
3642 new, err := os.Stat(cgo)
3643 tg.must(err)
3644 if !new.ModTime().Equal(old.ModTime()) {
3645 t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
3649 func TestGoTestRaceFailures(t *testing.T) {
3650 tooSlow(t)
3652 if !canRace {
3653 t.Skip("skipping because race detector not supported")
3656 tg := testgo(t)
3657 tg.parallel()
3658 defer tg.cleanup()
3659 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3661 tg.run("test", "testrace")
3663 tg.runFail("test", "-race", "testrace")
3664 tg.grepStdout("FAIL: TestRace", "TestRace did not fail")
3665 tg.grepBothNot("PASS", "something passed")
3667 tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".")
3668 tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail")
3669 tg.grepBothNot("PASS", "something passed")
3672 func TestGoTestImportErrorStack(t *testing.T) {
3673 const out = `package testdep/p1 (test)
3674 imports testdep/p2
3675 imports testdep/p3: build constraints exclude all Go files `
3677 tg := testgo(t)
3678 defer tg.cleanup()
3679 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3680 tg.runFail("test", "testdep/p1")
3681 if !strings.Contains(tg.stderr.String(), out) {
3682 t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String())
3686 func TestGoGetUpdate(t *testing.T) {
3687 // golang.org/issue/9224.
3688 // The recursive updating was trying to walk to
3689 // former dependencies, not current ones.
3691 testenv.MustHaveExternalNetwork(t)
3693 tg := testgo(t)
3694 defer tg.cleanup()
3695 tg.makeTempdir()
3696 tg.setenv("GOPATH", tg.path("."))
3698 rewind := func() {
3699 tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
3700 cmd := exec.Command("git", "reset", "--hard", "HEAD~")
3701 cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
3702 out, err := cmd.CombinedOutput()
3703 if err != nil {
3704 t.Fatalf("git: %v\n%s", err, out)
3708 rewind()
3709 tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3711 // Again with -d -u.
3712 rewind()
3713 tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3716 // Issue #20512.
3717 func TestGoGetRace(t *testing.T) {
3718 testenv.MustHaveExternalNetwork(t)
3719 if !canRace {
3720 t.Skip("skipping because race detector not supported")
3723 tg := testgo(t)
3724 defer tg.cleanup()
3725 tg.makeTempdir()
3726 tg.setenv("GOPATH", tg.path("."))
3727 tg.run("get", "-race", "github.com/rsc/go-get-issue-9224-cmd")
3730 func TestGoGetDomainRoot(t *testing.T) {
3731 // golang.org/issue/9357.
3732 // go get foo.io (not foo.io/subdir) was not working consistently.
3734 testenv.MustHaveExternalNetwork(t)
3736 tg := testgo(t)
3737 defer tg.cleanup()
3738 tg.makeTempdir()
3739 tg.setenv("GOPATH", tg.path("."))
3741 // go-get-issue-9357.appspot.com is running
3742 // the code at github.com/rsc/go-get-issue-9357,
3743 // a trivial Go on App Engine app that serves a
3744 // <meta> tag for the domain root.
3745 tg.run("get", "-d", "go-get-issue-9357.appspot.com")
3746 tg.run("get", "go-get-issue-9357.appspot.com")
3747 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3749 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3750 tg.run("get", "go-get-issue-9357.appspot.com")
3752 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3753 tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3756 func TestGoInstallShadowedGOPATH(t *testing.T) {
3757 // golang.org/issue/3652.
3758 // go get foo.io (not foo.io/subdir) was not working consistently.
3760 testenv.MustHaveExternalNetwork(t)
3762 tg := testgo(t)
3763 defer tg.cleanup()
3764 tg.makeTempdir()
3765 tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
3767 tg.tempDir("gopath1/src/test")
3768 tg.tempDir("gopath2/src/test")
3769 tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
3771 tg.cd(tg.path("gopath2/src/test"))
3772 tg.runFail("install")
3773 tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
3776 func TestGoBuildGOPATHOrder(t *testing.T) {
3777 // golang.org/issue/14176#issuecomment-179895769
3778 // golang.org/issue/14192
3779 // -I arguments to compiler could end up not in GOPATH order,
3780 // leading to unexpected import resolution in the compiler.
3781 // This is still not a complete fix (see golang.org/issue/14271 and next test)
3782 // but it is clearly OK and enough to fix both of the two reported
3783 // instances of the underlying problem. It will have to do for now.
3785 tg := testgo(t)
3786 defer tg.cleanup()
3787 tg.makeTempdir()
3788 tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2"))
3790 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3791 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3792 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3793 tg.tempFile("p1/src/bar/bar.go", `
3794 package bar
3795 import _ "baz"
3796 import _ "foo"
3799 tg.run("install", "-x", "bar")
3802 func TestGoBuildGOPATHOrderBroken(t *testing.T) {
3803 // This test is known not to work.
3804 // See golang.org/issue/14271.
3805 t.Skip("golang.org/issue/14271")
3807 tg := testgo(t)
3808 defer tg.cleanup()
3809 tg.makeTempdir()
3811 tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3812 tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3813 tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n")
3814 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3815 tg.tempFile("p1/src/bar/bar.go", `
3816 package bar
3817 import _ "baz"
3818 import _ "foo"
3821 colon := string(filepath.ListSeparator)
3822 tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2"))
3823 tg.run("install", "-x", "bar")
3825 tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1"))
3826 tg.run("install", "-x", "bar")
3829 func TestIssue11709(t *testing.T) {
3830 tg := testgo(t)
3831 defer tg.cleanup()
3832 tg.tempFile("run.go", `
3833 package main
3834 import "os"
3835 func main() {
3836 if os.Getenv("TERM") != "" {
3837 os.Exit(1)
3840 tg.unsetenv("TERM")
3841 tg.run("run", tg.path("run.go"))
3844 func TestIssue12096(t *testing.T) {
3845 tg := testgo(t)
3846 defer tg.cleanup()
3847 tg.tempFile("test_test.go", `
3848 package main
3849 import ("os"; "testing")
3850 func TestEnv(t *testing.T) {
3851 if os.Getenv("TERM") != "" {
3852 t.Fatal("TERM is set")
3855 tg.unsetenv("TERM")
3856 tg.run("test", tg.path("test_test.go"))
3859 func TestGoBuildOutput(t *testing.T) {
3860 skipIfGccgo(t, "gccgo has no standard packages")
3861 tooSlow(t)
3862 tg := testgo(t)
3863 defer tg.cleanup()
3865 tg.makeTempdir()
3866 tg.cd(tg.path("."))
3868 nonExeSuffix := ".exe"
3869 if exeSuffix == ".exe" {
3870 nonExeSuffix = ""
3873 tg.tempFile("x.go", "package main\nfunc main(){}\n")
3874 tg.run("build", "x.go")
3875 tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
3876 tg.must(os.Remove(tg.path("x" + exeSuffix)))
3877 tg.mustNotExist("x" + nonExeSuffix)
3879 tg.run("build", "-o", "myprog", "x.go")
3880 tg.mustNotExist("x")
3881 tg.mustNotExist("x.exe")
3882 tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
3883 tg.mustNotExist("myprog.exe")
3885 tg.tempFile("p.go", "package p\n")
3886 tg.run("build", "p.go")
3887 tg.mustNotExist("p")
3888 tg.mustNotExist("p.a")
3889 tg.mustNotExist("p.o")
3890 tg.mustNotExist("p.exe")
3892 tg.run("build", "-o", "p.a", "p.go")
3893 tg.wantArchive("p.a")
3895 tg.run("build", "cmd/gofmt")
3896 tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
3897 tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
3898 tg.mustNotExist("gofmt" + nonExeSuffix)
3900 tg.run("build", "-o", "mygofmt", "cmd/gofmt")
3901 tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
3902 tg.mustNotExist("mygofmt.exe")
3903 tg.mustNotExist("gofmt")
3904 tg.mustNotExist("gofmt.exe")
3906 tg.run("build", "sync/atomic")
3907 tg.mustNotExist("atomic")
3908 tg.mustNotExist("atomic.exe")
3910 tg.run("build", "-o", "myatomic.a", "sync/atomic")
3911 tg.wantArchive("myatomic.a")
3912 tg.mustNotExist("atomic")
3913 tg.mustNotExist("atomic.a")
3914 tg.mustNotExist("atomic.exe")
3916 tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
3917 tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
3920 func TestGoBuildARM(t *testing.T) {
3921 if testing.Short() {
3922 t.Skip("skipping cross-compile in short mode")
3925 tg := testgo(t)
3926 defer tg.cleanup()
3928 tg.makeTempdir()
3929 tg.cd(tg.path("."))
3931 tg.setenv("GOARCH", "arm")
3932 tg.setenv("GOOS", "linux")
3933 tg.setenv("GOARM", "5")
3934 tg.tempFile("hello.go", `package main
3935 func main() {}`)
3936 tg.run("build", "hello.go")
3937 tg.grepStderrNot("unable to find math.a", "did not build math.a correctly")
3940 // For issue 14337.
3941 func TestParallelTest(t *testing.T) {
3942 tooSlow(t)
3943 tg := testgo(t)
3944 tg.parallel()
3945 defer tg.cleanup()
3946 tg.makeTempdir()
3947 const testSrc = `package package_test
3948 import (
3949 "testing"
3951 func TestTest(t *testing.T) {
3953 tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
3954 tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
3955 tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
3956 tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
3957 tg.setenv("GOPATH", tg.path("."))
3958 tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
3961 func TestCgoConsistentResults(t *testing.T) {
3962 tooSlow(t)
3963 if !canCgo {
3964 t.Skip("skipping because cgo not enabled")
3966 switch runtime.GOOS {
3967 case "freebsd":
3968 testenv.SkipFlaky(t, 15405)
3969 case "solaris":
3970 testenv.SkipFlaky(t, 13247)
3973 tg := testgo(t)
3974 defer tg.cleanup()
3975 tg.parallel()
3976 tg.makeTempdir()
3977 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3978 exe1 := tg.path("cgotest1" + exeSuffix)
3979 exe2 := tg.path("cgotest2" + exeSuffix)
3980 tg.run("build", "-o", exe1, "cgotest")
3981 tg.run("build", "-x", "-o", exe2, "cgotest")
3982 b1, err := ioutil.ReadFile(exe1)
3983 tg.must(err)
3984 b2, err := ioutil.ReadFile(exe2)
3985 tg.must(err)
3987 if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) {
3988 t.Skip("skipping because C compiler does not support -fdebug-prefix-map")
3990 if !bytes.Equal(b1, b2) {
3991 t.Error("building cgotest twice did not produce the same output")
3995 // Issue 14444: go get -u .../ duplicate loads errors
3996 func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) {
3997 testenv.MustHaveExternalNetwork(t)
3999 tg := testgo(t)
4000 defer tg.cleanup()
4001 tg.makeTempdir()
4002 tg.setenv("GOPATH", tg.path("."))
4003 tg.run("get", "-u", ".../")
4004 tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache")
4007 // Issue 17119 more duplicate load errors
4008 func TestIssue17119(t *testing.T) {
4009 testenv.MustHaveExternalNetwork(t)
4011 tg := testgo(t)
4012 defer tg.cleanup()
4013 tg.parallel()
4014 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4015 tg.runFail("build", "dupload")
4016 tg.grepBothNot("duplicate load|internal error", "internal error")
4019 func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) {
4020 tg := testgo(t)
4021 defer tg.cleanup()
4022 // TODO: tg.parallel()
4023 tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal")
4024 tg.grepBothNot("^ok", "test passed unexpectedly")
4025 tg.grepBoth("FAIL.*benchfatal", "test did not run everything")
4028 func TestBinaryOnlyPackages(t *testing.T) {
4029 tooSlow(t)
4031 tg := testgo(t)
4032 defer tg.cleanup()
4033 tg.parallel()
4034 tg.makeTempdir()
4035 tg.setenv("GOPATH", tg.path("."))
4037 tg.tempFile("src/p1/p1.go", `//go:binary-only-package
4039 package p1
4041 tg.wantStale("p1", "missing or invalid binary-only package", "p1 is binary-only but has no binary, should be stale")
4042 tg.runFail("install", "p1")
4043 tg.grepStderr("missing or invalid binary-only package", "did not report attempt to compile binary-only package")
4045 tg.tempFile("src/p1/p1.go", `
4046 package p1
4047 import "fmt"
4048 func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } }
4050 tg.run("install", "p1")
4051 os.Remove(tg.path("src/p1/p1.go"))
4052 tg.mustNotExist(tg.path("src/p1/p1.go"))
4054 tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great
4056 package p2
4057 import "p1"
4058 func F() { p1.F(true) }
4060 tg.runFail("install", "p2")
4061 tg.grepStderr("no Go files", "did not complain about missing sources")
4063 tg.tempFile("src/p1/missing.go", `//go:binary-only-package
4065 package p1
4066 import _ "fmt"
4067 func G()
4069 tg.wantNotStale("p1", "binary-only package", "should NOT want to rebuild p1 (first)")
4070 tg.run("install", "-x", "p1") // no-op, up to date
4071 tg.grepBothNot(`[\\/]compile`, "should not have run compiler")
4072 tg.run("install", "p2") // does not rebuild p1 (or else p2 will fail)
4073 tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
4075 // changes to the non-source-code do not matter,
4076 // and only one file needs the special comment.
4077 tg.tempFile("src/p1/missing2.go", `
4078 package p1
4079 func H()
4081 tg.wantNotStale("p1", "binary-only package", "should NOT want to rebuild p1 (second)")
4082 tg.wantNotStale("p2", "", "should NOT want to rebuild p2")
4084 tg.tempFile("src/p3/p3.go", `
4085 package main
4086 import (
4087 "p1"
4088 "p2"
4090 func main() {
4091 p1.F(false)
4092 p2.F()
4095 tg.run("install", "p3")
4097 tg.run("run", tg.path("src/p3/p3.go"))
4098 tg.grepStdout("hello from p1", "did not see message from p1")
4100 tg.tempFile("src/p4/p4.go", `package main`)
4101 // The odd string split below avoids vet complaining about
4102 // a // +build line appearing too late in this source file.
4103 tg.tempFile("src/p4/p4not.go", `//go:binary-only-package
4105 /`+`/ +build asdf
4107 package main
4109 tg.run("list", "-f", "{{.BinaryOnly}}", "p4")
4110 tg.grepStdout("false", "did not see BinaryOnly=false for p4")
4113 // Issue 16050.
4114 func TestAlwaysLinkSysoFiles(t *testing.T) {
4115 tg := testgo(t)
4116 defer tg.cleanup()
4117 tg.parallel()
4118 tg.tempDir("src/syso")
4119 tg.tempFile("src/syso/a.syso", ``)
4120 tg.tempFile("src/syso/b.go", `package syso`)
4121 tg.setenv("GOPATH", tg.path("."))
4123 // We should see the .syso file regardless of the setting of
4124 // CGO_ENABLED.
4126 tg.setenv("CGO_ENABLED", "1")
4127 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4128 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1")
4130 tg.setenv("CGO_ENABLED", "0")
4131 tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4132 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0")
4135 // Issue 16120.
4136 func TestGenerateUsesBuildContext(t *testing.T) {
4137 if runtime.GOOS == "windows" {
4138 t.Skip("this test won't run under Windows")
4141 tg := testgo(t)
4142 defer tg.cleanup()
4143 tg.parallel()
4144 tg.tempDir("src/gen")
4145 tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n")
4146 tg.setenv("GOPATH", tg.path("."))
4148 tg.setenv("GOOS", "linux")
4149 tg.setenv("GOARCH", "amd64")
4150 tg.run("generate", "gen")
4151 tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination")
4153 tg.setenv("GOOS", "darwin")
4154 tg.setenv("GOARCH", "386")
4155 tg.run("generate", "gen")
4156 tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination")
4159 // Issue 14450: go get -u .../ tried to import not downloaded package
4160 func TestGoGetUpdateWithWildcard(t *testing.T) {
4161 testenv.MustHaveExternalNetwork(t)
4163 tg := testgo(t)
4164 defer tg.cleanup()
4165 tg.parallel()
4166 tg.makeTempdir()
4167 tg.setenv("GOPATH", tg.path("."))
4168 const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a"
4169 tg.run("get", aPkgImportPath)
4170 tg.run("get", "-u", ".../")
4171 tg.grepStderrNot("cannot find package", "did not update packages given wildcard path")
4173 var expectedPkgPaths = []string{
4174 "src/github.com/tmwh/go-get-issue-14450/b",
4175 "src/github.com/tmwh/go-get-issue-14450-b-dependency/c",
4176 "src/github.com/tmwh/go-get-issue-14450-b-dependency/d",
4179 for _, importPath := range expectedPkgPaths {
4180 _, err := os.Stat(tg.path(importPath))
4181 tg.must(err)
4183 const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e"
4184 tg.mustNotExist(tg.path(notExpectedPkgPath))
4187 func TestGoEnv(t *testing.T) {
4188 tg := testgo(t)
4189 tg.parallel()
4190 defer tg.cleanup()
4191 tg.setenv("GOOS", "freebsd") // to avoid invalid pair errors
4192 tg.setenv("GOARCH", "arm")
4193 tg.run("env", "GOARCH")
4194 tg.grepStdout("^arm$", "GOARCH not honored")
4196 tg.run("env", "GCCGO")
4197 tg.grepStdout(".", "GCCGO unexpectedly empty")
4199 tg.run("env", "CGO_CFLAGS")
4200 tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty")
4202 tg.setenv("CGO_CFLAGS", "-foobar")
4203 tg.run("env", "CGO_CFLAGS")
4204 tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored")
4206 tg.setenv("CC", "gcc -fmust -fgo -ffaster")
4207 tg.run("env", "CC")
4208 tg.grepStdout("gcc", "CC not found")
4209 tg.run("env", "GOGCCFLAGS")
4210 tg.grepStdout("-ffaster", "CC arguments not found")
4213 const (
4214 noMatchesPattern = `(?m)^ok.*\[no tests to run\]`
4215 okPattern = `(?m)^ok`
4218 func TestMatchesNoTests(t *testing.T) {
4219 tg := testgo(t)
4220 defer tg.cleanup()
4221 // TODO: tg.parallel()
4222 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go")
4223 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4226 func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) {
4227 tg := testgo(t)
4228 defer tg.cleanup()
4229 tg.parallel()
4230 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4231 tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror")
4232 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4233 tg.grepBoth("FAIL", "go test did not say FAIL")
4236 func TestMatchesNoBenchmarksIsOK(t *testing.T) {
4237 tg := testgo(t)
4238 defer tg.cleanup()
4239 // TODO: tg.parallel()
4240 tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go")
4241 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4242 tg.grepBoth(okPattern, "go test did not say ok")
4245 func TestMatchesOnlyExampleIsOK(t *testing.T) {
4246 tg := testgo(t)
4247 defer tg.cleanup()
4248 // TODO: tg.parallel()
4249 tg.run("test", "-run", "Example", "testdata/example1_test.go")
4250 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4251 tg.grepBoth(okPattern, "go test did not say ok")
4254 func TestMatchesOnlyBenchmarkIsOK(t *testing.T) {
4255 tg := testgo(t)
4256 defer tg.cleanup()
4257 // TODO: tg.parallel()
4258 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4259 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4260 tg.grepBoth(okPattern, "go test did not say ok")
4263 func TestBenchmarkLabels(t *testing.T) {
4264 tg := testgo(t)
4265 defer tg.cleanup()
4266 // TODO: tg.parallel()
4267 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4268 tg.run("test", "-run", "^$", "-bench", ".", "bench")
4269 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4270 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4271 tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench")
4272 tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times")
4275 func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) {
4276 tg := testgo(t)
4277 defer tg.cleanup()
4278 // TODO: tg.parallel()
4279 tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4280 tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4281 tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4282 tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:")
4285 func TestMatchesOnlyTestIsOK(t *testing.T) {
4286 tg := testgo(t)
4287 defer tg.cleanup()
4288 // TODO: tg.parallel()
4289 tg.run("test", "-run", "Test", "testdata/standalone_test.go")
4290 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4291 tg.grepBoth(okPattern, "go test did not say ok")
4294 func TestMatchesNoTestsWithSubtests(t *testing.T) {
4295 tg := testgo(t)
4296 defer tg.cleanup()
4297 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go")
4298 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4301 func TestMatchesNoSubtestsMatch(t *testing.T) {
4302 tg := testgo(t)
4303 defer tg.cleanup()
4304 tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go")
4305 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4308 func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) {
4309 tg := testgo(t)
4310 defer tg.cleanup()
4311 tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go")
4312 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4313 tg.grepBoth("FAIL", "go test did not say FAIL")
4316 func TestMatchesOnlySubtestIsOK(t *testing.T) {
4317 tg := testgo(t)
4318 defer tg.cleanup()
4319 tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go")
4320 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4321 tg.grepBoth(okPattern, "go test did not say ok")
4324 func TestMatchesNoSubtestsParallel(t *testing.T) {
4325 tg := testgo(t)
4326 defer tg.cleanup()
4327 tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go")
4328 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4331 func TestMatchesOnlySubtestParallelIsOK(t *testing.T) {
4332 tg := testgo(t)
4333 defer tg.cleanup()
4334 tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go")
4335 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4336 tg.grepBoth(okPattern, "go test did not say ok")
4339 // Issue 18845
4340 func TestBenchTimeout(t *testing.T) {
4341 tooSlow(t)
4342 tg := testgo(t)
4343 defer tg.cleanup()
4344 tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go")
4347 // Issue 19394
4348 func TestWriteProfilesOnTimeout(t *testing.T) {
4349 tooSlow(t)
4350 tg := testgo(t)
4351 defer tg.cleanup()
4352 tg.tempDir("profiling")
4353 tg.tempFile("profiling/timeouttest_test.go", `package timeouttest_test
4354 import "testing"
4355 import "time"
4356 func TestSleep(t *testing.T) { time.Sleep(time.Second) }`)
4357 tg.cd(tg.path("profiling"))
4358 tg.runFail(
4359 "test",
4360 "-cpuprofile", tg.path("profiling/cpu.pprof"), "-memprofile", tg.path("profiling/mem.pprof"),
4361 "-timeout", "1ms")
4362 tg.mustHaveContent(tg.path("profiling/cpu.pprof"))
4363 tg.mustHaveContent(tg.path("profiling/mem.pprof"))
4366 func TestLinkXImportPathEscape(t *testing.T) {
4367 // golang.org/issue/16710
4368 skipIfGccgo(t, "gccgo does not support -ldflags -X")
4369 tg := testgo(t)
4370 defer tg.cleanup()
4371 tg.parallel()
4372 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4373 exe := "./linkx" + exeSuffix
4374 tg.creatingTemp(exe)
4375 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main")
4376 out, err := exec.Command(exe).CombinedOutput()
4377 if err != nil {
4378 tg.t.Fatal(err)
4380 if string(out) != "linkXworked\n" {
4381 tg.t.Log(string(out))
4382 tg.t.Fatal(`incorrect output: expected "linkXworked\n"`)
4386 // Issue 18044.
4387 func TestLdBindNow(t *testing.T) {
4388 tg := testgo(t)
4389 defer tg.cleanup()
4390 tg.parallel()
4391 tg.setenv("LD_BIND_NOW", "1")
4392 tg.run("help")
4395 // Issue 18225.
4396 // This is really a cmd/asm issue but this is a convenient place to test it.
4397 func TestConcurrentAsm(t *testing.T) {
4398 skipIfGccgo(t, "gccgo does not use cmd/asm")
4399 tg := testgo(t)
4400 defer tg.cleanup()
4401 tg.parallel()
4402 asm := `DATA ·constants<>+0x0(SB)/8,$0
4403 GLOBL ·constants<>(SB),8,$8
4405 tg.tempFile("go/src/p/a.s", asm)
4406 tg.tempFile("go/src/p/b.s", asm)
4407 tg.tempFile("go/src/p/p.go", `package p`)
4408 tg.setenv("GOPATH", tg.path("go"))
4409 tg.run("build", "p")
4412 // Issue 18778.
4413 func TestDotDotDotOutsideGOPATH(t *testing.T) {
4414 tg := testgo(t)
4415 defer tg.cleanup()
4417 tg.tempFile("pkgs/a.go", `package x`)
4418 tg.tempFile("pkgs/a_test.go", `package x_test
4419 import "testing"
4420 func TestX(t *testing.T) {}`)
4422 tg.tempFile("pkgs/a/a.go", `package a`)
4423 tg.tempFile("pkgs/a/a_test.go", `package a_test
4424 import "testing"
4425 func TestA(t *testing.T) {}`)
4427 tg.cd(tg.path("pkgs"))
4428 tg.run("build", "./...")
4429 tg.run("test", "./...")
4430 tg.run("list", "./...")
4431 tg.grepStdout("pkgs$", "expected package not listed")
4432 tg.grepStdout("pkgs/a", "expected package not listed")
4435 // Issue 18975.
4436 func TestFFLAGS(t *testing.T) {
4437 if !canCgo {
4438 t.Skip("skipping because cgo not enabled")
4441 tg := testgo(t)
4442 defer tg.cleanup()
4443 tg.parallel()
4445 tg.tempFile("p/src/p/main.go", `package main
4446 // #cgo FFLAGS: -no-such-fortran-flag
4447 import "C"
4448 func main() {}
4450 tg.tempFile("p/src/p/a.f", `! comment`)
4451 tg.setenv("GOPATH", tg.path("p"))
4453 // This should normally fail because we are passing an unknown flag,
4454 // but issue #19080 points to Fortran compilers that succeed anyhow.
4455 // To work either way we call doRun directly rather than run or runFail.
4456 tg.doRun([]string{"build", "-x", "p"})
4458 tg.grepStderr("no-such-fortran-flag", `missing expected "-no-such-fortran-flag"`)
4461 // Issue 19198.
4462 // This is really a cmd/link issue but this is a convenient place to test it.
4463 func TestDuplicateGlobalAsmSymbols(t *testing.T) {
4464 skipIfGccgo(t, "gccgo does not use cmd/asm")
4465 tooSlow(t)
4466 if runtime.GOARCH != "386" && runtime.GOARCH != "amd64" {
4467 t.Skipf("skipping test on %s", runtime.GOARCH)
4469 if !canCgo {
4470 t.Skip("skipping because cgo not enabled")
4473 tg := testgo(t)
4474 defer tg.cleanup()
4475 tg.parallel()
4477 asm := `
4478 #include "textflag.h"
4480 DATA sym<>+0x0(SB)/8,$0
4481 GLOBL sym<>(SB),(NOPTR+RODATA),$8
4483 TEXT ·Data(SB),NOSPLIT,$0
4484 MOVB sym<>(SB), AX
4485 MOVB AX, ret+0(FP)
4488 tg.tempFile("go/src/a/a.s", asm)
4489 tg.tempFile("go/src/a/a.go", `package a; func Data() uint8`)
4490 tg.tempFile("go/src/b/b.s", asm)
4491 tg.tempFile("go/src/b/b.go", `package b; func Data() uint8`)
4492 tg.tempFile("go/src/p/p.go", `
4493 package main
4494 import "a"
4495 import "b"
4496 import "C"
4497 func main() {
4498 _ = a.Data() + b.Data()
4501 tg.setenv("GOPATH", tg.path("go"))
4502 exe := tg.path("p.exe")
4503 tg.creatingTemp(exe)
4504 tg.run("build", "-o", exe, "p")
4507 func TestBuildTagsNoComma(t *testing.T) {
4508 skipIfGccgo(t, "gccgo has no standard packages")
4509 tg := testgo(t)
4510 defer tg.cleanup()
4511 tg.makeTempdir()
4512 tg.setenv("GOPATH", tg.path("go"))
4513 tg.run("build", "-tags", "tag1 tag2", "math")
4514 tg.runFail("build", "-tags", "tag1,tag2", "math")
4515 tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
4518 func copyFile(src, dst string, perm os.FileMode) error {
4519 sf, err := os.Open(src)
4520 if err != nil {
4521 return err
4523 defer sf.Close()
4525 df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
4526 if err != nil {
4527 return err
4530 _, err = io.Copy(df, sf)
4531 err2 := df.Close()
4532 if err != nil {
4533 return err
4535 return err2
4538 func TestExecutableGOROOT(t *testing.T) {
4539 skipIfGccgo(t, "gccgo has no GOROOT")
4540 if runtime.GOOS == "openbsd" {
4541 t.Skipf("test case does not work on %s, missing os.Executable", runtime.GOOS)
4544 // Env with no GOROOT.
4545 var env []string
4546 for _, e := range os.Environ() {
4547 if !strings.HasPrefix(e, "GOROOT=") {
4548 env = append(env, e)
4552 check := func(t *testing.T, exe, want string) {
4553 cmd := exec.Command(exe, "env", "GOROOT")
4554 cmd.Env = env
4555 out, err := cmd.CombinedOutput()
4556 if err != nil {
4557 t.Fatalf("%s env GOROOT: %v, %s", exe, err, out)
4559 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4560 if err != nil {
4561 t.Fatal(err)
4563 want, err = filepath.EvalSymlinks(want)
4564 if err != nil {
4565 t.Fatal(err)
4567 if !strings.EqualFold(goroot, want) {
4568 t.Errorf("go env GOROOT:\nhave %s\nwant %s", goroot, want)
4569 } else {
4570 t.Logf("go env GOROOT: %s", goroot)
4574 // Note: Must not call tg methods inside subtests: tg is attached to outer t.
4575 tg := testgo(t)
4576 defer tg.cleanup()
4578 tg.makeTempdir()
4579 tg.tempDir("new/bin")
4580 newGoTool := tg.path("new/bin/go" + exeSuffix)
4581 tg.must(copyFile(tg.goTool(), newGoTool, 0775))
4582 newRoot := tg.path("new")
4584 t.Run("RelocatedExe", func(t *testing.T) {
4585 // Should fall back to default location in binary,
4586 // which is the GOROOT we used when building testgo.exe.
4587 check(t, newGoTool, testGOROOT)
4590 // If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT,
4591 // so it should find the new tree.
4592 tg.tempDir("new/pkg/tool")
4593 t.Run("RelocatedTree", func(t *testing.T) {
4594 check(t, newGoTool, newRoot)
4597 tg.tempDir("other/bin")
4598 symGoTool := tg.path("other/bin/go" + exeSuffix)
4600 // Symlink into go tree should still find go tree.
4601 t.Run("SymlinkedExe", func(t *testing.T) {
4602 testenv.MustHaveSymlink(t)
4603 if err := os.Symlink(newGoTool, symGoTool); err != nil {
4604 t.Fatal(err)
4606 check(t, symGoTool, newRoot)
4609 tg.must(os.RemoveAll(tg.path("new/pkg")))
4611 // Binaries built in the new tree should report the
4612 // new tree when they call runtime.GOROOT.
4613 t.Run("RuntimeGoroot", func(t *testing.T) {
4614 // Build a working GOROOT the easy way, with symlinks.
4615 testenv.MustHaveSymlink(t)
4616 if err := os.Symlink(filepath.Join(testGOROOT, "src"), tg.path("new/src")); err != nil {
4617 t.Fatal(err)
4619 if err := os.Symlink(filepath.Join(testGOROOT, "pkg"), tg.path("new/pkg")); err != nil {
4620 t.Fatal(err)
4623 cmd := exec.Command(newGoTool, "run", "testdata/print_goroot.go")
4624 cmd.Env = env
4625 out, err := cmd.CombinedOutput()
4626 if err != nil {
4627 t.Fatalf("%s run testdata/print_goroot.go: %v, %s", newGoTool, err, out)
4629 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4630 if err != nil {
4631 t.Fatal(err)
4633 want, err := filepath.EvalSymlinks(tg.path("new"))
4634 if err != nil {
4635 t.Fatal(err)
4637 if !strings.EqualFold(goroot, want) {
4638 t.Errorf("go run testdata/print_goroot.go:\nhave %s\nwant %s", goroot, want)
4639 } else {
4640 t.Logf("go run testdata/print_goroot.go: %s", goroot)
4645 func TestNeedVersion(t *testing.T) {
4646 skipIfGccgo(t, "gccgo does not use cmd/compile")
4647 tg := testgo(t)
4648 defer tg.cleanup()
4649 tg.parallel()
4650 tg.tempFile("goversion.go", `package main; func main() {}`)
4651 path := tg.path("goversion.go")
4652 tg.setenv("TESTGO_VERSION", "go1.testgo")
4653 tg.runFail("run", path)
4654 tg.grepStderr("compile", "does not match go tool version")
4657 // Test that user can override default code generation flags.
4658 func TestUserOverrideFlags(t *testing.T) {
4659 skipIfGccgo(t, "gccgo does not use -gcflags")
4660 if !canCgo {
4661 t.Skip("skipping because cgo not enabled")
4663 if runtime.GOOS != "linux" {
4664 // We are testing platform-independent code, so it's
4665 // OK to skip cases that work differently.
4666 t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS)
4669 tg := testgo(t)
4670 defer tg.cleanup()
4671 // Don't call tg.parallel, as creating override.h and override.a may
4672 // confuse other tests.
4673 tg.tempFile("override.go", `package main
4675 import "C"
4677 //export GoFunc
4678 func GoFunc() {}
4680 func main() {}`)
4681 tg.creatingTemp("override.a")
4682 tg.creatingTemp("override.h")
4683 tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=all=-shared=false", tg.path("override.go"))
4684 tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag")
4687 func TestCgoFlagContainsSpace(t *testing.T) {
4688 tooSlow(t)
4689 if !canCgo {
4690 t.Skip("skipping because cgo not enabled")
4692 tg := testgo(t)
4693 defer tg.cleanup()
4695 tg.makeTempdir()
4696 tg.cd(tg.path("."))
4697 tg.tempFile("main.go", `package main
4698 // #cgo CFLAGS: -I"c flags"
4699 // #cgo LDFLAGS: -L"ld flags"
4700 import "C"
4701 func main() {}
4703 tg.run("run", "-x", "main.go")
4704 tg.grepStderr(`"-I[^"]+c flags"`, "did not find quoted c flags")
4705 tg.grepStderrNot(`"-I[^"]+c flags".*"-I[^"]+c flags"`, "found too many quoted c flags")
4706 tg.grepStderr(`"-L[^"]+ld flags"`, "did not find quoted ld flags")
4707 tg.grepStderrNot(`"-L[^"]+c flags".*"-L[^"]+c flags"`, "found too many quoted ld flags")
4710 // Issue #20435.
4711 func TestGoTestRaceCoverModeFailures(t *testing.T) {
4712 tooSlow(t)
4713 if !canRace {
4714 t.Skip("skipping because race detector not supported")
4717 tg := testgo(t)
4718 tg.parallel()
4719 defer tg.cleanup()
4720 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4722 tg.run("test", "testrace")
4724 tg.runFail("test", "-race", "-covermode=set", "testrace")
4725 tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed")
4726 tg.grepBothNot("PASS", "something passed")
4729 // Issue 9737: verify that GOARM and GO386 affect the computed build ID.
4730 func TestBuildIDContainsArchModeEnv(t *testing.T) {
4731 if testing.Short() {
4732 t.Skip("skipping in short mode")
4735 var tg *testgoData
4736 testWith := func(before, after func()) func(*testing.T) {
4737 return func(t *testing.T) {
4738 tg = testgo(t)
4739 defer tg.cleanup()
4740 tg.tempFile("src/mycmd/x.go", `package main
4741 func main() {}`)
4742 tg.setenv("GOPATH", tg.path("."))
4744 tg.cd(tg.path("src/mycmd"))
4745 tg.setenv("GOOS", "linux")
4746 before()
4747 tg.run("install", "mycmd")
4748 after()
4749 tg.wantStale("mycmd", "stale dependency: runtime/internal/sys", "should be stale after environment variable change")
4753 t.Run("386", testWith(func() {
4754 tg.setenv("GOARCH", "386")
4755 tg.setenv("GO386", "387")
4756 }, func() {
4757 tg.setenv("GO386", "sse2")
4760 t.Run("arm", testWith(func() {
4761 tg.setenv("GOARCH", "arm")
4762 tg.setenv("GOARM", "5")
4763 }, func() {
4764 tg.setenv("GOARM", "7")
4768 func TestTestRegexps(t *testing.T) {
4769 tg := testgo(t)
4770 defer tg.cleanup()
4771 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4772 tg.run("test", "-cpu=1", "-run=X/Y", "-bench=X/Y", "-count=2", "-v", "testregexp")
4773 var lines []string
4774 for _, line := range strings.SplitAfter(tg.getStdout(), "\n") {
4775 if strings.Contains(line, "=== RUN") || strings.Contains(line, "--- BENCH") || strings.Contains(line, "LOG") {
4776 lines = append(lines, line)
4780 // Important parts:
4781 // TestX is run, twice
4782 // TestX/Y is run, twice
4783 // TestXX is run, twice
4784 // TestZ is not run
4785 // BenchmarkX is run but only with N=1, once
4786 // BenchmarkXX is run but only with N=1, once
4787 // BenchmarkX/Y is run in full, twice
4788 want := `=== RUN TestX
4789 === RUN TestX/Y
4790 x_test.go:6: LOG: X running
4791 x_test.go:8: LOG: Y running
4792 === RUN TestXX
4793 z_test.go:10: LOG: XX running
4794 === RUN TestX
4795 === RUN TestX/Y
4796 x_test.go:6: LOG: X running
4797 x_test.go:8: LOG: Y running
4798 === RUN TestXX
4799 z_test.go:10: LOG: XX running
4800 --- BENCH: BenchmarkX/Y
4801 x_test.go:15: LOG: Y running N=1
4802 x_test.go:15: LOG: Y running N=100
4803 x_test.go:15: LOG: Y running N=10000
4804 x_test.go:15: LOG: Y running N=1000000
4805 x_test.go:15: LOG: Y running N=100000000
4806 x_test.go:15: LOG: Y running N=2000000000
4807 --- BENCH: BenchmarkX/Y
4808 x_test.go:15: LOG: Y running N=1
4809 x_test.go:15: LOG: Y running N=100
4810 x_test.go:15: LOG: Y running N=10000
4811 x_test.go:15: LOG: Y running N=1000000
4812 x_test.go:15: LOG: Y running N=100000000
4813 x_test.go:15: LOG: Y running N=2000000000
4814 --- BENCH: BenchmarkX
4815 x_test.go:13: LOG: X running N=1
4816 --- BENCH: BenchmarkXX
4817 z_test.go:18: LOG: XX running N=1
4820 have := strings.Join(lines, "")
4821 if have != want {
4822 t.Errorf("reduced output:<<<\n%s>>> want:<<<\n%s>>>", have, want)
4826 func TestListTests(t *testing.T) {
4827 tooSlow(t)
4828 var tg *testgoData
4829 testWith := func(listName, expected string) func(*testing.T) {
4830 return func(t *testing.T) {
4831 tg = testgo(t)
4832 defer tg.cleanup()
4833 tg.run("test", "./testdata/src/testlist/...", fmt.Sprintf("-list=%s", listName))
4834 tg.grepStdout(expected, fmt.Sprintf("-test.list=%s returned %q, expected %s", listName, tg.getStdout(), expected))
4838 t.Run("Test", testWith("Test", "TestSimple"))
4839 t.Run("Bench", testWith("Benchmark", "BenchmarkSimple"))
4840 t.Run("Example1", testWith("Example", "ExampleSimple"))
4841 t.Run("Example2", testWith("Example", "ExampleWithEmptyOutput"))
4844 func TestBuildmodePIE(t *testing.T) {
4845 if testing.Short() && testenv.Builder() == "" {
4846 t.Skipf("skipping in -short mode on non-builder")
4849 platform := fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
4850 switch platform {
4851 case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x",
4852 "android/amd64", "android/arm", "android/arm64", "android/386":
4853 case "darwin/amd64":
4854 default:
4855 t.Skipf("skipping test because buildmode=pie is not supported on %s", platform)
4858 tg := testgo(t)
4859 defer tg.cleanup()
4861 tg.tempFile("main.go", `package main; func main() { print("hello") }`)
4862 src := tg.path("main.go")
4863 obj := tg.path("main")
4864 tg.run("build", "-buildmode=pie", "-o", obj, src)
4866 switch runtime.GOOS {
4867 case "linux", "android":
4868 f, err := elf.Open(obj)
4869 if err != nil {
4870 t.Fatal(err)
4872 defer f.Close()
4873 if f.Type != elf.ET_DYN {
4874 t.Errorf("PIE type must be ET_DYN, but %s", f.Type)
4876 case "darwin":
4877 f, err := macho.Open(obj)
4878 if err != nil {
4879 t.Fatal(err)
4881 defer f.Close()
4882 if f.Flags&macho.FlagDyldLink == 0 {
4883 t.Error("PIE must have DyldLink flag, but not")
4885 if f.Flags&macho.FlagPIE == 0 {
4886 t.Error("PIE must have PIE flag, but not")
4888 default:
4889 panic("unreachable")
4892 out, err := exec.Command(obj).CombinedOutput()
4893 if err != nil {
4894 t.Fatal(err)
4897 if string(out) != "hello" {
4898 t.Errorf("got %q; want %q", out, "hello")
4902 func TestExecBuildX(t *testing.T) {
4903 tooSlow(t)
4904 if !canCgo {
4905 t.Skip("skipping because cgo not enabled")
4908 if runtime.GOOS == "plan9" || runtime.GOOS == "windows" {
4909 t.Skipf("skipping because unix shell is not supported on %s", runtime.GOOS)
4912 tg := testgo(t)
4913 defer tg.cleanup()
4915 tg.setenv("GOCACHE", "off")
4917 tg.tempFile("main.go", `package main; import "C"; func main() { print("hello") }`)
4918 src := tg.path("main.go")
4919 obj := tg.path("main")
4920 tg.run("build", "-x", "-o", obj, src)
4921 sh := tg.path("test.sh")
4922 err := ioutil.WriteFile(sh, []byte("set -e\n"+tg.getStderr()), 0666)
4923 if err != nil {
4924 t.Fatal(err)
4927 out, err := exec.Command(obj).CombinedOutput()
4928 if err != nil {
4929 t.Fatal(err)
4931 if string(out) != "hello" {
4932 t.Fatalf("got %q; want %q", out, "hello")
4935 err = os.Remove(obj)
4936 if err != nil {
4937 t.Fatal(err)
4940 out, err = exec.Command("/usr/bin/env", "bash", "-x", sh).CombinedOutput()
4941 if err != nil {
4942 t.Fatalf("/bin/sh %s: %v\n%s", sh, err, out)
4944 t.Logf("shell output:\n%s", out)
4946 out, err = exec.Command(obj).CombinedOutput()
4947 if err != nil {
4948 t.Fatal(err)
4950 if string(out) != "hello" {
4951 t.Fatalf("got %q; want %q", out, "hello")
4955 func TestParallelNumber(t *testing.T) {
4956 tooSlow(t)
4957 for _, n := range [...]string{"-1", "0"} {
4958 t.Run(n, func(t *testing.T) {
4959 tg := testgo(t)
4960 defer tg.cleanup()
4961 tg.runFail("test", "-parallel", n, "testdata/standalone_parallel_sub_test.go")
4962 tg.grepBoth("-parallel can only be given", "go test -parallel with N<1 did not error")
4967 func TestWrongGOOSErrorBeforeLoadError(t *testing.T) {
4968 skipIfGccgo(t, "gccgo assumes cross-compilation is always possible")
4969 tg := testgo(t)
4970 defer tg.cleanup()
4971 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4972 tg.setenv("GOOS", "windwos")
4973 tg.runFail("build", "exclude")
4974 tg.grepStderr("unsupported GOOS/GOARCH pair", "GOOS=windwos go build exclude did not report 'unsupported GOOS/GOARCH pair'")
4977 func TestUpxCompression(t *testing.T) {
4978 if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
4979 t.Skipf("skipping upx test on %s/%s", runtime.GOOS, runtime.GOARCH)
4982 out, err := exec.Command("upx", "--version").CombinedOutput()
4983 if err != nil {
4984 t.Skip("skipping because upx is not available")
4987 // upx --version prints `upx <version>` in the first line of output:
4988 // upx 3.94
4989 // [...]
4990 re := regexp.MustCompile(`([[:digit:]]+)\.([[:digit:]]+)`)
4991 upxVersion := re.FindStringSubmatch(string(out))
4992 if len(upxVersion) != 3 {
4993 t.Errorf("bad upx version string: %s", upxVersion)
4996 major, err1 := strconv.Atoi(upxVersion[1])
4997 minor, err2 := strconv.Atoi(upxVersion[2])
4998 if err1 != nil || err2 != nil {
4999 t.Errorf("bad upx version string: %s", upxVersion[0])
5002 // Anything below 3.94 is known not to work with go binaries
5003 if (major < 3) || (major == 3 && minor < 94) {
5004 t.Skipf("skipping because upx version %v.%v is too old", major, minor)
5007 tg := testgo(t)
5008 defer tg.cleanup()
5010 tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello upx") }`)
5011 src := tg.path("main.go")
5012 obj := tg.path("main")
5013 tg.run("build", "-o", obj, src)
5015 out, err = exec.Command("upx", obj).CombinedOutput()
5016 if err != nil {
5017 t.Logf("executing upx\n%s\n", out)
5018 t.Fatalf("upx failed with %v", err)
5021 out, err = exec.Command(obj).CombinedOutput()
5022 if err != nil {
5023 t.Logf("%s", out)
5024 t.Fatalf("running compressed go binary failed with error %s", err)
5026 if string(out) != "hello upx" {
5027 t.Fatalf("bad output from compressed go binary:\ngot %q; want %q", out, "hello upx")
5031 func TestGOTMPDIR(t *testing.T) {
5032 tg := testgo(t)
5033 defer tg.cleanup()
5034 tg.parallel()
5035 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5036 tg.makeTempdir()
5037 tg.setenv("GOTMPDIR", tg.tempdir)
5038 tg.setenv("GOCACHE", "off")
5040 // complex/x is a trivial non-main package.
5041 tg.run("build", "-work", "-x", "complex/w")
5042 tg.grepStderr("WORK="+regexp.QuoteMeta(tg.tempdir), "did not work in $GOTMPDIR")
5045 func TestBuildCache(t *testing.T) {
5046 tooSlow(t)
5047 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5048 t.Skip("GODEBUG gocacheverify")
5050 tg := testgo(t)
5051 defer tg.cleanup()
5052 tg.parallel()
5053 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5054 tg.makeTempdir()
5055 tg.setenv("GOCACHE", tg.tempdir)
5057 // complex/w is a trivial non-main package.
5058 // It imports nothing, so there should be no Deps.
5059 tg.run("list", "-f={{join .Deps \" \"}}", "complex/w")
5060 tg.grepStdoutNot(".+", "complex/w depends on unexpected packages")
5062 tg.run("build", "-x", "complex/w")
5063 tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler")
5065 tg.run("build", "-x", "complex/w")
5066 tg.grepStderrNot(`[\\/]compile|gccgo`, "ran compiler incorrectly")
5068 tg.run("build", "-a", "-x", "complex/w")
5069 tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler with -a")
5071 // complex is a non-trivial main package.
5072 // the link step should not be cached.
5073 tg.run("build", "-o", os.DevNull, "-x", "complex")
5074 tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
5076 tg.run("build", "-o", os.DevNull, "-x", "complex")
5077 tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
5080 func TestCacheOutput(t *testing.T) {
5081 // Test that command output is cached and replayed too.
5082 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5083 t.Skip("GODEBUG gocacheverify")
5085 tg := testgo(t)
5086 defer tg.cleanup()
5087 tg.parallel()
5088 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5089 tg.makeTempdir()
5090 tg.setenv("GOCACHE", tg.tempdir)
5092 tg.run("build", "-gcflags=-m", "errors")
5093 stdout1 := tg.getStdout()
5094 stderr1 := tg.getStderr()
5096 tg.run("build", "-gcflags=-m", "errors")
5097 stdout2 := tg.getStdout()
5098 stderr2 := tg.getStderr()
5100 if stdout2 != stdout1 || stderr2 != stderr1 {
5101 t.Errorf("cache did not reproduce output:\n\nstdout1:\n%s\n\nstdout2:\n%s\n\nstderr1:\n%s\n\nstderr2:\n%s",
5102 stdout1, stdout2, stderr1, stderr2)
5106 func TestCacheCoverage(t *testing.T) {
5107 tooSlow(t)
5109 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5110 t.Skip("GODEBUG gocacheverify")
5113 tg := testgo(t)
5114 defer tg.cleanup()
5115 tg.parallel()
5116 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5117 tg.makeTempdir()
5119 tg.setenv("GOCACHE", tg.path("c1"))
5120 tg.run("test", "-cover", "-short", "strings")
5121 tg.run("test", "-cover", "-short", "math", "strings")
5124 func TestIssue22588(t *testing.T) {
5125 // Don't get confused by stderr coming from tools.
5126 tg := testgo(t)
5127 defer tg.cleanup()
5128 tg.parallel()
5130 if _, err := os.Stat("/usr/bin/time"); err != nil {
5131 t.Skip(err)
5134 tg.run("list", "-f={{.Stale}}", "runtime")
5135 tg.run("list", "-toolexec=/usr/bin/time", "-f={{.Stale}}", "runtime")
5136 tg.grepStdout("false", "incorrectly reported runtime as stale")
5139 func TestIssue22531(t *testing.T) {
5140 tooSlow(t)
5141 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5142 t.Skip("GODEBUG gocacheverify")
5144 tg := testgo(t)
5145 defer tg.cleanup()
5146 tg.parallel()
5147 tg.makeTempdir()
5148 tg.setenv("GOPATH", tg.tempdir)
5149 tg.setenv("GOCACHE", tg.path("cache"))
5150 tg.tempFile("src/m/main.go", "package main /* c1 */; func main() {}\n")
5151 tg.run("install", "-x", "m")
5152 tg.run("list", "-f", "{{.Stale}}", "m")
5153 tg.grepStdout("false", "reported m as stale after install")
5154 tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5156 // The link action ID did not include the full main build ID,
5157 // even though the full main build ID is written into the
5158 // eventual binary. That caused the following install to
5159 // be a no-op, thinking the gofmt binary was up-to-date,
5160 // even though .Stale could see it was not.
5161 tg.tempFile("src/m/main.go", "package main /* c2 */; func main() {}\n")
5162 tg.run("install", "-x", "m")
5163 tg.run("list", "-f", "{{.Stale}}", "m")
5164 tg.grepStdout("false", "reported m as stale after reinstall")
5165 tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5168 func TestIssue22596(t *testing.T) {
5169 tooSlow(t)
5170 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5171 t.Skip("GODEBUG gocacheverify")
5173 tg := testgo(t)
5174 defer tg.cleanup()
5175 tg.parallel()
5176 tg.makeTempdir()
5177 tg.setenv("GOCACHE", tg.path("cache"))
5178 tg.tempFile("gopath1/src/p/p.go", "package p; func F(){}\n")
5179 tg.tempFile("gopath2/src/p/p.go", "package p; func F(){}\n")
5181 tg.setenv("GOPATH", tg.path("gopath1"))
5182 tg.run("list", "-f={{.Target}}", "p")
5183 target1 := strings.TrimSpace(tg.getStdout())
5184 tg.run("install", "p")
5185 tg.wantNotStale("p", "", "p stale after install")
5187 tg.setenv("GOPATH", tg.path("gopath2"))
5188 tg.run("list", "-f={{.Target}}", "p")
5189 target2 := strings.TrimSpace(tg.getStdout())
5190 tg.must(os.MkdirAll(filepath.Dir(target2), 0777))
5191 tg.must(copyFile(target1, target2, 0666))
5192 tg.wantStale("p", "build ID mismatch", "p not stale after copy from gopath1")
5193 tg.run("install", "p")
5194 tg.wantNotStale("p", "", "p stale after install2")
5197 func TestTestCache(t *testing.T) {
5198 tooSlow(t)
5200 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5201 t.Skip("GODEBUG gocacheverify")
5203 tg := testgo(t)
5204 defer tg.cleanup()
5205 tg.parallel()
5206 tg.makeTempdir()
5207 tg.setenv("GOPATH", tg.tempdir)
5208 tg.setenv("GOCACHE", tg.path("cache"))
5210 if runtime.Compiler != "gccgo" {
5211 // timeout here should not affect result being cached
5212 // or being retrieved later.
5213 tg.run("test", "-x", "-timeout=10s", "errors")
5214 tg.grepStderr(`[\\/](compile|gccgo) `, "did not run compiler")
5215 tg.grepStderr(`[\\/](link|gccgo) `, "did not run linker")
5216 tg.grepStderr(`errors\.test`, "did not run test")
5218 tg.run("test", "-x", "errors")
5219 tg.grepStdout(`ok \terrors\t\(cached\)`, "did not report cached result")
5220 tg.grepStderrNot(`[\\/](compile|gccgo) `, "incorrectly ran compiler")
5221 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5222 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5223 tg.grepStderrNot("DO NOT USE", "poisoned action status leaked")
5225 // Even very low timeouts do not disqualify cached entries.
5226 tg.run("test", "-timeout=1ns", "-x", "errors")
5227 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5229 tg.run("clean", "-testcache")
5230 tg.run("test", "-x", "errors")
5231 tg.grepStderr(`errors\.test`, "did not run test")
5234 // The -p=1 in the commands below just makes the -x output easier to read.
5236 t.Log("\n\nINITIAL\n\n")
5238 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5239 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\nvar X = 1\n")
5240 tg.tempFile("src/t/t1/t1_test.go", "package t\nimport \"testing\"\nfunc Test1(*testing.T) {}\n")
5241 tg.tempFile("src/t/t2/t2_test.go", "package t\nimport _ \"p1\"\nimport \"testing\"\nfunc Test2(*testing.T) {}\n")
5242 tg.tempFile("src/t/t3/t3_test.go", "package t\nimport \"p1\"\nimport \"testing\"\nfunc Test3(t *testing.T) {t.Log(p1.X)}\n")
5243 tg.tempFile("src/t/t4/t4_test.go", "package t\nimport \"p2\"\nimport \"testing\"\nfunc Test4(t *testing.T) {t.Log(p2.X)}")
5244 tg.run("test", "-x", "-v", "-short", "t/...")
5246 t.Log("\n\nREPEAT\n\n")
5248 tg.run("test", "-x", "-v", "-short", "t/...")
5249 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5250 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5251 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5252 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5253 tg.grepStderrNot(`[\\/](compile|gccgo) `, "incorrectly ran compiler")
5254 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5255 tg.grepStderrNot(`p[0-9]\.test`, "incorrectly ran test")
5257 t.Log("\n\nCOMMENT\n\n")
5259 // Changing the program text without affecting the compiled package
5260 // should result in the package being rebuilt but nothing more.
5261 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 01\n")
5262 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5263 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t1")
5264 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t2")
5265 tg.grepStdout(`ok \tt/t3\t\(cached\)`, "did not cache t3")
5266 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t4")
5267 tg.grepStderrNot(`([\\/](compile|gccgo) ).*t[0-9]_test\.go`, "incorrectly ran compiler")
5268 tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5269 tg.grepStderrNot(`t[0-9]\.test.*test\.short`, "incorrectly ran test")
5271 t.Log("\n\nCHANGE\n\n")
5273 // Changing the actual package should have limited effects.
5274 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 02\n")
5275 tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5277 // p2 should have been rebuilt.
5278 tg.grepStderr(`([\\/]compile|gccgo).*p2.go`, "did not recompile p2")
5280 // t1 does not import anything, should not have been rebuilt.
5281 tg.grepStderrNot(`([\\/]compile|gccgo).*t1_test.go`, "incorrectly recompiled t1")
5282 tg.grepStderrNot(`([\\/]link|gccgo).*t1_test`, "incorrectly relinked t1_test")
5283 tg.grepStdout(`ok \tt/t1\t\(cached\)`, "did not cache t/t1")
5285 // t2 imports p1 and must be rebuilt and relinked,
5286 // but the change should not have any effect on the test binary,
5287 // so the test should not have been rerun.
5288 tg.grepStderr(`([\\/]compile|gccgo).*t2_test.go`, "did not recompile t2")
5289 tg.grepStderr(`([\\/]link|gccgo).*t2\.test`, "did not relink t2_test")
5290 // This check does not currently work with gccgo, as garbage
5291 // collection of unused variables is not turned on by default.
5292 if runtime.Compiler != "gccgo" {
5293 tg.grepStdout(`ok \tt/t2\t\(cached\)`, "did not cache t/t2")
5296 // t3 imports p1, and changing X changes t3's test binary.
5297 tg.grepStderr(`([\\/]compile|gccgo).*t3_test.go`, "did not recompile t3")
5298 tg.grepStderr(`([\\/]link|gccgo).*t3\.test`, "did not relink t3_test")
5299 tg.grepStderr(`t3\.test.*-test.short`, "did not rerun t3_test")
5300 tg.grepStdoutNot(`ok \tt/t3\t\(cached\)`, "reported cached t3_test result")
5302 // t4 imports p2, but p2 did not change, so t4 should be relinked, not recompiled,
5303 // and not rerun.
5304 tg.grepStderrNot(`([\\/]compile|gccgo).*t4_test.go`, "incorrectly recompiled t4")
5305 tg.grepStderr(`([\\/]link|gccgo).*t4\.test`, "did not relink t4_test")
5306 // This check does not currently work with gccgo, as garbage
5307 // collection of unused variables is not turned on by default.
5308 if runtime.Compiler != "gccgo" {
5309 tg.grepStdout(`ok \tt/t4\t\(cached\)`, "did not cache t/t4")
5313 func TestTestCacheInputs(t *testing.T) {
5314 tooSlow(t)
5316 if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5317 t.Skip("GODEBUG gocacheverify")
5319 tg := testgo(t)
5320 defer tg.cleanup()
5321 tg.parallel()
5322 tg.makeTempdir()
5323 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5324 tg.setenv("GOCACHE", tg.path("cache"))
5326 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5327 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"))
5328 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("x"), 0644))
5329 old := time.Now().Add(-1 * time.Minute)
5330 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5331 info, err := os.Stat(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5332 if err != nil {
5333 t.Fatal(err)
5335 t.Logf("file.txt: old=%v, info.ModTime=%v", old, info.ModTime()) // help debug when Chtimes lies about succeeding
5336 tg.setenv("TESTKEY", "x")
5338 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), []byte("#!/bin/sh\nexit 0\n"), 0755))
5339 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old, old))
5341 tg.run("test", "testcache")
5342 tg.run("test", "testcache")
5343 tg.grepStdout(`\(cached\)`, "did not cache")
5345 tg.setenv("TESTKEY", "y")
5346 tg.run("test", "testcache")
5347 tg.grepStdoutNot(`\(cached\)`, "did not notice env var change")
5348 tg.run("test", "testcache")
5349 tg.grepStdout(`\(cached\)`, "did not cache")
5351 tg.run("test", "testcache", "-run=FileSize")
5352 tg.run("test", "testcache", "-run=FileSize")
5353 tg.grepStdout(`\(cached\)`, "did not cache")
5354 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxx"), 0644))
5355 tg.run("test", "testcache", "-run=FileSize")
5356 tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5357 tg.run("test", "testcache", "-run=FileSize")
5358 tg.grepStdout(`\(cached\)`, "did not cache")
5360 tg.run("test", "testcache", "-run=Chdir")
5361 tg.run("test", "testcache", "-run=Chdir")
5362 tg.grepStdout(`\(cached\)`, "did not cache")
5363 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxxxx"), 0644))
5364 tg.run("test", "testcache", "-run=Chdir")
5365 tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5366 tg.run("test", "testcache", "-run=Chdir")
5367 tg.grepStdout(`\(cached\)`, "did not cache")
5369 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5370 tg.run("test", "testcache", "-run=FileContent")
5371 tg.run("test", "testcache", "-run=FileContent")
5372 tg.grepStdout(`\(cached\)`, "did not cache")
5373 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("yyy"), 0644))
5374 old2 := old.Add(10 * time.Second)
5375 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old2, old2))
5376 tg.run("test", "testcache", "-run=FileContent")
5377 tg.grepStdoutNot(`\(cached\)`, "did not notice file content change")
5378 tg.run("test", "testcache", "-run=FileContent")
5379 tg.grepStdout(`\(cached\)`, "did not cache")
5381 tg.run("test", "testcache", "-run=DirList")
5382 tg.run("test", "testcache", "-run=DirList")
5383 tg.grepStdout(`\(cached\)`, "did not cache")
5384 tg.must(os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt")))
5385 tg.run("test", "testcache", "-run=DirList")
5386 tg.grepStdoutNot(`\(cached\)`, "did not notice directory change")
5387 tg.run("test", "testcache", "-run=DirList")
5388 tg.grepStdout(`\(cached\)`, "did not cache")
5390 tg.tempFile("file.txt", "")
5391 tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"), []byte(`package testcache
5393 import (
5394 "os"
5395 "testing"
5398 func TestExternalFile(t *testing.T) {
5399 os.Open(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5400 _, err := os.Stat(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5401 if err != nil {
5402 t.Fatal(err)
5405 `), 0666))
5406 defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"))
5407 tg.run("test", "testcache", "-run=ExternalFile")
5408 tg.run("test", "testcache", "-run=ExternalFile")
5409 tg.grepStdout(`\(cached\)`, "did not cache")
5410 tg.must(os.Remove(filepath.Join(tg.tempdir, "file.txt")))
5411 tg.run("test", "testcache", "-run=ExternalFile")
5412 tg.grepStdout(`\(cached\)`, "did not cache")
5414 switch runtime.GOOS {
5415 case "nacl", "plan9", "windows":
5416 // no shell scripts
5417 default:
5418 tg.run("test", "testcache", "-run=Exec")
5419 tg.run("test", "testcache", "-run=Exec")
5420 tg.grepStdout(`\(cached\)`, "did not cache")
5421 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old2, old2))
5422 tg.run("test", "testcache", "-run=Exec")
5423 tg.grepStdoutNot(`\(cached\)`, "did not notice script change")
5424 tg.run("test", "testcache", "-run=Exec")
5425 tg.grepStdout(`\(cached\)`, "did not cache")
5429 func TestNoCache(t *testing.T) {
5430 switch runtime.GOOS {
5431 case "windows":
5432 t.Skipf("no unwritable directories on %s", runtime.GOOS)
5434 if os.Getuid() == 0 {
5435 t.Skip("skipping test because running as root")
5438 tg := testgo(t)
5439 defer tg.cleanup()
5440 tg.parallel()
5441 tg.tempFile("triv.go", `package main; func main() {}`)
5442 tg.must(os.MkdirAll(tg.path("unwritable"), 0555))
5443 home := "HOME"
5444 if runtime.GOOS == "plan9" {
5445 home = "home"
5447 tg.setenv(home, tg.path(filepath.Join("unwritable", "home")))
5448 tg.unsetenv("GOCACHE")
5449 tg.run("build", "-o", tg.path("triv"), tg.path("triv.go"))
5450 tg.grepStderr("disabling cache", "did not disable cache")
5453 func TestTestVet(t *testing.T) {
5454 tooSlow(t)
5455 tg := testgo(t)
5456 defer tg.cleanup()
5457 tg.parallel()
5459 tg.tempFile("p1_test.go", `
5460 package p
5461 import "testing"
5462 func Test(t *testing.T) {
5463 t.Logf("%d") // oops
5467 tg.runFail("test", tg.path("p1_test.go"))
5468 tg.grepStderr(`Logf format %d`, "did not diagnose bad Logf")
5469 tg.run("test", "-vet=off", tg.path("p1_test.go"))
5470 tg.grepStdout(`^ok`, "did not print test summary")
5472 tg.tempFile("p1.go", `
5473 package p
5474 import "fmt"
5475 func F() {
5476 fmt.Printf("%d") // oops
5479 tg.runFail("test", tg.path("p1.go"))
5480 tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5481 tg.run("test", "-x", "-vet=shift", tg.path("p1.go"))
5482 tg.grepStderr(`[\\/]vet.*-shift`, "did not run vet with -shift")
5483 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5484 tg.run("test", "-vet=off", tg.path("p1.go"))
5485 tg.grepStdout(`\[no test files\]`, "did not print test summary")
5487 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5488 tg.run("test", "vetcycle") // must not fail; #22890
5490 tg.runFail("test", "vetfail/...")
5491 tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5492 tg.grepStdout(`ok\s+vetfail/p2`, "did not run vetfail/p2")
5495 func TestTestRebuild(t *testing.T) {
5496 tg := testgo(t)
5497 defer tg.cleanup()
5498 tg.parallel()
5500 // golang.org/issue/23701.
5501 // b_test imports b with augmented method from export_test.go.
5502 // b_test also imports a, which imports b.
5503 // Must not accidentally see un-augmented b propagate through a to b_test.
5504 tg.tempFile("src/a/a.go", `package a
5505 import "b"
5506 type Type struct{}
5507 func (*Type) M() b.T {return 0}
5509 tg.tempFile("src/b/b.go", `package b
5510 type T int
5511 type I interface {M() T}
5513 tg.tempFile("src/b/export_test.go", `package b
5514 func (*T) Method() *T { return nil }
5516 tg.tempFile("src/b/b_test.go", `package b_test
5517 import (
5518 "testing"
5520 . "b"
5522 func TestBroken(t *testing.T) {
5523 x := new(T)
5524 x.Method()
5525 _ = new(a.Type)
5529 tg.setenv("GOPATH", tg.path("."))
5530 tg.run("test", "b")
5533 func TestInstallDeps(t *testing.T) {
5534 tooSlow(t)
5535 tg := testgo(t)
5536 defer tg.cleanup()
5537 tg.parallel()
5538 tg.makeTempdir()
5539 tg.setenv("GOPATH", tg.tempdir)
5541 tg.tempFile("src/p1/p1.go", "package p1\nvar X = 1\n")
5542 tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\n")
5543 tg.tempFile("src/main1/main.go", "package main\nimport _ \"p2\"\nfunc main() {}\n")
5545 tg.run("list", "-f={{.Target}}", "p1")
5546 p1 := strings.TrimSpace(tg.getStdout())
5547 tg.run("list", "-f={{.Target}}", "p2")
5548 p2 := strings.TrimSpace(tg.getStdout())
5549 tg.run("list", "-f={{.Target}}", "main1")
5550 main1 := strings.TrimSpace(tg.getStdout())
5552 tg.run("install", "main1")
5554 tg.mustExist(main1)
5555 tg.mustNotExist(p2)
5556 tg.mustNotExist(p1)
5558 tg.run("install", "p2")
5559 tg.mustExist(p2)
5560 tg.mustNotExist(p1)
5562 // don't let install -i overwrite runtime
5563 tg.wantNotStale("runtime", "", "must be non-stale before install -i")
5565 tg.run("install", "-i", "main1")
5566 tg.mustExist(p1)
5567 tg.must(os.Remove(p1))
5569 tg.run("install", "-i", "p2")
5570 tg.mustExist(p1)
5573 func TestFmtLoadErrors(t *testing.T) {
5574 tg := testgo(t)
5575 defer tg.cleanup()
5576 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5577 tg.runFail("fmt", "does-not-exist")
5578 tg.run("fmt", "-n", "exclude")
5581 func TestRelativePkgdir(t *testing.T) {
5582 tooSlow(t)
5583 tg := testgo(t)
5584 defer tg.cleanup()
5585 tg.makeTempdir()
5586 tg.setenv("GOCACHE", "off")
5587 tg.cd(tg.tempdir)
5589 tg.run("build", "-i", "-pkgdir=.", "runtime")
5592 func TestGcflagsPatterns(t *testing.T) {
5593 skipIfGccgo(t, "gccgo has no standard packages")
5594 tg := testgo(t)
5595 defer tg.cleanup()
5596 tg.setenv("GOPATH", "")
5597 tg.setenv("GOCACHE", "off")
5599 tg.run("build", "-n", "-v", "-gcflags= \t\r\n -e", "fmt")
5600 tg.grepStderr("^# fmt", "did not rebuild fmt")
5601 tg.grepStderrNot("^# reflect", "incorrectly rebuilt reflect")
5603 tg.run("build", "-n", "-v", "-gcflags=-e", "fmt", "reflect")
5604 tg.grepStderr("^# fmt", "did not rebuild fmt")
5605 tg.grepStderr("^# reflect", "did not rebuild reflect")
5606 tg.grepStderrNot("^# runtime", "incorrectly rebuilt runtime")
5608 tg.run("build", "-n", "-x", "-v", "-gcflags= \t\r\n reflect \t\r\n = \t\r\n -N", "fmt")
5609 tg.grepStderr("^# fmt", "did not rebuild fmt")
5610 tg.grepStderr("^# reflect", "did not rebuild reflect")
5611 tg.grepStderr("compile.* -N .*-p reflect", "did not build reflect with -N flag")
5612 tg.grepStderrNot("compile.* -N .*-p fmt", "incorrectly built fmt with -N flag")
5614 tg.run("test", "-c", "-n", "-gcflags=-N", "-ldflags=-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")
5618 tg.run("test", "-c", "-n", "-gcflags=strings=-N", "-ldflags=strings=-X=x.y=z", "strings")
5619 tg.grepStderr("compile.* -N .*compare_test.go", "did not compile strings_test package with -N flag")
5620 tg.grepStderr("link.* -X=x.y=z", "did not link strings.test binary with -X flag")
5623 func TestGoTestMinusN(t *testing.T) {
5624 // Intent here is to verify that 'go test -n' works without crashing.
5625 // This reuses flag_test.go, but really any test would do.
5626 tg := testgo(t)
5627 defer tg.cleanup()
5628 tg.run("test", "testdata/flag_test.go", "-n", "-args", "-v=7")
5631 func TestGoTestJSON(t *testing.T) {
5632 skipIfGccgo(t, "gccgo does not have standard packages")
5633 tooSlow(t)
5635 tg := testgo(t)
5636 defer tg.cleanup()
5637 tg.parallel()
5638 tg.makeTempdir()
5639 tg.setenv("GOCACHE", tg.tempdir)
5640 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5642 // It would be nice to test that the output is interlaced
5643 // but it seems to be impossible to do that in a short test
5644 // that isn't also flaky. Just check that we get JSON output.
5645 tg.run("test", "-json", "-short", "-v", "errors", "empty/pkg", "skipper")
5646 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5647 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5649 tg.grepStdout(`"Action":"output","Package":"empty/pkg","Output":".*no test files`, "did not see no test files print")
5650 tg.grepStdout(`"Action":"skip","Package":"empty/pkg"`, "did not see skip")
5652 tg.grepStdout(`"Action":"output","Package":"skipper","Test":"Test","Output":"--- SKIP:`, "did not see SKIP output")
5653 tg.grepStdout(`"Action":"skip","Package":"skipper","Test":"Test"`, "did not see skip result for Test")
5655 tg.run("test", "-json", "-short", "-v", "errors")
5656 tg.grepStdout(`"Action":"output","Package":"errors","Output":".*\(cached\)`, "did not see no cached output")
5658 tg.run("test", "-json", "-bench=NONE", "-short", "-v", "errors")
5659 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5660 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5662 tg.run("test", "-o", tg.path("errors.test.exe"), "-c", "errors")
5663 tg.run("tool", "test2json", "-p", "errors", tg.path("errors.test.exe"), "-test.v", "-test.short")
5664 tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5665 tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5666 tg.grepStdout(`\{"Action":"pass","Package":"errors"\}`, "did not see final pass")
5669 func TestFailFast(t *testing.T) {
5670 tooSlow(t)
5671 tg := testgo(t)
5672 defer tg.cleanup()
5674 tests := []struct {
5675 run string
5676 failfast bool
5677 nfail int
5679 {"TestFailingA", true, 1},
5680 {"TestFailing[AB]", true, 1},
5681 {"TestFailing[AB]", false, 2},
5682 // mix with non-failing tests:
5683 {"TestA|TestFailing[AB]", true, 1},
5684 {"TestA|TestFailing[AB]", false, 2},
5685 // mix with parallel tests:
5686 {"TestFailingB|TestParallelFailingA", true, 2},
5687 {"TestFailingB|TestParallelFailingA", false, 2},
5688 {"TestFailingB|TestParallelFailing[AB]", true, 3},
5689 {"TestFailingB|TestParallelFailing[AB]", false, 3},
5690 // mix with parallel sub-tests
5691 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", true, 3},
5692 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", false, 5},
5693 {"TestParallelFailingSubtestsA", true, 1},
5694 // only parallels:
5695 {"TestParallelFailing[AB]", false, 2},
5696 // non-parallel subtests:
5697 {"TestFailingSubtestsA", true, 1},
5698 {"TestFailingSubtestsA", false, 2},
5701 for _, tt := range tests {
5702 t.Run(tt.run, func(t *testing.T) {
5703 tg.runFail("test", "./testdata/src/failfast_test.go", "-run="+tt.run, "-failfast="+strconv.FormatBool(tt.failfast))
5705 nfail := strings.Count(tg.getStdout(), "FAIL - ")
5707 if nfail != tt.nfail {
5708 t.Errorf("go test -run=%s -failfast=%t printed %d FAILs, want %d", tt.run, tt.failfast, nfail, tt.nfail)
5714 // Issue 22986.
5715 func TestImportPath(t *testing.T) {
5716 tooSlow(t)
5717 tg := testgo(t)
5718 defer tg.cleanup()
5719 tg.parallel()
5721 tg.tempFile("src/a/a.go", `
5722 package main
5724 import (
5725 "log"
5726 p "a/p-1.0"
5729 func main() {
5730 if !p.V {
5731 log.Fatal("false")
5735 tg.tempFile("src/a/a_test.go", `
5736 package main_test
5738 import (
5739 p "a/p-1.0"
5740 "testing"
5743 func TestV(t *testing.T) {
5744 if !p.V {
5745 t.Fatal("false")
5749 tg.tempFile("src/a/p-1.0/p.go", `
5750 package p
5752 var V = true
5754 func init() {}
5757 tg.setenv("GOPATH", tg.path("."))
5758 tg.run("build", "-o", tg.path("a.exe"), "a")
5759 tg.run("test", "a")
5762 // Issue 23150.
5763 func TestCpuprofileTwice(t *testing.T) {
5764 tg := testgo(t)
5765 defer tg.cleanup()
5766 tg.parallel()
5767 tg.tempFile("prof/src/x/x_test.go", `
5768 package x_test
5769 import (
5770 "testing"
5771 "time"
5773 func TestSleep(t *testing.T) { time.Sleep(10 * time.Millisecond) }`)
5774 tg.setenv("GOPATH", tg.path("prof"))
5775 bin := tg.path("x.test")
5776 out := tg.path("cpu.out")
5777 tg.run("test", "-o="+bin, "-cpuprofile="+out, "x")
5778 tg.must(os.Remove(out))
5779 tg.run("test", "-o="+bin, "-cpuprofile="+out, "x")
5780 tg.mustExist(out)
5783 // Issue 23694.
5784 func TestAtomicCoverpkgAll(t *testing.T) {
5785 skipIfGccgo(t, "gccgo has no cover tool")
5786 tg := testgo(t)
5787 defer tg.cleanup()
5788 tg.parallel()
5790 tg.tempFile("src/x/x.go", `package x; import _ "sync/atomic"; func F() {}`)
5791 tg.tempFile("src/x/x_test.go", `package x; import "testing"; func TestF(t *testing.T) { F() }`)
5792 tg.setenv("GOPATH", tg.path("."))
5793 tg.run("test", "-coverpkg=all", "-covermode=atomic", "x")
5794 if canRace {
5795 tg.run("test", "-coverpkg=all", "-race", "x")
5799 func TestBadCommandLines(t *testing.T) {
5800 tg := testgo(t)
5801 defer tg.cleanup()
5803 tg.tempFile("src/x/x.go", "package x\n")
5804 tg.setenv("GOPATH", tg.path("."))
5806 tg.run("build", "x")
5808 tg.tempFile("src/x/@y.go", "package x\n")
5809 tg.runFail("build", "x")
5810 tg.grepStderr("invalid input file name \"@y.go\"", "did not reject @y.go")
5811 tg.must(os.Remove(tg.path("src/x/@y.go")))
5813 tg.tempFile("src/x/-y.go", "package x\n")
5814 tg.runFail("build", "x")
5815 tg.grepStderr("invalid input file name \"-y.go\"", "did not reject -y.go")
5816 tg.must(os.Remove(tg.path("src/x/-y.go")))
5818 if runtime.Compiler == "gccgo" {
5819 tg.runFail("build", "-gccgoflags=all=@x", "x")
5820 } else {
5821 tg.runFail("build", "-gcflags=all=@x", "x")
5823 tg.grepStderr("invalid command-line argument @x in command", "did not reject @x during exec")
5825 tg.tempFile("src/@x/x.go", "package x\n")
5826 tg.setenv("GOPATH", tg.path("."))
5827 tg.runFail("build", "@x")
5828 tg.grepStderr("invalid input directory name \"@x\"", "did not reject @x directory")
5830 tg.tempFile("src/@x/y/y.go", "package y\n")
5831 tg.setenv("GOPATH", tg.path("."))
5832 tg.runFail("build", "@x/y")
5833 tg.grepStderr("invalid import path \"@x/y\"", "did not reject @x/y import path")
5835 tg.tempFile("src/-x/x.go", "package x\n")
5836 tg.setenv("GOPATH", tg.path("."))
5837 tg.runFail("build", "--", "-x")
5838 tg.grepStderr("invalid input directory name \"-x\"", "did not reject -x directory")
5840 tg.tempFile("src/-x/y/y.go", "package y\n")
5841 tg.setenv("GOPATH", tg.path("."))
5842 tg.runFail("build", "--", "-x/y")
5843 tg.grepStderr("invalid import path \"-x/y\"", "did not reject -x/y import path")
5846 func TestBadCgoDirectives(t *testing.T) {
5847 if !canCgo {
5848 t.Skip("no cgo")
5850 tg := testgo(t)
5851 defer tg.cleanup()
5853 tg.tempFile("src/x/x.go", "package x\n")
5854 tg.setenv("GOPATH", tg.path("."))
5856 if runtime.Compiler == "gc" {
5857 tg.tempFile("src/x/x.go", `package x
5859 //go:cgo_ldflag "-fplugin=foo.so"
5861 import "C"
5863 tg.runFail("build", "x")
5864 tg.grepStderr("//go:cgo_ldflag .* only allowed in cgo-generated code", "did not reject //go:cgo_ldflag directive")
5867 tg.must(os.Remove(tg.path("src/x/x.go")))
5868 tg.runFail("build", "x")
5869 tg.grepStderr("no Go files", "did not report missing source code")
5870 tg.tempFile("src/x/_cgo_yy.go", `package x
5872 //go:cgo_ldflag "-fplugin=foo.so"
5874 import "C"
5876 tg.runFail("build", "x")
5877 tg.grepStderr("no Go files", "did not report missing source code") // _* files are ignored...
5879 if runtime.Compiler == "gc" {
5880 tg.runFail("build", tg.path("src/x/_cgo_yy.go")) // ... but if forced, the comment is rejected
5881 // Actually, today there is a separate issue that _ files named
5882 // on the command-line are ignored. Once that is fixed,
5883 // we want to see the cgo_ldflag error.
5884 tg.grepStderr("//go:cgo_ldflag only allowed in cgo-generated code|no Go files", "did not reject //go:cgo_ldflag directive")
5887 tg.must(os.Remove(tg.path("src/x/_cgo_yy.go")))
5889 tg.tempFile("src/x/x.go", "package x\n")
5890 tg.tempFile("src/x/y.go", `package x
5891 // #cgo CFLAGS: -fplugin=foo.so
5892 import "C"
5894 tg.runFail("build", "x")
5895 tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
5897 tg.tempFile("src/x/y.go", `package x
5898 // #cgo CFLAGS: -Ibar -fplugin=foo.so
5899 import "C"
5901 tg.runFail("build", "x")
5902 tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
5904 tg.tempFile("src/x/y.go", `package x
5905 // #cgo pkg-config: -foo
5906 import "C"
5908 tg.runFail("build", "x")
5909 tg.grepStderr("invalid pkg-config package name: -foo", "did not reject pkg-config: -foo")
5911 tg.tempFile("src/x/y.go", `package x
5912 // #cgo pkg-config: @foo
5913 import "C"
5915 tg.runFail("build", "x")
5916 tg.grepStderr("invalid pkg-config package name: @foo", "did not reject pkg-config: -foo")
5918 tg.tempFile("src/x/y.go", `package x
5919 // #cgo CFLAGS: @foo
5920 import "C"
5922 tg.runFail("build", "x")
5923 tg.grepStderr("invalid flag in #cgo CFLAGS: @foo", "did not reject @foo flag")
5925 tg.tempFile("src/x/y.go", `package x
5926 // #cgo CFLAGS: -D
5927 import "C"
5929 tg.runFail("build", "x")
5930 tg.grepStderr("invalid flag in #cgo CFLAGS: -D without argument", "did not reject trailing -I flag")
5932 // Note that -I @foo is allowed because we rewrite it into -I /path/to/src/@foo
5933 // before the check is applied. There's no such rewrite for -D.
5935 tg.tempFile("src/x/y.go", `package x
5936 // #cgo CFLAGS: -D @foo
5937 import "C"
5939 tg.runFail("build", "x")
5940 tg.grepStderr("invalid flag in #cgo CFLAGS: -D @foo", "did not reject -D @foo flag")
5942 tg.tempFile("src/x/y.go", `package x
5943 // #cgo CFLAGS: -D@foo
5944 import "C"
5946 tg.runFail("build", "x")
5947 tg.grepStderr("invalid flag in #cgo CFLAGS: -D@foo", "did not reject -D@foo flag")
5949 tg.setenv("CGO_CFLAGS", "-D@foo")
5950 tg.tempFile("src/x/y.go", `package x
5951 import "C"
5953 tg.run("build", "-n", "x")
5954 tg.grepStderr("-D@foo", "did not find -D@foo in commands")