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