]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/go/go_test.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[gostls13.git] / src / cmd / go / go_test.go
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.
4
5 package main_test
6
7 import (
8         "bytes"
9         "context"
10         "debug/elf"
11         "debug/macho"
12         "flag"
13         "fmt"
14         "go/format"
15         "internal/race"
16         "internal/testenv"
17         "io"
18         "io/ioutil"
19         "log"
20         "os"
21         "os/exec"
22         "path/filepath"
23         "regexp"
24         "runtime"
25         "strconv"
26         "strings"
27         "testing"
28         "time"
29
30         "cmd/go/internal/cache"
31         "cmd/go/internal/cfg"
32         "cmd/go/internal/robustio"
33         "cmd/internal/sys"
34 )
35
36 var (
37         canRun  = true  // whether we can run go or ./testgo
38         canRace = false // whether we can run the race detector
39         canCgo  = false // whether we can use cgo
40         canMSan = false // whether we can run the memory sanitizer
41
42         exeSuffix string // ".exe" on Windows
43
44         skipExternal = false // skip external tests
45 )
46
47 func tooSlow(t *testing.T) {
48         if testing.Short() {
49                 // In -short mode; skip test, except run it on the {darwin,linux,windows}/amd64 builders.
50                 if testenv.Builder() != "" && runtime.GOARCH == "amd64" && (runtime.GOOS == "linux" || runtime.GOOS == "darwin" || runtime.GOOS == "windows") {
51                         return
52                 }
53                 t.Skip("skipping test in -short mode")
54         }
55 }
56
57 func init() {
58         switch runtime.GOOS {
59         case "android", "js", "nacl":
60                 canRun = false
61         case "darwin":
62                 switch runtime.GOARCH {
63                 case "arm", "arm64":
64                         canRun = false
65                 }
66         case "linux":
67                 switch runtime.GOARCH {
68                 case "arm":
69                         // many linux/arm machines are too slow to run
70                         // the full set of external tests.
71                         skipExternal = true
72                 case "mips", "mipsle", "mips64", "mips64le":
73                         // Also slow.
74                         skipExternal = true
75                         if testenv.Builder() != "" {
76                                 // On the builders, skip the cmd/go
77                                 // tests. They're too slow and already
78                                 // covered by other ports. There's
79                                 // nothing os/arch specific in the
80                                 // tests.
81                                 canRun = false
82                         }
83                 }
84         case "freebsd":
85                 switch runtime.GOARCH {
86                 case "arm":
87                         // many freebsd/arm machines are too slow to run
88                         // the full set of external tests.
89                         skipExternal = true
90                         canRun = false
91                 }
92         case "plan9":
93                 switch runtime.GOARCH {
94                 case "arm":
95                         // many plan9/arm machines are too slow to run
96                         // the full set of external tests.
97                         skipExternal = true
98                 }
99         case "windows":
100                 exeSuffix = ".exe"
101         }
102 }
103
104 // testGOROOT is the GOROOT to use when running testgo, a cmd/go binary
105 // build from this process's current GOROOT, but run from a different
106 // (temp) directory.
107 var testGOROOT string
108
109 var testCC string
110 var testGOCACHE string
111
112 var testGo string
113 var testTmpDir string
114 var testBin string
115
116 // testCtx is canceled when the test binary is about to time out.
117 //
118 // If https://golang.org/issue/28135 is accepted, uses of this variable in test
119 // functions should be replaced by t.Context().
120 var testCtx = context.Background()
121
122 // The TestMain function creates a go command for testing purposes and
123 // deletes it after the tests have been run.
124 func TestMain(m *testing.M) {
125         // $GO_GCFLAGS a compiler debug flag known to cmd/dist, make.bash, etc.
126         // It is not a standard go command flag; use os.Getenv, not cfg.Getenv.
127         if os.Getenv("GO_GCFLAGS") != "" {
128                 fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
129                 fmt.Printf("cmd/go test is not compatible with $GO_GCFLAGS being set\n")
130                 fmt.Printf("SKIP\n")
131                 return
132         }
133         os.Unsetenv("GOROOT_FINAL")
134
135         flag.Parse()
136
137         timeoutFlag := flag.Lookup("test.timeout")
138         if timeoutFlag != nil {
139                 // TODO(golang.org/issue/28147): The go command does not pass the
140                 // test.timeout flag unless either -timeout or -test.timeout is explicitly
141                 // set on the command line.
142                 if d := timeoutFlag.Value.(flag.Getter).Get().(time.Duration); d != 0 {
143                         aBitShorter := d * 95 / 100
144                         var cancel context.CancelFunc
145                         testCtx, cancel = context.WithTimeout(testCtx, aBitShorter)
146                         defer cancel()
147                 }
148         }
149
150         if *proxyAddr != "" {
151                 StartProxy()
152                 select {}
153         }
154
155         // Run with a temporary TMPDIR to check that the tests don't
156         // leave anything behind.
157         topTmpdir, err := ioutil.TempDir("", "cmd-go-test-")
158         if err != nil {
159                 log.Fatal(err)
160         }
161         if !*testWork {
162                 defer removeAll(topTmpdir)
163         }
164         os.Setenv(tempEnvName(), topTmpdir)
165
166         dir, err := ioutil.TempDir(topTmpdir, "tmpdir")
167         if err != nil {
168                 log.Fatal(err)
169         }
170         testTmpDir = dir
171         if !*testWork {
172                 defer removeAll(testTmpDir)
173         }
174
175         testGOCACHE = cache.DefaultDir()
176         if canRun {
177                 testBin = filepath.Join(testTmpDir, "testbin")
178                 if err := os.Mkdir(testBin, 0777); err != nil {
179                         log.Fatal(err)
180                 }
181                 testGo = filepath.Join(testBin, "go"+exeSuffix)
182                 args := []string{"build", "-tags", "testgo", "-o", testGo}
183                 if race.Enabled {
184                         args = append(args, "-race")
185                 }
186                 gotool, err := testenv.GoTool()
187                 if err != nil {
188                         fmt.Fprintln(os.Stderr, err)
189                         os.Exit(2)
190                 }
191
192                 goEnv := func(name string) string {
193                         out, err := exec.Command(gotool, "env", name).CombinedOutput()
194                         if err != nil {
195                                 fmt.Fprintf(os.Stderr, "go env %s: %v\n%s", name, err, out)
196                                 os.Exit(2)
197                         }
198                         return strings.TrimSpace(string(out))
199                 }
200                 testGOROOT = goEnv("GOROOT")
201
202                 // The whole GOROOT/pkg tree was installed using the GOHOSTOS/GOHOSTARCH
203                 // toolchain (installed in GOROOT/pkg/tool/GOHOSTOS_GOHOSTARCH).
204                 // The testgo.exe we are about to create will be built for GOOS/GOARCH,
205                 // which means it will use the GOOS/GOARCH toolchain
206                 // (installed in GOROOT/pkg/tool/GOOS_GOARCH).
207                 // If these are not the same toolchain, then the entire standard library
208                 // will look out of date (the compilers in those two different tool directories
209                 // are built for different architectures and have different buid IDs),
210                 // which will cause many tests to do unnecessary rebuilds and some
211                 // tests to attempt to overwrite the installed standard library.
212                 // Bail out entirely in this case.
213                 hostGOOS := goEnv("GOHOSTOS")
214                 hostGOARCH := goEnv("GOHOSTARCH")
215                 if hostGOOS != runtime.GOOS || hostGOARCH != runtime.GOARCH {
216                         fmt.Fprintf(os.Stderr, "testing: warning: no tests to run\n") // magic string for cmd/go
217                         fmt.Printf("cmd/go test is not compatible with GOOS/GOARCH != GOHOSTOS/GOHOSTARCH (%s/%s != %s/%s)\n", runtime.GOOS, runtime.GOARCH, hostGOOS, hostGOARCH)
218                         fmt.Printf("SKIP\n")
219                         return
220                 }
221
222                 buildCmd := exec.Command(gotool, args...)
223                 buildCmd.Env = append(os.Environ(), "GOFLAGS=-mod=vendor")
224                 out, err := buildCmd.CombinedOutput()
225                 if err != nil {
226                         fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out)
227                         os.Exit(2)
228                 }
229
230                 out, err = exec.Command(gotool, "env", "CC").CombinedOutput()
231                 if err != nil {
232                         fmt.Fprintf(os.Stderr, "could not find testing CC: %v\n%s", err, out)
233                         os.Exit(2)
234                 }
235                 testCC = strings.TrimSpace(string(out))
236
237                 if out, err := exec.Command(testGo, "env", "CGO_ENABLED").Output(); err != nil {
238                         fmt.Fprintf(os.Stderr, "running testgo failed: %v\n", err)
239                         canRun = false
240                 } else {
241                         canCgo, err = strconv.ParseBool(strings.TrimSpace(string(out)))
242                         if err != nil {
243                                 fmt.Fprintf(os.Stderr, "can't parse go env CGO_ENABLED output: %v\n", strings.TrimSpace(string(out)))
244                         }
245                 }
246
247                 out, err = exec.Command(gotool, "env", "GOCACHE").CombinedOutput()
248                 if err != nil {
249                         fmt.Fprintf(os.Stderr, "could not find testing GOCACHE: %v\n%s", err, out)
250                         os.Exit(2)
251                 }
252                 testGOCACHE = strings.TrimSpace(string(out))
253
254                 canMSan = canCgo && sys.MSanSupported(runtime.GOOS, runtime.GOARCH)
255                 canRace = canCgo && sys.RaceDetectorSupported(runtime.GOOS, runtime.GOARCH)
256                 // The race detector doesn't work on Alpine Linux:
257                 // golang.org/issue/14481
258                 // gccgo does not support the race detector.
259                 if isAlpineLinux() || runtime.Compiler == "gccgo" {
260                         canRace = false
261                 }
262         }
263         // Don't let these environment variables confuse the test.
264         os.Setenv("GOENV", "off")
265         os.Unsetenv("GOBIN")
266         os.Unsetenv("GOPATH")
267         os.Unsetenv("GIT_ALLOW_PROTOCOL")
268         os.Setenv("HOME", "/test-go-home-does-not-exist")
269         // On some systems the default C compiler is ccache.
270         // Setting HOME to a non-existent directory will break
271         // those systems. Disable ccache and use real compiler. Issue 17668.
272         os.Setenv("CCACHE_DISABLE", "1")
273         if cfg.Getenv("GOCACHE") == "" {
274                 os.Setenv("GOCACHE", testGOCACHE) // because $HOME is gone
275         }
276
277         r := m.Run()
278         if !*testWork {
279                 removeAll(testTmpDir) // os.Exit won't run defer
280         }
281
282         if !*testWork {
283                 // There shouldn't be anything left in topTmpdir.
284                 dirf, err := os.Open(topTmpdir)
285                 if err != nil {
286                         log.Fatal(err)
287                 }
288                 names, err := dirf.Readdirnames(0)
289                 if err != nil {
290                         log.Fatal(err)
291                 }
292                 if len(names) > 0 {
293                         log.Fatalf("unexpected files left in tmpdir: %v", names)
294                 }
295
296                 removeAll(topTmpdir)
297         }
298
299         os.Exit(r)
300 }
301
302 func isAlpineLinux() bool {
303         if runtime.GOOS != "linux" {
304                 return false
305         }
306         fi, err := os.Lstat("/etc/alpine-release")
307         return err == nil && fi.Mode().IsRegular()
308 }
309
310 // The length of an mtime tick on this system. This is an estimate of
311 // how long we need to sleep to ensure that the mtime of two files is
312 // different.
313 // We used to try to be clever but that didn't always work (see golang.org/issue/12205).
314 var mtimeTick time.Duration = 1 * time.Second
315
316 // Manage a single run of the testgo binary.
317 type testgoData struct {
318         t              *testing.T
319         temps          []string
320         wd             string
321         env            []string
322         tempdir        string
323         ran            bool
324         inParallel     bool
325         stdout, stderr bytes.Buffer
326         execDir        string // dir for tg.run
327 }
328
329 // skipIfGccgo skips the test if using gccgo.
330 func skipIfGccgo(t *testing.T, msg string) {
331         if runtime.Compiler == "gccgo" {
332                 t.Skipf("skipping test not supported on gccgo: %s", msg)
333         }
334 }
335
336 // testgo sets up for a test that runs testgo.
337 func testgo(t *testing.T) *testgoData {
338         t.Helper()
339         testenv.MustHaveGoBuild(t)
340
341         if skipExternal {
342                 t.Skipf("skipping external tests on %s/%s", runtime.GOOS, runtime.GOARCH)
343         }
344
345         return &testgoData{t: t}
346 }
347
348 // must gives a fatal error if err is not nil.
349 func (tg *testgoData) must(err error) {
350         tg.t.Helper()
351         if err != nil {
352                 tg.t.Fatal(err)
353         }
354 }
355
356 // check gives a test non-fatal error if err is not nil.
357 func (tg *testgoData) check(err error) {
358         tg.t.Helper()
359         if err != nil {
360                 tg.t.Error(err)
361         }
362 }
363
364 // parallel runs the test in parallel by calling t.Parallel.
365 func (tg *testgoData) parallel() {
366         tg.t.Helper()
367         if tg.ran {
368                 tg.t.Fatal("internal testsuite error: call to parallel after run")
369         }
370         if tg.wd != "" {
371                 tg.t.Fatal("internal testsuite error: call to parallel after cd")
372         }
373         for _, e := range tg.env {
374                 if strings.HasPrefix(e, "GOROOT=") || strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
375                         val := e[strings.Index(e, "=")+1:]
376                         if strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata") {
377                                 tg.t.Fatalf("internal testsuite error: call to parallel with testdata in environment (%s)", e)
378                         }
379                 }
380         }
381         tg.inParallel = true
382         tg.t.Parallel()
383 }
384
385 // pwd returns the current directory.
386 func (tg *testgoData) pwd() string {
387         tg.t.Helper()
388         wd, err := os.Getwd()
389         if err != nil {
390                 tg.t.Fatalf("could not get working directory: %v", err)
391         }
392         return wd
393 }
394
395 // cd changes the current directory to the named directory. Note that
396 // using this means that the test must not be run in parallel with any
397 // other tests.
398 func (tg *testgoData) cd(dir string) {
399         tg.t.Helper()
400         if tg.inParallel {
401                 tg.t.Fatal("internal testsuite error: changing directory when running in parallel")
402         }
403         if tg.wd == "" {
404                 tg.wd = tg.pwd()
405         }
406         abs, err := filepath.Abs(dir)
407         tg.must(os.Chdir(dir))
408         if err == nil {
409                 tg.setenv("PWD", abs)
410         }
411 }
412
413 // sleep sleeps for one tick, where a tick is a conservative estimate
414 // of how long it takes for a file modification to get a different
415 // mtime.
416 func (tg *testgoData) sleep() {
417         time.Sleep(mtimeTick)
418 }
419
420 // setenv sets an environment variable to use when running the test go
421 // command.
422 func (tg *testgoData) setenv(name, val string) {
423         tg.t.Helper()
424         if tg.inParallel && (name == "GOROOT" || name == "GOPATH" || name == "GOBIN") && (strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata")) {
425                 tg.t.Fatalf("internal testsuite error: call to setenv with testdata (%s=%s) after parallel", name, val)
426         }
427         tg.unsetenv(name)
428         tg.env = append(tg.env, name+"="+val)
429 }
430
431 // unsetenv removes an environment variable.
432 func (tg *testgoData) unsetenv(name string) {
433         if tg.env == nil {
434                 tg.env = append([]string(nil), os.Environ()...)
435                 tg.env = append(tg.env, "GO111MODULE=off")
436         }
437         for i, v := range tg.env {
438                 if strings.HasPrefix(v, name+"=") {
439                         tg.env = append(tg.env[:i], tg.env[i+1:]...)
440                         break
441                 }
442         }
443 }
444
445 func (tg *testgoData) goTool() string {
446         return testGo
447 }
448
449 // doRun runs the test go command, recording stdout and stderr and
450 // returning exit status.
451 func (tg *testgoData) doRun(args []string) error {
452         tg.t.Helper()
453         if !canRun {
454                 panic("testgoData.doRun called but canRun false")
455         }
456         if tg.inParallel {
457                 for _, arg := range args {
458                         if strings.HasPrefix(arg, "testdata") || strings.HasPrefix(arg, "./testdata") {
459                                 tg.t.Fatal("internal testsuite error: parallel run using testdata")
460                         }
461                 }
462         }
463
464         hasGoroot := false
465         for _, v := range tg.env {
466                 if strings.HasPrefix(v, "GOROOT=") {
467                         hasGoroot = true
468                         break
469                 }
470         }
471         prog := tg.goTool()
472         if !hasGoroot {
473                 tg.setenv("GOROOT", testGOROOT)
474         }
475
476         tg.t.Logf("running testgo %v", args)
477         cmd := exec.Command(prog, args...)
478         tg.stdout.Reset()
479         tg.stderr.Reset()
480         cmd.Dir = tg.execDir
481         cmd.Stdout = &tg.stdout
482         cmd.Stderr = &tg.stderr
483         cmd.Env = tg.env
484         status := cmd.Run()
485         if tg.stdout.Len() > 0 {
486                 tg.t.Log("standard output:")
487                 tg.t.Log(tg.stdout.String())
488         }
489         if tg.stderr.Len() > 0 {
490                 tg.t.Log("standard error:")
491                 tg.t.Log(tg.stderr.String())
492         }
493         tg.ran = true
494         return status
495 }
496
497 // run runs the test go command, and expects it to succeed.
498 func (tg *testgoData) run(args ...string) {
499         tg.t.Helper()
500         if status := tg.doRun(args); status != nil {
501                 wd, _ := os.Getwd()
502                 tg.t.Logf("go %v failed unexpectedly in %s: %v", args, wd, status)
503                 tg.t.FailNow()
504         }
505 }
506
507 // runFail runs the test go command, and expects it to fail.
508 func (tg *testgoData) runFail(args ...string) {
509         tg.t.Helper()
510         if status := tg.doRun(args); status == nil {
511                 tg.t.Fatal("testgo succeeded unexpectedly")
512         } else {
513                 tg.t.Log("testgo failed as expected:", status)
514         }
515 }
516
517 // runGit runs a git command, and expects it to succeed.
518 func (tg *testgoData) runGit(dir string, args ...string) {
519         tg.t.Helper()
520         cmd := exec.Command("git", args...)
521         tg.stdout.Reset()
522         tg.stderr.Reset()
523         cmd.Stdout = &tg.stdout
524         cmd.Stderr = &tg.stderr
525         cmd.Dir = dir
526         cmd.Env = tg.env
527         status := cmd.Run()
528         if tg.stdout.Len() > 0 {
529                 tg.t.Log("git standard output:")
530                 tg.t.Log(tg.stdout.String())
531         }
532         if tg.stderr.Len() > 0 {
533                 tg.t.Log("git standard error:")
534                 tg.t.Log(tg.stderr.String())
535         }
536         if status != nil {
537                 tg.t.Logf("git %v failed unexpectedly: %v", args, status)
538                 tg.t.FailNow()
539         }
540 }
541
542 // getStdout returns standard output of the testgo run as a string.
543 func (tg *testgoData) getStdout() string {
544         tg.t.Helper()
545         if !tg.ran {
546                 tg.t.Fatal("internal testsuite error: stdout called before run")
547         }
548         return tg.stdout.String()
549 }
550
551 // getStderr returns standard error of the testgo run as a string.
552 func (tg *testgoData) getStderr() string {
553         tg.t.Helper()
554         if !tg.ran {
555                 tg.t.Fatal("internal testsuite error: stdout called before run")
556         }
557         return tg.stderr.String()
558 }
559
560 // doGrepMatch looks for a regular expression in a buffer, and returns
561 // whether it is found. The regular expression is matched against
562 // each line separately, as with the grep command.
563 func (tg *testgoData) doGrepMatch(match string, b *bytes.Buffer) bool {
564         tg.t.Helper()
565         if !tg.ran {
566                 tg.t.Fatal("internal testsuite error: grep called before run")
567         }
568         re := regexp.MustCompile(match)
569         for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
570                 if re.Match(ln) {
571                         return true
572                 }
573         }
574         return false
575 }
576
577 // doGrep looks for a regular expression in a buffer and fails if it
578 // is not found. The name argument is the name of the output we are
579 // searching, "output" or "error". The msg argument is logged on
580 // failure.
581 func (tg *testgoData) doGrep(match string, b *bytes.Buffer, name, msg string) {
582         tg.t.Helper()
583         if !tg.doGrepMatch(match, b) {
584                 tg.t.Log(msg)
585                 tg.t.Logf("pattern %v not found in standard %s", match, name)
586                 tg.t.FailNow()
587         }
588 }
589
590 // grepStdout looks for a regular expression in the test run's
591 // standard output and fails, logging msg, if it is not found.
592 func (tg *testgoData) grepStdout(match, msg string) {
593         tg.t.Helper()
594         tg.doGrep(match, &tg.stdout, "output", msg)
595 }
596
597 // grepStderr looks for a regular expression in the test run's
598 // standard error and fails, logging msg, if it is not found.
599 func (tg *testgoData) grepStderr(match, msg string) {
600         tg.t.Helper()
601         tg.doGrep(match, &tg.stderr, "error", msg)
602 }
603
604 // grepBoth looks for a regular expression in the test run's standard
605 // output or stand error and fails, logging msg, if it is not found.
606 func (tg *testgoData) grepBoth(match, msg string) {
607         tg.t.Helper()
608         if !tg.doGrepMatch(match, &tg.stdout) && !tg.doGrepMatch(match, &tg.stderr) {
609                 tg.t.Log(msg)
610                 tg.t.Logf("pattern %v not found in standard output or standard error", match)
611                 tg.t.FailNow()
612         }
613 }
614
615 // doGrepNot looks for a regular expression in a buffer and fails if
616 // it is found. The name and msg arguments are as for doGrep.
617 func (tg *testgoData) doGrepNot(match string, b *bytes.Buffer, name, msg string) {
618         tg.t.Helper()
619         if tg.doGrepMatch(match, b) {
620                 tg.t.Log(msg)
621                 tg.t.Logf("pattern %v found unexpectedly in standard %s", match, name)
622                 tg.t.FailNow()
623         }
624 }
625
626 // grepStdoutNot looks for a regular expression in the test run's
627 // standard output and fails, logging msg, if it is found.
628 func (tg *testgoData) grepStdoutNot(match, msg string) {
629         tg.t.Helper()
630         tg.doGrepNot(match, &tg.stdout, "output", msg)
631 }
632
633 // grepStderrNot looks for a regular expression in the test run's
634 // standard error and fails, logging msg, if it is found.
635 func (tg *testgoData) grepStderrNot(match, msg string) {
636         tg.t.Helper()
637         tg.doGrepNot(match, &tg.stderr, "error", msg)
638 }
639
640 // grepBothNot looks for a regular expression in the test run's
641 // standard output or stand error and fails, logging msg, if it is
642 // found.
643 func (tg *testgoData) grepBothNot(match, msg string) {
644         tg.t.Helper()
645         if tg.doGrepMatch(match, &tg.stdout) || tg.doGrepMatch(match, &tg.stderr) {
646                 tg.t.Log(msg)
647                 tg.t.Fatalf("pattern %v found unexpectedly in standard output or standard error", match)
648         }
649 }
650
651 // doGrepCount counts the number of times a regexp is seen in a buffer.
652 func (tg *testgoData) doGrepCount(match string, b *bytes.Buffer) int {
653         tg.t.Helper()
654         if !tg.ran {
655                 tg.t.Fatal("internal testsuite error: doGrepCount called before run")
656         }
657         re := regexp.MustCompile(match)
658         c := 0
659         for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
660                 if re.Match(ln) {
661                         c++
662                 }
663         }
664         return c
665 }
666
667 // grepCountBoth returns the number of times a regexp is seen in both
668 // standard output and standard error.
669 func (tg *testgoData) grepCountBoth(match string) int {
670         tg.t.Helper()
671         return tg.doGrepCount(match, &tg.stdout) + tg.doGrepCount(match, &tg.stderr)
672 }
673
674 // creatingTemp records that the test plans to create a temporary file
675 // or directory. If the file or directory exists already, it will be
676 // removed. When the test completes, the file or directory will be
677 // removed if it exists.
678 func (tg *testgoData) creatingTemp(path string) {
679         tg.t.Helper()
680         if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) {
681                 tg.t.Fatalf("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path)
682         }
683         // If we have changed the working directory, make sure we have
684         // an absolute path, because we are going to change directory
685         // back before we remove the temporary.
686         if tg.wd != "" && !filepath.IsAbs(path) {
687                 path = filepath.Join(tg.pwd(), path)
688         }
689         tg.must(robustio.RemoveAll(path))
690         tg.temps = append(tg.temps, path)
691 }
692
693 // makeTempdir makes a temporary directory for a run of testgo. If
694 // the temporary directory was already created, this does nothing.
695 func (tg *testgoData) makeTempdir() {
696         tg.t.Helper()
697         if tg.tempdir == "" {
698                 var err error
699                 tg.tempdir, err = ioutil.TempDir("", "gotest")
700                 tg.must(err)
701         }
702 }
703
704 // tempFile adds a temporary file for a run of testgo.
705 func (tg *testgoData) tempFile(path, contents string) {
706         tg.t.Helper()
707         tg.makeTempdir()
708         tg.must(os.MkdirAll(filepath.Join(tg.tempdir, filepath.Dir(path)), 0755))
709         bytes := []byte(contents)
710         if strings.HasSuffix(path, ".go") {
711                 formatted, err := format.Source(bytes)
712                 if err == nil {
713                         bytes = formatted
714                 }
715         }
716         tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644))
717 }
718
719 // tempDir adds a temporary directory for a run of testgo.
720 func (tg *testgoData) tempDir(path string) {
721         tg.t.Helper()
722         tg.makeTempdir()
723         if err := os.MkdirAll(filepath.Join(tg.tempdir, path), 0755); err != nil && !os.IsExist(err) {
724                 tg.t.Fatal(err)
725         }
726 }
727
728 // path returns the absolute pathname to file with the temporary
729 // directory.
730 func (tg *testgoData) path(name string) string {
731         tg.t.Helper()
732         if tg.tempdir == "" {
733                 tg.t.Fatalf("internal testsuite error: path(%q) with no tempdir", name)
734         }
735         if name == "." {
736                 return tg.tempdir
737         }
738         return filepath.Join(tg.tempdir, name)
739 }
740
741 // mustExist fails if path does not exist.
742 func (tg *testgoData) mustExist(path string) {
743         tg.t.Helper()
744         if _, err := os.Stat(path); err != nil {
745                 if os.IsNotExist(err) {
746                         tg.t.Fatalf("%s does not exist but should", path)
747                 }
748                 tg.t.Fatalf("%s stat failed: %v", path, err)
749         }
750 }
751
752 // mustNotExist fails if path exists.
753 func (tg *testgoData) mustNotExist(path string) {
754         tg.t.Helper()
755         if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
756                 tg.t.Fatalf("%s exists but should not (%v)", path, err)
757         }
758 }
759
760 // mustHaveContent succeeds if filePath is a path to a file,
761 // and that file is readable and not empty.
762 func (tg *testgoData) mustHaveContent(filePath string) {
763         tg.mustExist(filePath)
764         f, err := os.Stat(filePath)
765         if err != nil {
766                 tg.t.Fatal(err)
767         }
768         if f.Size() == 0 {
769                 tg.t.Fatalf("expected %s to have data, but is empty", filePath)
770         }
771 }
772
773 // wantExecutable fails with msg if path is not executable.
774 func (tg *testgoData) wantExecutable(path, msg string) {
775         tg.t.Helper()
776         if st, err := os.Stat(path); err != nil {
777                 if !os.IsNotExist(err) {
778                         tg.t.Log(err)
779                 }
780                 tg.t.Fatal(msg)
781         } else {
782                 if runtime.GOOS != "windows" && st.Mode()&0111 == 0 {
783                         tg.t.Fatalf("binary %s exists but is not executable", path)
784                 }
785         }
786 }
787
788 // wantArchive fails if path is not an archive.
789 func (tg *testgoData) wantArchive(path string) {
790         tg.t.Helper()
791         f, err := os.Open(path)
792         if err != nil {
793                 tg.t.Fatal(err)
794         }
795         buf := make([]byte, 100)
796         io.ReadFull(f, buf)
797         f.Close()
798         if !bytes.HasPrefix(buf, []byte("!<arch>\n")) {
799                 tg.t.Fatalf("file %s exists but is not an archive", path)
800         }
801 }
802
803 // isStale reports whether pkg is stale, and why
804 func (tg *testgoData) isStale(pkg string) (bool, string) {
805         tg.t.Helper()
806         tg.run("list", "-f", "{{.Stale}}:{{.StaleReason}}", pkg)
807         v := strings.TrimSpace(tg.getStdout())
808         f := strings.SplitN(v, ":", 2)
809         if len(f) == 2 {
810                 switch f[0] {
811                 case "true":
812                         return true, f[1]
813                 case "false":
814                         return false, f[1]
815                 }
816         }
817         tg.t.Fatalf("unexpected output checking staleness of package %v: %v", pkg, v)
818         panic("unreachable")
819 }
820
821 // wantStale fails with msg if pkg is not stale.
822 func (tg *testgoData) wantStale(pkg, reason, msg string) {
823         tg.t.Helper()
824         stale, why := tg.isStale(pkg)
825         if !stale {
826                 tg.t.Fatal(msg)
827         }
828         // We always accept the reason as being "not installed but
829         // available in build cache", because when that is the case go
830         // list doesn't try to sort out the underlying reason why the
831         // package is not installed.
832         if reason == "" && why != "" || !strings.Contains(why, reason) && !strings.Contains(why, "not installed but available in build cache") {
833                 tg.t.Errorf("wrong reason for Stale=true: %q, want %q", why, reason)
834         }
835 }
836
837 // wantNotStale fails with msg if pkg is stale.
838 func (tg *testgoData) wantNotStale(pkg, reason, msg string) {
839         tg.t.Helper()
840         stale, why := tg.isStale(pkg)
841         if stale {
842                 tg.t.Fatal(msg)
843         }
844         if reason == "" && why != "" || !strings.Contains(why, reason) {
845                 tg.t.Errorf("wrong reason for Stale=false: %q, want %q", why, reason)
846         }
847 }
848
849 // If -testwork is specified, the test prints the name of the temp directory
850 // and does not remove it when done, so that a programmer can
851 // poke at the test file tree afterward.
852 var testWork = flag.Bool("testwork", false, "")
853
854 // cleanup cleans up a test that runs testgo.
855 func (tg *testgoData) cleanup() {
856         tg.t.Helper()
857         if tg.wd != "" {
858                 wd, _ := os.Getwd()
859                 tg.t.Logf("ended in %s", wd)
860
861                 if err := os.Chdir(tg.wd); err != nil {
862                         // We are unlikely to be able to continue.
863                         fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err)
864                         os.Exit(2)
865                 }
866         }
867         if *testWork {
868                 tg.t.Logf("TESTWORK=%s\n", tg.path("."))
869                 return
870         }
871         for _, path := range tg.temps {
872                 tg.check(removeAll(path))
873         }
874         if tg.tempdir != "" {
875                 tg.check(removeAll(tg.tempdir))
876         }
877 }
878
879 func removeAll(dir string) error {
880         // module cache has 0444 directories;
881         // make them writable in order to remove content.
882         filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
883                 if err != nil {
884                         return nil // ignore errors walking in file system
885                 }
886                 if info.IsDir() {
887                         os.Chmod(path, 0777)
888                 }
889                 return nil
890         })
891         return robustio.RemoveAll(dir)
892 }
893
894 // failSSH puts an ssh executable in the PATH that always fails.
895 // This is to stub out uses of ssh by go get.
896 func (tg *testgoData) failSSH() {
897         tg.t.Helper()
898         wd, err := os.Getwd()
899         if err != nil {
900                 tg.t.Fatal(err)
901         }
902         fail := filepath.Join(wd, "testdata/failssh")
903         tg.setenv("PATH", fmt.Sprintf("%v%c%v", fail, filepath.ListSeparator, os.Getenv("PATH")))
904 }
905
906 func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) {
907         if testing.Short() {
908                 t.Skip("skipping lengthy test in short mode")
909         }
910
911         tg := testgo(t)
912         defer tg.cleanup()
913
914         // Copy the runtime packages into a temporary GOROOT
915         // so that we can change files.
916         for _, copydir := range []string{
917                 "src/runtime",
918                 "src/internal/bytealg",
919                 "src/internal/cpu",
920                 "src/unsafe",
921                 filepath.Join("pkg", runtime.GOOS+"_"+runtime.GOARCH),
922                 filepath.Join("pkg/tool", runtime.GOOS+"_"+runtime.GOARCH),
923                 "pkg/include",
924         } {
925                 srcdir := filepath.Join(testGOROOT, copydir)
926                 tg.tempDir(filepath.Join("goroot", copydir))
927                 err := filepath.Walk(srcdir,
928                         func(path string, info os.FileInfo, err error) error {
929                                 if err != nil {
930                                         return err
931                                 }
932                                 if info.IsDir() {
933                                         return nil
934                                 }
935                                 srcrel, err := filepath.Rel(srcdir, path)
936                                 if err != nil {
937                                         return err
938                                 }
939                                 dest := filepath.Join("goroot", copydir, srcrel)
940                                 data, err := ioutil.ReadFile(path)
941                                 if err != nil {
942                                         return err
943                                 }
944                                 tg.tempFile(dest, string(data))
945                                 if err := os.Chmod(tg.path(dest), info.Mode()); err != nil {
946                                         return err
947                                 }
948                                 return nil
949                         })
950                 if err != nil {
951                         t.Fatal(err)
952                 }
953         }
954         tg.setenv("GOROOT", tg.path("goroot"))
955
956         addVar := func(name string, idx int) (restore func()) {
957                 data, err := ioutil.ReadFile(name)
958                 if err != nil {
959                         t.Fatal(err)
960                 }
961                 old := data
962                 data = append(data, fmt.Sprintf("var DummyUnusedVar%d bool\n", idx)...)
963                 if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil {
964                         t.Fatal(err)
965                 }
966                 tg.sleep()
967                 return func() {
968                         if err := ioutil.WriteFile(name, old, 0666); err != nil {
969                                 t.Fatal(err)
970                         }
971                 }
972         }
973
974         // Every main package depends on the "runtime".
975         tg.tempFile("d1/src/p1/p1.go", `package main; func main(){}`)
976         tg.setenv("GOPATH", tg.path("d1"))
977         // Pass -i flag to rebuild everything outdated.
978         tg.run("install", "-i", "p1")
979         tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, before any changes")
980
981         // Changing mtime of runtime/internal/sys/sys.go
982         // should have no effect: only the content matters.
983         // In fact this should be true even outside a release branch.
984         sys := tg.path("goroot/src/runtime/internal/sys/sys.go")
985         tg.sleep()
986         restore := addVar(sys, 0)
987         restore()
988         tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after updating mtime of runtime/internal/sys/sys.go")
989
990         // But changing content of any file should have an effect.
991         // Previously zversion.go was the only one that mattered;
992         // now they all matter, so keep using sys.go.
993         restore = addVar(sys, 1)
994         defer restore()
995         tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go")
996         restore()
997         tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after changing back to old release")
998         addVar(sys, 2)
999         tg.wantStale("p1", "stale dependency: runtime", "./testgo list claims p1 is NOT stale, incorrectly, after changing sys.go again")
1000         tg.run("install", "-i", "p1")
1001         tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with new release")
1002
1003         // Restore to "old" release.
1004         restore()
1005         tg.wantStale("p1", "stale dependency: runtime/internal/sys", "./testgo list claims p1 is NOT stale, incorrectly, after restoring sys.go")
1006         tg.run("install", "-i", "p1")
1007         tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release")
1008 }
1009
1010 func testLocalRun(tg *testgoData, exepath, local, match string) {
1011         tg.t.Helper()
1012         out, err := exec.Command(exepath).Output()
1013         if err != nil {
1014                 tg.t.Fatalf("error running %v: %v", exepath, err)
1015         }
1016         if !regexp.MustCompile(match).Match(out) {
1017                 tg.t.Log(string(out))
1018                 tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local)
1019         }
1020 }
1021
1022 func testLocalEasy(tg *testgoData, local string) {
1023         tg.t.Helper()
1024         exepath := "./easy" + exeSuffix
1025         tg.creatingTemp(exepath)
1026         tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go"))
1027         testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1028 }
1029
1030 func testLocalEasySub(tg *testgoData, local string) {
1031         tg.t.Helper()
1032         exepath := "./easysub" + exeSuffix
1033         tg.creatingTemp(exepath)
1034         tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go"))
1035         testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
1036 }
1037
1038 func testLocalHard(tg *testgoData, local string) {
1039         tg.t.Helper()
1040         exepath := "./hard" + exeSuffix
1041         tg.creatingTemp(exepath)
1042         tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go"))
1043         testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`)
1044 }
1045
1046 func testLocalInstall(tg *testgoData, local string) {
1047         tg.t.Helper()
1048         tg.runFail("install", filepath.Join("testdata", local, "easy.go"))
1049 }
1050
1051 func TestLocalImportsEasy(t *testing.T) {
1052         tg := testgo(t)
1053         defer tg.cleanup()
1054         testLocalEasy(tg, "local")
1055 }
1056
1057 func TestLocalImportsEasySub(t *testing.T) {
1058         tg := testgo(t)
1059         defer tg.cleanup()
1060         testLocalEasySub(tg, "local")
1061 }
1062
1063 func TestLocalImportsHard(t *testing.T) {
1064         tg := testgo(t)
1065         defer tg.cleanup()
1066         testLocalHard(tg, "local")
1067 }
1068
1069 func TestLocalImportsGoInstallShouldFail(t *testing.T) {
1070         tg := testgo(t)
1071         defer tg.cleanup()
1072         testLocalInstall(tg, "local")
1073 }
1074
1075 const badDirName = `#$%:, &()*;<=>?\^{}`
1076
1077 func copyBad(tg *testgoData) {
1078         tg.t.Helper()
1079         if runtime.GOOS == "windows" {
1080                 tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName)
1081         }
1082
1083         tg.must(filepath.Walk("testdata/local",
1084                 func(path string, info os.FileInfo, err error) error {
1085                         if err != nil {
1086                                 return err
1087                         }
1088                         if info.IsDir() {
1089                                 return nil
1090                         }
1091                         var data []byte
1092                         data, err = ioutil.ReadFile(path)
1093                         if err != nil {
1094                                 return err
1095                         }
1096                         newpath := strings.Replace(path, "local", badDirName, 1)
1097                         tg.tempFile(newpath, string(data))
1098                         return nil
1099                 }))
1100         tg.cd(tg.path("."))
1101 }
1102
1103 func TestBadImportsEasy(t *testing.T) {
1104         tg := testgo(t)
1105         defer tg.cleanup()
1106         // TODO: tg.parallel()
1107         copyBad(tg)
1108         testLocalEasy(tg, badDirName)
1109 }
1110
1111 func TestBadImportsEasySub(t *testing.T) {
1112         tg := testgo(t)
1113         defer tg.cleanup()
1114         copyBad(tg)
1115         testLocalEasySub(tg, badDirName)
1116 }
1117
1118 func TestBadImportsHard(t *testing.T) {
1119         tg := testgo(t)
1120         defer tg.cleanup()
1121         copyBad(tg)
1122         testLocalHard(tg, badDirName)
1123 }
1124
1125 func TestBadImportsGoInstallShouldFail(t *testing.T) {
1126         tg := testgo(t)
1127         defer tg.cleanup()
1128         copyBad(tg)
1129         testLocalInstall(tg, badDirName)
1130 }
1131
1132 func TestInternalPackagesInGOROOTAreRespected(t *testing.T) {
1133         skipIfGccgo(t, "gccgo does not have GOROOT")
1134         tg := testgo(t)
1135         defer tg.cleanup()
1136         tg.runFail("build", "-v", "./testdata/testinternal")
1137         tg.grepBoth(`testinternal(\/|\\)p\.go\:3\:8\: use of internal package net/http/internal not allowed`, "wrong error message for testdata/testinternal")
1138 }
1139
1140 func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) {
1141         tg := testgo(t)
1142         defer tg.cleanup()
1143         tg.runFail("build", "-v", "./testdata/testinternal2")
1144         tg.grepBoth(`testinternal2(\/|\\)p\.go\:3\:8\: use of internal package .*internal/w not allowed`, "wrote error message for testdata/testinternal2")
1145 }
1146
1147 func TestRunInternal(t *testing.T) {
1148         tg := testgo(t)
1149         defer tg.cleanup()
1150         dir := filepath.Join(tg.pwd(), "testdata")
1151         tg.setenv("GOPATH", dir)
1152         tg.run("run", filepath.Join(dir, "src/run/good.go"))
1153         tg.runFail("run", filepath.Join(dir, "src/run/bad.go"))
1154         tg.grepStderr(`testdata(\/|\\)src(\/|\\)run(\/|\\)bad\.go\:3\:8\: use of internal package run/subdir/internal/private not allowed`, "unexpected error for run/bad.go")
1155 }
1156
1157 func TestRunPkg(t *testing.T) {
1158         tg := testgo(t)
1159         defer tg.cleanup()
1160         dir := filepath.Join(tg.pwd(), "testdata")
1161         tg.setenv("GOPATH", dir)
1162         tg.run("run", "hello")
1163         tg.grepStderr("hello, world", "did not find hello, world")
1164         tg.cd(filepath.Join(dir, "src/hello"))
1165         tg.run("run", ".")
1166         tg.grepStderr("hello, world", "did not find hello, world")
1167 }
1168
1169 func testMove(t *testing.T, vcs, url, base, config string) {
1170         testenv.MustHaveExternalNetwork(t)
1171
1172         tg := testgo(t)
1173         defer tg.cleanup()
1174         tg.parallel()
1175         tg.tempDir("src")
1176         tg.must(os.Mkdir(tg.path(".hg"), 0700))
1177         tg.must(ioutil.WriteFile(filepath.Join(tg.path(".hg"), "hgrc"), nil, 0600))
1178         tg.setenv("GOPATH", tg.path("."))
1179         tg.run("get", "-d", url)
1180         tg.run("get", "-d", "-u", url)
1181         switch vcs {
1182         case "svn":
1183                 // SVN doesn't believe in text files so we can't just edit the config.
1184                 // Check out a different repo into the wrong place.
1185                 tg.must(robustio.RemoveAll(tg.path("src/code.google.com/p/rsc-svn")))
1186                 tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk")
1187                 tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn")))
1188         default:
1189                 path := tg.path(filepath.Join("src", config))
1190                 data, err := ioutil.ReadFile(path)
1191                 tg.must(err)
1192                 data = bytes.ReplaceAll(data, []byte(base), []byte(base+"XXX"))
1193                 tg.must(ioutil.WriteFile(path, data, 0644))
1194         }
1195         if vcs == "git" {
1196                 // git will ask for a username and password when we
1197                 // run go get -d -f -u. An empty username and
1198                 // password will work. Prevent asking by setting
1199                 // GIT_ASKPASS.
1200                 tg.creatingTemp("sink" + exeSuffix)
1201                 tg.tempFile("src/sink/sink.go", `package main; func main() {}`)
1202                 tg.run("build", "-o", "sink"+exeSuffix, "sink")
1203                 tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix))
1204         }
1205         tg.runFail("get", "-d", "-u", url)
1206         tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason")
1207         tg.runFail("get", "-d", "-f", "-u", url)
1208         tg.grepStderr("validating server certificate|[nN]ot [fF]ound", "go get -d -f -u "+url+" failed for wrong reason")
1209 }
1210
1211 func TestInternalPackageErrorsAreHandled(t *testing.T) {
1212         tg := testgo(t)
1213         defer tg.cleanup()
1214         tg.run("list", "./testdata/testinternal3")
1215 }
1216
1217 func TestInternalCache(t *testing.T) {
1218         tg := testgo(t)
1219         defer tg.cleanup()
1220         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4"))
1221         tg.runFail("build", "p")
1222         tg.grepStderr("internal", "did not fail to build p")
1223 }
1224
1225 func TestMoveGit(t *testing.T) {
1226         testenv.MustHaveExecPath(t, "git")
1227         testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config")
1228 }
1229
1230 func TestMoveHG(t *testing.T) {
1231         testenv.MustHaveExecPath(t, "hg")
1232         testMove(t, "hg", "vcs-test.golang.org/go/custom-hg-hello", "custom-hg-hello", "vcs-test.golang.org/go/custom-hg-hello/.hg/hgrc")
1233 }
1234
1235 // TODO(rsc): Set up a test case on SourceForge (?) for svn.
1236 // func testMoveSVN(t *testing.T) {
1237 //      testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-")
1238 // }
1239
1240 func TestImportCommandMatch(t *testing.T) {
1241         tg := testgo(t)
1242         defer tg.cleanup()
1243         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1244         tg.run("build", "./testdata/importcom/works.go")
1245 }
1246
1247 func TestImportCommentMismatch(t *testing.T) {
1248         tg := testgo(t)
1249         defer tg.cleanup()
1250         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1251         tg.runFail("build", "./testdata/importcom/wrongplace.go")
1252         tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import")
1253 }
1254
1255 func TestImportCommentSyntaxError(t *testing.T) {
1256         tg := testgo(t)
1257         defer tg.cleanup()
1258         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1259         tg.runFail("build", "./testdata/importcom/bad.go")
1260         tg.grepStderr("cannot parse import comment", "go build did not mention syntax error")
1261 }
1262
1263 func TestImportCommentConflict(t *testing.T) {
1264         tg := testgo(t)
1265         defer tg.cleanup()
1266         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
1267         tg.runFail("build", "./testdata/importcom/conflict.go")
1268         tg.grepStderr("found import comments", "go build did not mention comment conflict")
1269 }
1270
1271 func TestImportCycle(t *testing.T) {
1272         tg := testgo(t)
1273         defer tg.cleanup()
1274         tg.parallel()
1275         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcycle"))
1276         tg.runFail("build", "selfimport")
1277
1278         count := tg.grepCountBoth("import cycle not allowed")
1279         if count == 0 {
1280                 t.Fatal("go build did not mention cyclical import")
1281         }
1282         if count > 1 {
1283                 t.Fatal("go build mentioned import cycle more than once")
1284         }
1285
1286         // Don't hang forever.
1287         tg.run("list", "-e", "-json", "selfimport")
1288 }
1289
1290 // cmd/go: custom import path checking should not apply to Go packages without import comment.
1291 func TestIssue10952(t *testing.T) {
1292         testenv.MustHaveExternalNetwork(t)
1293         testenv.MustHaveExecPath(t, "git")
1294
1295         tg := testgo(t)
1296         defer tg.cleanup()
1297         tg.parallel()
1298         tg.tempDir("src")
1299         tg.setenv("GOPATH", tg.path("."))
1300         const importPath = "github.com/zombiezen/go-get-issue-10952"
1301         tg.run("get", "-d", "-u", importPath)
1302         repoDir := tg.path("src/" + importPath)
1303         tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git")
1304         tg.run("get", "-d", "-u", importPath)
1305 }
1306
1307 func TestIssue16471(t *testing.T) {
1308         testenv.MustHaveExternalNetwork(t)
1309         testenv.MustHaveExecPath(t, "git")
1310
1311         tg := testgo(t)
1312         defer tg.cleanup()
1313         tg.parallel()
1314         tg.tempDir("src")
1315         tg.setenv("GOPATH", tg.path("."))
1316         tg.must(os.MkdirAll(tg.path("src/rsc.io/go-get-issue-10952"), 0755))
1317         tg.runGit(tg.path("src/rsc.io"), "clone", "https://github.com/zombiezen/go-get-issue-10952")
1318         tg.runFail("get", "-u", "rsc.io/go-get-issue-10952")
1319         tg.grepStderr("rsc.io/go-get-issue-10952 is a custom import path for https://github.com/rsc/go-get-issue-10952, but .* is checked out from https://github.com/zombiezen/go-get-issue-10952", "did not detect updated import path")
1320 }
1321
1322 // Test git clone URL that uses SCP-like syntax and custom import path checking.
1323 func TestIssue11457(t *testing.T) {
1324         testenv.MustHaveExternalNetwork(t)
1325         testenv.MustHaveExecPath(t, "git")
1326
1327         tg := testgo(t)
1328         defer tg.cleanup()
1329         tg.parallel()
1330         tg.tempDir("src")
1331         tg.setenv("GOPATH", tg.path("."))
1332         const importPath = "rsc.io/go-get-issue-11457"
1333         tg.run("get", "-d", "-u", importPath)
1334         repoDir := tg.path("src/" + importPath)
1335         tg.runGit(repoDir, "remote", "set-url", "origin", "git@github.com:rsc/go-get-issue-11457")
1336
1337         // At this time, custom import path checking compares remotes verbatim (rather than
1338         // just the host and path, skipping scheme and user), so we expect go get -u to fail.
1339         // However, the goal of this test is to verify that gitRemoteRepo correctly parsed
1340         // the SCP-like syntax, and we expect it to appear in the error message.
1341         tg.runFail("get", "-d", "-u", importPath)
1342         want := " is checked out from ssh://git@github.com/rsc/go-get-issue-11457"
1343         if !strings.HasSuffix(strings.TrimSpace(tg.getStderr()), want) {
1344                 t.Error("expected clone URL to appear in stderr")
1345         }
1346 }
1347
1348 func TestGetGitDefaultBranch(t *testing.T) {
1349         testenv.MustHaveExternalNetwork(t)
1350         testenv.MustHaveExecPath(t, "git")
1351
1352         tg := testgo(t)
1353         defer tg.cleanup()
1354         tg.parallel()
1355         tg.tempDir("src")
1356         tg.setenv("GOPATH", tg.path("."))
1357
1358         // This repo has two branches, master and another-branch.
1359         // The another-branch is the default that you get from 'git clone'.
1360         // The go get command variants should not override this.
1361         const importPath = "github.com/rsc/go-get-default-branch"
1362
1363         tg.run("get", "-d", importPath)
1364         repoDir := tg.path("src/" + importPath)
1365         tg.runGit(repoDir, "branch", "--contains", "HEAD")
1366         tg.grepStdout(`\* another-branch`, "not on correct default branch")
1367
1368         tg.run("get", "-d", "-u", importPath)
1369         tg.runGit(repoDir, "branch", "--contains", "HEAD")
1370         tg.grepStdout(`\* another-branch`, "not on correct default branch")
1371 }
1372
1373 // Security issue. Don't disable. See golang.org/issue/22125.
1374 func TestAccidentalGitCheckout(t *testing.T) {
1375         testenv.MustHaveExternalNetwork(t)
1376         testenv.MustHaveExecPath(t, "git")
1377
1378         tg := testgo(t)
1379         defer tg.cleanup()
1380         tg.parallel()
1381         tg.tempDir("src")
1382
1383         tg.setenv("GOPATH", tg.path("."))
1384
1385         tg.runFail("get", "-u", "vcs-test.golang.org/go/test1-svn-git")
1386         tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1387
1388         if _, err := os.Stat(tg.path("SrC")); err == nil {
1389                 // This case only triggers on a case-insensitive file system.
1390                 tg.runFail("get", "-u", "vcs-test.golang.org/go/test2-svn-git/test2main")
1391                 tg.grepStderr("src[\\\\/]vcs-test.* uses git, but parent .*src[\\\\/]vcs-test.* uses svn", "get did not fail for right reason")
1392         }
1393 }
1394
1395 func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) {
1396         tg := testgo(t)
1397         defer tg.cleanup()
1398         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1399         tg.runFail("test", "syntaxerror")
1400         tg.grepStderr("x_test.go:", "did not diagnose error")
1401         tg.grepStdout("FAIL", "go test did not say FAIL")
1402 }
1403
1404 func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) {
1405         tg := testgo(t)
1406         defer tg.cleanup()
1407         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1408         tg.runFail("list", "...")
1409         tg.grepBoth("badpkg", "go list ... failure does not mention badpkg")
1410         tg.run("list", "m...")
1411 }
1412
1413 func TestRelativeImportsGoTest(t *testing.T) {
1414         tg := testgo(t)
1415         defer tg.cleanup()
1416         tg.run("test", "./testdata/testimport")
1417 }
1418
1419 func TestRelativeImportsGoTestDashI(t *testing.T) {
1420         tg := testgo(t)
1421         defer tg.cleanup()
1422
1423         // don't let test -i overwrite runtime
1424         tg.wantNotStale("runtime", "", "must be non-stale before test -i")
1425
1426         tg.run("test", "-i", "./testdata/testimport")
1427 }
1428
1429 func TestRelativeImportsInCommandLinePackage(t *testing.T) {
1430         tg := testgo(t)
1431         defer tg.cleanup()
1432         // TODO: tg.parallel()
1433         files, err := filepath.Glob("./testdata/testimport/*.go")
1434         tg.must(err)
1435         tg.run(append([]string{"test"}, files...)...)
1436 }
1437
1438 func TestNonCanonicalImportPaths(t *testing.T) {
1439         tg := testgo(t)
1440         defer tg.cleanup()
1441         tg.parallel()
1442         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1443         tg.runFail("build", "canonical/d")
1444         tg.grepStderr("package canonical/d", "did not report canonical/d")
1445         tg.grepStderr("imports canonical/b", "did not report canonical/b")
1446         tg.grepStderr("imports canonical/a/: non-canonical", "did not report canonical/a/")
1447 }
1448
1449 func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) {
1450         tg := testgo(t)
1451         defer tg.cleanup()
1452         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1"))
1453         tg.runFail("get", "-u", "foo")
1454
1455         // TODO(iant): We should not have to use strconv.Quote here.
1456         // The code in vcs.go should be changed so that it is not required.
1457         quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo"))
1458         quoted = quoted[1 : len(quoted)-1]
1459
1460         tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo")
1461 }
1462
1463 func TestInstallFailsWithNoBuildableFiles(t *testing.T) {
1464         tg := testgo(t)
1465         defer tg.cleanup()
1466         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1467         tg.setenv("CGO_ENABLED", "0")
1468         tg.runFail("install", "cgotest")
1469         tg.grepStderr("build constraints exclude all Go files", "go install cgotest did not report 'build constraints exclude all Go files'")
1470 }
1471
1472 // Issue 21895
1473 func TestMSanAndRaceRequireCgo(t *testing.T) {
1474         if !canMSan && !canRace {
1475                 t.Skip("skipping because both msan and the race detector are not supported")
1476         }
1477
1478         tg := testgo(t)
1479         defer tg.cleanup()
1480         tg.tempFile("triv.go", `package main; func main() {}`)
1481         tg.setenv("CGO_ENABLED", "0")
1482         if canRace {
1483                 tg.runFail("install", "-race", "triv.go")
1484                 tg.grepStderr("-race requires cgo", "did not correctly report that -race requires cgo")
1485                 tg.grepStderrNot("-msan", "reported that -msan instead of -race requires cgo")
1486         }
1487         if canMSan {
1488                 tg.runFail("install", "-msan", "triv.go")
1489                 tg.grepStderr("-msan requires cgo", "did not correctly report that -msan requires cgo")
1490                 tg.grepStderrNot("-race", "reported that -race instead of -msan requires cgo")
1491         }
1492 }
1493
1494 func TestRelativeGOBINFail(t *testing.T) {
1495         tg := testgo(t)
1496         defer tg.cleanup()
1497         tg.tempFile("triv.go", `package main; func main() {}`)
1498         tg.setenv("GOBIN", ".")
1499         tg.cd(tg.path("."))
1500         tg.runFail("install")
1501         tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path")
1502 }
1503
1504 // Test that without $GOBIN set, binaries get installed
1505 // into the GOPATH bin directory.
1506 func TestInstallIntoGOPATH(t *testing.T) {
1507         tg := testgo(t)
1508         defer tg.cleanup()
1509         tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1510         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1511         tg.run("install", "go-cmd-test")
1512         tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1513 }
1514
1515 // Issue 12407
1516 func TestBuildOutputToDevNull(t *testing.T) {
1517         tg := testgo(t)
1518         defer tg.cleanup()
1519         fi1, err1 := os.Lstat(os.DevNull)
1520         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1521         tg.run("build", "-o", os.DevNull, "go-cmd-test")
1522         fi2, err2 := os.Lstat(os.DevNull)
1523         if err1 == nil {
1524                 if err2 != nil {
1525                         t.Errorf("second stat of /dev/null failed: %v", err2)
1526                 } else if !os.SameFile(fi1, fi2) {
1527                         t.Errorf("/dev/null changed: now %v was %v", fi1, fi2)
1528                 }
1529         }
1530 }
1531
1532 // Issue 28549.
1533 func TestTestOutputToDevNull(t *testing.T) {
1534         tg := testgo(t)
1535         defer tg.cleanup()
1536         fi1, err1 := os.Lstat(os.DevNull)
1537         tg.makeTempdir()
1538         tg.setenv("GOPATH", tg.path("."))
1539         tg.tempFile("src/p/p.go", "package p\n")
1540         tg.tempFile("src/p/p_test.go", "package p\nimport \"testing\"\nfunc TestX(t *testing.T) {}\n")
1541         tg.run("test", "-o", os.DevNull, "-c", "p")
1542         tg.mustNotExist("p.test")
1543         fi2, err2 := os.Lstat(os.DevNull)
1544         if err1 == nil {
1545                 if err2 != nil {
1546                         t.Errorf("second stat of /dev/null failed: %v", err2)
1547                 } else if !os.SameFile(fi1, fi2) {
1548                         t.Errorf("/dev/null changed: now %v was %v", fi1, fi2)
1549                 }
1550         }
1551 }
1552
1553 func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) {
1554         tooSlow(t)
1555         tg := testgo(t)
1556         defer tg.cleanup()
1557         tg.parallel()
1558         gobin := filepath.Join(tg.pwd(), "testdata", "bin")
1559         tg.creatingTemp(gobin)
1560         tg.setenv("GOBIN", gobin)
1561         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1562         tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now()))
1563         tg.sleep()
1564         tg.run("test", "main_test")
1565         tg.run("install", "main_test")
1566         tg.wantNotStale("main_test", "", "after go install, main listed as stale")
1567         tg.run("test", "main_test")
1568 }
1569
1570 func TestPackageMainTestCompilerFlags(t *testing.T) {
1571         tg := testgo(t)
1572         defer tg.cleanup()
1573         tg.parallel()
1574         tg.makeTempdir()
1575         tg.setenv("GOPATH", tg.path("."))
1576         tg.tempFile("src/p1/p1.go", "package main\n")
1577         tg.tempFile("src/p1/p1_test.go", "package main\nimport \"testing\"\nfunc Test(t *testing.T){}\n")
1578         tg.run("test", "-c", "-n", "p1")
1579         tg.grepBothNot(`([\\/]compile|gccgo).* (-p main|-fgo-pkgpath=main).*p1\.go`, "should not have run compile -p main p1.go")
1580         tg.grepStderr(`([\\/]compile|gccgo).* (-p p1|-fgo-pkgpath=p1).*p1\.go`, "should have run compile -p p1 p1.go")
1581 }
1582
1583 // Issue 12690
1584 func TestPackageNotStaleWithTrailingSlash(t *testing.T) {
1585         skipIfGccgo(t, "gccgo does not have GOROOT")
1586         tg := testgo(t)
1587         defer tg.cleanup()
1588
1589         // Make sure the packages below are not stale.
1590         tg.wantNotStale("runtime", "", "must be non-stale before test runs")
1591         tg.wantNotStale("os", "", "must be non-stale before test runs")
1592         tg.wantNotStale("io", "", "must be non-stale before test runs")
1593
1594         goroot := runtime.GOROOT()
1595         tg.setenv("GOROOT", goroot+"/")
1596
1597         tg.wantNotStale("runtime", "", "with trailing slash in GOROOT, runtime listed as stale")
1598         tg.wantNotStale("os", "", "with trailing slash in GOROOT, os listed as stale")
1599         tg.wantNotStale("io", "", "with trailing slash in GOROOT, io listed as stale")
1600 }
1601
1602 // With $GOBIN set, binaries get installed to $GOBIN.
1603 func TestInstallIntoGOBIN(t *testing.T) {
1604         tg := testgo(t)
1605         defer tg.cleanup()
1606         gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1607         tg.creatingTemp(gobin)
1608         tg.setenv("GOBIN", gobin)
1609         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1610         tg.run("install", "go-cmd-test")
1611         tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test")
1612 }
1613
1614 // Issue 11065
1615 func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) {
1616         tg := testgo(t)
1617         defer tg.cleanup()
1618         pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test")
1619         tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix))
1620         tg.setenv("GOBIN", pkg)
1621         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1622         tg.cd(pkg)
1623         tg.run("install")
1624         tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory")
1625 }
1626
1627 // Without $GOBIN set, installing a program outside $GOPATH should fail
1628 // (there is nowhere to install it).
1629 func TestInstallWithoutDestinationFails(t *testing.T) {
1630         tg := testgo(t)
1631         defer tg.cleanup()
1632         tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go")
1633         tg.grepStderr("no install location for .go files listed on command line", "wrong error")
1634 }
1635
1636 // With $GOBIN set, should install there.
1637 func TestInstallToGOBINCommandLinePackage(t *testing.T) {
1638         tg := testgo(t)
1639         defer tg.cleanup()
1640         gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
1641         tg.creatingTemp(gobin)
1642         tg.setenv("GOBIN", gobin)
1643         tg.run("install", "testdata/src/go-cmd-test/helloworld.go")
1644         tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld")
1645 }
1646
1647 func TestGoGetNonPkg(t *testing.T) {
1648         testenv.MustHaveExternalNetwork(t)
1649         testenv.MustHaveExecPath(t, "git")
1650
1651         tg := testgo(t)
1652         defer tg.cleanup()
1653         tg.tempDir("gobin")
1654         tg.setenv("GOPATH", tg.path("."))
1655         tg.setenv("GOBIN", tg.path("gobin"))
1656         tg.runFail("get", "-d", "golang.org/x/tools")
1657         tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1658         tg.runFail("get", "-d", "-u", "golang.org/x/tools")
1659         tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1660         tg.runFail("get", "-d", "golang.org/x/tools")
1661         tg.grepStderr("golang.org/x/tools: no Go files", "missing error")
1662 }
1663
1664 func TestGoGetTestOnlyPkg(t *testing.T) {
1665         testenv.MustHaveExternalNetwork(t)
1666         testenv.MustHaveExecPath(t, "git")
1667
1668         tg := testgo(t)
1669         defer tg.cleanup()
1670         tg.tempDir("gopath")
1671         tg.setenv("GOPATH", tg.path("gopath"))
1672         tg.run("get", "golang.org/x/tour/content...")
1673         tg.run("get", "-t", "golang.org/x/tour/content...")
1674 }
1675
1676 func TestInstalls(t *testing.T) {
1677         if testing.Short() {
1678                 t.Skip("don't install into GOROOT in short mode")
1679         }
1680
1681         tg := testgo(t)
1682         defer tg.cleanup()
1683         tg.parallel()
1684         tg.tempDir("gobin")
1685         tg.setenv("GOPATH", tg.path("."))
1686         goroot := runtime.GOROOT()
1687         tg.setenv("GOROOT", goroot)
1688
1689         // cmd/fix installs into tool
1690         tg.run("env", "GOOS")
1691         goos := strings.TrimSpace(tg.getStdout())
1692         tg.setenv("GOOS", goos)
1693         tg.run("env", "GOARCH")
1694         goarch := strings.TrimSpace(tg.getStdout())
1695         tg.setenv("GOARCH", goarch)
1696         fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix
1697         tg.must(robustio.RemoveAll(fixbin))
1698         tg.run("install", "cmd/fix")
1699         tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool")
1700         tg.must(os.Remove(fixbin))
1701         tg.setenv("GOBIN", tg.path("gobin"))
1702         tg.run("install", "cmd/fix")
1703         tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set")
1704         tg.unsetenv("GOBIN")
1705
1706         // gopath program installs into GOBIN
1707         tg.tempFile("src/progname/p.go", `package main; func main() {}`)
1708         tg.setenv("GOBIN", tg.path("gobin"))
1709         tg.run("install", "progname")
1710         tg.unsetenv("GOBIN")
1711         tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname")
1712
1713         // gopath program installs into GOPATH/bin
1714         tg.run("install", "progname")
1715         tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname")
1716 }
1717
1718 func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) {
1719         tg := testgo(t)
1720         defer tg.cleanup()
1721         tg.setenv("GOPATH", ".")
1722         tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1723         tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1724 }
1725
1726 func TestRejectRelativePathsInGOPATH(t *testing.T) {
1727         tg := testgo(t)
1728         defer tg.cleanup()
1729         sep := string(filepath.ListSeparator)
1730         tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".")
1731         tg.runFail("build", "go-cmd-test")
1732         tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1733 }
1734
1735 func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) {
1736         tg := testgo(t)
1737         defer tg.cleanup()
1738         tg.setenv("GOPATH", "testdata")
1739         tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
1740         tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1741 }
1742
1743 // Issue 21928.
1744 func TestRejectBlankPathsInGOPATH(t *testing.T) {
1745         tg := testgo(t)
1746         defer tg.cleanup()
1747         sep := string(filepath.ListSeparator)
1748         tg.setenv("GOPATH", " "+sep+filepath.Join(tg.pwd(), "testdata"))
1749         tg.runFail("build", "go-cmd-test")
1750         tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
1751 }
1752
1753 // Issue 21928.
1754 func TestIgnoreEmptyPathsInGOPATH(t *testing.T) {
1755         tg := testgo(t)
1756         defer tg.cleanup()
1757         tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
1758         sep := string(filepath.ListSeparator)
1759         tg.setenv("GOPATH", ""+sep+filepath.Join(tg.pwd(), "testdata"))
1760         tg.run("install", "go-cmd-test")
1761         tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
1762 }
1763
1764 // Issue 4104.
1765 func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
1766         tooSlow(t)
1767         tg := testgo(t)
1768         defer tg.cleanup()
1769         tg.parallel()
1770         tg.run("test", "errors", "errors", "errors", "errors", "errors")
1771         if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") {
1772                 t.Error("go test errors errors errors errors errors tested the same package multiple times")
1773         }
1774 }
1775
1776 func TestGoListHasAConsistentOrder(t *testing.T) {
1777         tooSlow(t)
1778         tg := testgo(t)
1779         defer tg.cleanup()
1780         tg.parallel()
1781         tg.run("list", "std")
1782         first := tg.getStdout()
1783         tg.run("list", "std")
1784         if first != tg.getStdout() {
1785                 t.Error("go list std ordering is inconsistent")
1786         }
1787 }
1788
1789 func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
1790         tooSlow(t)
1791         tg := testgo(t)
1792         defer tg.cleanup()
1793         tg.parallel()
1794         tg.run("list", "std")
1795         tg.grepStdoutNot("cmd/", "go list std shows commands")
1796 }
1797
1798 func TestGoListCmdOnlyShowsCommands(t *testing.T) {
1799         skipIfGccgo(t, "gccgo does not have GOROOT")
1800         tooSlow(t)
1801         tg := testgo(t)
1802         defer tg.cleanup()
1803         tg.parallel()
1804         tg.run("list", "cmd")
1805         out := strings.TrimSpace(tg.getStdout())
1806         for _, line := range strings.Split(out, "\n") {
1807                 if !strings.Contains(line, "cmd/") {
1808                         t.Error("go list cmd shows non-commands")
1809                         break
1810                 }
1811         }
1812 }
1813
1814 func TestGoListDedupsPackages(t *testing.T) {
1815         tg := testgo(t)
1816         defer tg.cleanup()
1817         // TODO: tg.parallel()
1818         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
1819         tg.run("list", "xtestonly", "./testdata/src/xtestonly/...")
1820         got := strings.TrimSpace(tg.getStdout())
1821         const want = "xtestonly"
1822         if got != want {
1823                 t.Errorf("got %q; want %q", got, want)
1824         }
1825 }
1826
1827 func TestGoListDeps(t *testing.T) {
1828         tg := testgo(t)
1829         defer tg.cleanup()
1830         tg.parallel()
1831         tg.tempDir("src/p1/p2/p3/p4")
1832         tg.setenv("GOPATH", tg.path("."))
1833         tg.tempFile("src/p1/p.go", "package p1\nimport _ \"p1/p2\"\n")
1834         tg.tempFile("src/p1/p2/p.go", "package p2\nimport _ \"p1/p2/p3\"\n")
1835         tg.tempFile("src/p1/p2/p3/p.go", "package p3\nimport _ \"p1/p2/p3/p4\"\n")
1836         tg.tempFile("src/p1/p2/p3/p4/p.go", "package p4\n")
1837         tg.run("list", "-f", "{{.Deps}}", "p1")
1838         tg.grepStdout("p1/p2/p3/p4", "Deps(p1) does not mention p4")
1839
1840         tg.run("list", "-deps", "p1")
1841         tg.grepStdout("p1/p2/p3/p4", "-deps p1 does not mention p4")
1842
1843         if runtime.Compiler != "gccgo" {
1844                 // Check the list is in dependency order.
1845                 tg.run("list", "-deps", "math")
1846                 want := "internal/cpu\nunsafe\nmath/bits\nmath\n"
1847                 out := tg.stdout.String()
1848                 if !strings.Contains(out, "internal/cpu") {
1849                         // Some systems don't use internal/cpu.
1850                         want = "unsafe\nmath/bits\nmath\n"
1851                 }
1852                 if tg.stdout.String() != want {
1853                         t.Fatalf("list -deps math: wrong order\nhave %q\nwant %q", tg.stdout.String(), want)
1854                 }
1855         }
1856 }
1857
1858 func TestGoListTest(t *testing.T) {
1859         skipIfGccgo(t, "gccgo does not have standard packages")
1860         tg := testgo(t)
1861         defer tg.cleanup()
1862         tg.parallel()
1863         tg.makeTempdir()
1864         tg.setenv("GOCACHE", tg.tempdir)
1865
1866         tg.run("list", "-test", "-deps", "sort")
1867         tg.grepStdout(`^sort.test$`, "missing test main")
1868         tg.grepStdout(`^sort$`, "missing real sort")
1869         tg.grepStdout(`^sort \[sort.test\]$`, "missing test copy of sort")
1870         tg.grepStdout(`^testing \[sort.test\]$`, "missing test copy of testing")
1871         tg.grepStdoutNot(`^testing$`, "unexpected real copy of testing")
1872
1873         tg.run("list", "-test", "sort")
1874         tg.grepStdout(`^sort.test$`, "missing test main")
1875         tg.grepStdout(`^sort$`, "missing real sort")
1876         tg.grepStdout(`^sort \[sort.test\]$`, "unexpected test copy of sort")
1877         tg.grepStdoutNot(`^testing \[sort.test\]$`, "unexpected test copy of testing")
1878         tg.grepStdoutNot(`^testing$`, "unexpected real copy of testing")
1879
1880         tg.run("list", "-test", "cmd/dist", "cmd/doc")
1881         tg.grepStdout(`^cmd/dist$`, "missing cmd/dist")
1882         tg.grepStdout(`^cmd/doc$`, "missing cmd/doc")
1883         tg.grepStdout(`^cmd/doc\.test$`, "missing cmd/doc test")
1884         tg.grepStdoutNot(`^cmd/dist\.test$`, "unexpected cmd/dist test")
1885         tg.grepStdoutNot(`^testing`, "unexpected testing")
1886
1887         tg.run("list", "-test", "runtime/cgo")
1888         tg.grepStdout(`^runtime/cgo$`, "missing runtime/cgo")
1889
1890         tg.run("list", "-deps", "-f", "{{if .DepOnly}}{{.ImportPath}}{{end}}", "sort")
1891         tg.grepStdout(`^internal/reflectlite$`, "missing internal/reflectlite")
1892         tg.grepStdoutNot(`^sort`, "unexpected sort")
1893 }
1894
1895 func TestGoListCompiledCgo(t *testing.T) {
1896         tooSlow(t)
1897         tg := testgo(t)
1898         defer tg.cleanup()
1899         tg.parallel()
1900         tg.makeTempdir()
1901         tg.setenv("GOCACHE", tg.tempdir)
1902
1903         tg.run("list", "-f", `{{join .CgoFiles "\n"}}`, "net")
1904         if tg.stdout.String() == "" {
1905                 t.Skip("net does not use cgo")
1906         }
1907         if strings.Contains(tg.stdout.String(), tg.tempdir) {
1908                 t.Fatalf(".CgoFiles unexpectedly mentioned cache %s", tg.tempdir)
1909         }
1910         tg.run("list", "-compiled", "-f", `{{.Dir}}{{"\n"}}{{join .CompiledGoFiles "\n"}}`, "net")
1911         if !strings.Contains(tg.stdout.String(), tg.tempdir) {
1912                 t.Fatalf(".CompiledGoFiles with -compiled did not mention cache %s", tg.tempdir)
1913         }
1914         dir := ""
1915         for _, file := range strings.Split(tg.stdout.String(), "\n") {
1916                 if file == "" {
1917                         continue
1918                 }
1919                 if dir == "" {
1920                         dir = file
1921                         continue
1922                 }
1923                 if !strings.Contains(file, "/") && !strings.Contains(file, `\`) {
1924                         file = filepath.Join(dir, file)
1925                 }
1926                 if _, err := os.Stat(file); err != nil {
1927                         t.Fatalf("cannot find .CompiledGoFiles result %s: %v", file, err)
1928                 }
1929         }
1930 }
1931
1932 func TestGoListExport(t *testing.T) {
1933         skipIfGccgo(t, "gccgo does not have standard packages")
1934         tg := testgo(t)
1935         defer tg.cleanup()
1936         tg.parallel()
1937         tg.makeTempdir()
1938         tg.setenv("GOCACHE", tg.tempdir)
1939
1940         tg.run("list", "-f", "{{.Export}}", "strings")
1941         if tg.stdout.String() != "" {
1942                 t.Fatalf(".Export without -export unexpectedly set")
1943         }
1944         tg.run("list", "-export", "-f", "{{.Export}}", "strings")
1945         file := strings.TrimSpace(tg.stdout.String())
1946         if file == "" {
1947                 t.Fatalf(".Export with -export was empty")
1948         }
1949         if _, err := os.Stat(file); err != nil {
1950                 t.Fatalf("cannot find .Export result %s: %v", file, err)
1951         }
1952 }
1953
1954 // Issue 4096. Validate the output of unsuccessful go install foo/quxx.
1955 func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) {
1956         tg := testgo(t)
1957         defer tg.cleanup()
1958         tg.parallel()
1959         tg.runFail("install", "foo/quxx")
1960         if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 {
1961                 t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`)
1962         }
1963 }
1964
1965 func TestGOROOTSearchFailureReporting(t *testing.T) {
1966         tg := testgo(t)
1967         defer tg.cleanup()
1968         tg.parallel()
1969         tg.runFail("install", "foo/quxx")
1970         if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 {
1971                 t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`)
1972         }
1973 }
1974
1975 func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) {
1976         tg := testgo(t)
1977         defer tg.cleanup()
1978         tg.parallel()
1979         sep := string(filepath.ListSeparator)
1980         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1981         tg.runFail("install", "foo/quxx")
1982         if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 {
1983                 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`)
1984         }
1985 }
1986
1987 // Test (from $GOPATH) annotation is reported for the first GOPATH entry,
1988 func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) {
1989         tg := testgo(t)
1990         defer tg.cleanup()
1991         tg.parallel()
1992         sep := string(filepath.ListSeparator)
1993         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
1994         tg.runFail("install", "foo/quxx")
1995         if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 {
1996                 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`)
1997         }
1998 }
1999
2000 // but not on the second.
2001 func TestMentionGOPATHNotOnSecondEntry(t *testing.T) {
2002         tg := testgo(t)
2003         defer tg.cleanup()
2004         tg.parallel()
2005         sep := string(filepath.ListSeparator)
2006         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
2007         tg.runFail("install", "foo/quxx")
2008         if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 {
2009                 t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`)
2010         }
2011 }
2012
2013 func homeEnvName() string {
2014         switch runtime.GOOS {
2015         case "windows":
2016                 return "USERPROFILE"
2017         case "plan9":
2018                 return "home"
2019         default:
2020                 return "HOME"
2021         }
2022 }
2023
2024 func tempEnvName() string {
2025         switch runtime.GOOS {
2026         case "windows":
2027                 return "TMP"
2028         case "plan9":
2029                 return "TMPDIR" // actually plan 9 doesn't have one at all but this is fine
2030         default:
2031                 return "TMPDIR"
2032         }
2033 }
2034
2035 func TestDefaultGOPATH(t *testing.T) {
2036         tg := testgo(t)
2037         defer tg.cleanup()
2038         tg.parallel()
2039         tg.tempDir("home/go")
2040         tg.setenv(homeEnvName(), tg.path("home"))
2041
2042         tg.run("env", "GOPATH")
2043         tg.grepStdout(regexp.QuoteMeta(tg.path("home/go")), "want GOPATH=$HOME/go")
2044
2045         tg.setenv("GOROOT", tg.path("home/go"))
2046         tg.run("env", "GOPATH")
2047         tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go")
2048
2049         tg.setenv("GOROOT", tg.path("home/go")+"/")
2050         tg.run("env", "GOPATH")
2051         tg.grepStdoutNot(".", "want unset GOPATH because GOROOT=$HOME/go/")
2052 }
2053
2054 func TestDefaultGOPATHGet(t *testing.T) {
2055         testenv.MustHaveExternalNetwork(t)
2056         testenv.MustHaveExecPath(t, "git")
2057
2058         tg := testgo(t)
2059         defer tg.cleanup()
2060         tg.setenv("GOPATH", "")
2061         tg.tempDir("home")
2062         tg.setenv(homeEnvName(), tg.path("home"))
2063
2064         // warn for creating directory
2065         tg.run("get", "-v", "github.com/golang/example/hello")
2066         tg.grepStderr("created GOPATH="+regexp.QuoteMeta(tg.path("home/go"))+"; see 'go help gopath'", "did not create GOPATH")
2067
2068         // no warning if directory already exists
2069         tg.must(robustio.RemoveAll(tg.path("home/go")))
2070         tg.tempDir("home/go")
2071         tg.run("get", "github.com/golang/example/hello")
2072         tg.grepStderrNot(".", "expected no output on standard error")
2073
2074         // error if $HOME/go is a file
2075         tg.must(robustio.RemoveAll(tg.path("home/go")))
2076         tg.tempFile("home/go", "")
2077         tg.runFail("get", "github.com/golang/example/hello")
2078         tg.grepStderr(`mkdir .*[/\\]go: .*(not a directory|cannot find the path)`, "expected error because $HOME/go is a file")
2079 }
2080
2081 func TestDefaultGOPATHPrintedSearchList(t *testing.T) {
2082         tg := testgo(t)
2083         defer tg.cleanup()
2084         tg.setenv("GOPATH", "")
2085         tg.tempDir("home")
2086         tg.setenv(homeEnvName(), tg.path("home"))
2087
2088         tg.runFail("install", "github.com/golang/example/hello")
2089         tg.grepStderr(regexp.QuoteMeta(tg.path("home/go/src/github.com/golang/example/hello"))+`.*from \$GOPATH`, "expected default GOPATH")
2090 }
2091
2092 // Issue 4186. go get cannot be used to download packages to $GOROOT.
2093 // Test that without GOPATH set, go get should fail.
2094 func TestGoGetIntoGOROOT(t *testing.T) {
2095         testenv.MustHaveExternalNetwork(t)
2096
2097         tg := testgo(t)
2098         defer tg.cleanup()
2099         tg.parallel()
2100         tg.tempDir("src")
2101
2102         // Fails because GOROOT=GOPATH
2103         tg.setenv("GOPATH", tg.path("."))
2104         tg.setenv("GOROOT", tg.path("."))
2105         tg.runFail("get", "-d", "github.com/golang/example/hello")
2106         tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2107         tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2108
2109         // Fails because GOROOT=GOPATH after cleaning.
2110         tg.setenv("GOPATH", tg.path(".")+"/")
2111         tg.setenv("GOROOT", tg.path("."))
2112         tg.runFail("get", "-d", "github.com/golang/example/hello")
2113         tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2114         tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2115
2116         tg.setenv("GOPATH", tg.path("."))
2117         tg.setenv("GOROOT", tg.path(".")+"/")
2118         tg.runFail("get", "-d", "github.com/golang/example/hello")
2119         tg.grepStderr("warning: GOPATH set to GOROOT", "go should detect GOPATH=GOROOT")
2120         tg.grepStderr(`\$GOPATH must not be set to \$GOROOT`, "go should detect GOPATH=GOROOT")
2121
2122         // Fails because GOROOT=$HOME/go so default GOPATH unset.
2123         tg.tempDir("home/go")
2124         tg.setenv(homeEnvName(), tg.path("home"))
2125         tg.setenv("GOPATH", "")
2126         tg.setenv("GOROOT", tg.path("home/go"))
2127         tg.runFail("get", "-d", "github.com/golang/example/hello")
2128         tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2129
2130         tg.setenv(homeEnvName(), tg.path("home")+"/")
2131         tg.setenv("GOPATH", "")
2132         tg.setenv("GOROOT", tg.path("home/go"))
2133         tg.runFail("get", "-d", "github.com/golang/example/hello")
2134         tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2135
2136         tg.setenv(homeEnvName(), tg.path("home"))
2137         tg.setenv("GOPATH", "")
2138         tg.setenv("GOROOT", tg.path("home/go")+"/")
2139         tg.runFail("get", "-d", "github.com/golang/example/hello")
2140         tg.grepStderr(`\$GOPATH not set`, "expected GOPATH not set")
2141 }
2142
2143 func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) {
2144         skipIfGccgo(t, "gccgo does not support -ldflags -X")
2145         tooSlow(t)
2146         tg := testgo(t)
2147         defer tg.cleanup()
2148         tg.parallel()
2149         tg.tempFile("main.go", `package main
2150                 var extern string
2151                 func main() {
2152                         println(extern)
2153                 }`)
2154         tg.run("run", "-ldflags", `-X "main.extern=hello world"`, tg.path("main.go"))
2155         tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`)
2156 }
2157
2158 func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) {
2159         skipIfGccgo(t, "gccgo has no standard packages")
2160         tooSlow(t)
2161         tg := testgo(t)
2162         defer tg.cleanup()
2163         // TODO: tg.parallel()
2164         tg.makeTempdir()
2165         tg.cd(tg.path("."))
2166         tg.run("test", "-cpuprofile", "errors.prof", "errors")
2167         tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test")
2168 }
2169
2170 func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) {
2171         skipIfGccgo(t, "gccgo has no standard packages")
2172         tooSlow(t)
2173         tg := testgo(t)
2174         defer tg.cleanup()
2175         // TODO: tg.parallel()
2176         tg.makeTempdir()
2177         tg.cd(tg.path("."))
2178         tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2179         tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test")
2180 }
2181
2182 func TestGoTestMutexprofileLeavesBinaryBehind(t *testing.T) {
2183         skipIfGccgo(t, "gccgo has no standard packages")
2184         tooSlow(t)
2185         tg := testgo(t)
2186         defer tg.cleanup()
2187         // TODO: tg.parallel()
2188         tg.makeTempdir()
2189         tg.cd(tg.path("."))
2190         tg.run("test", "-mutexprofile", "errors.prof", "errors")
2191         tg.wantExecutable("errors.test"+exeSuffix, "go test -mutexprofile did not create errors.test")
2192 }
2193
2194 func TestGoTestMutexprofileDashOControlsBinaryLocation(t *testing.T) {
2195         skipIfGccgo(t, "gccgo has no standard packages")
2196         tooSlow(t)
2197         tg := testgo(t)
2198         defer tg.cleanup()
2199         // TODO: tg.parallel()
2200         tg.makeTempdir()
2201         tg.cd(tg.path("."))
2202         tg.run("test", "-mutexprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
2203         tg.wantExecutable("myerrors.test"+exeSuffix, "go test -mutexprofile -o myerrors.test did not create myerrors.test")
2204 }
2205
2206 func TestGoBuildNonMain(t *testing.T) {
2207         tg := testgo(t)
2208         defer tg.cleanup()
2209         // TODO: tg.parallel()
2210         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2211         tg.runFail("build", "-buildmode=exe", "-o", "not_main"+exeSuffix, "not_main")
2212         tg.grepStderr("-buildmode=exe requires exactly one main package", "go build with -o and -buildmode=exe should on a non-main package should throw an error")
2213         tg.mustNotExist("not_main" + exeSuffix)
2214 }
2215
2216 func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) {
2217         skipIfGccgo(t, "gccgo has no standard packages")
2218         tooSlow(t)
2219         tg := testgo(t)
2220         defer tg.cleanup()
2221         tg.parallel()
2222         tg.makeTempdir()
2223         tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2224         tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test")
2225 }
2226
2227 func TestGoTestDashOWritesBinary(t *testing.T) {
2228         skipIfGccgo(t, "gccgo has no standard packages")
2229         tooSlow(t)
2230         tg := testgo(t)
2231         defer tg.cleanup()
2232         tg.parallel()
2233         tg.makeTempdir()
2234         tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2235         tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2236 }
2237
2238 func TestGoTestDashIDashOWritesBinary(t *testing.T) {
2239         skipIfGccgo(t, "gccgo has no standard packages")
2240         tooSlow(t)
2241         tg := testgo(t)
2242         defer tg.cleanup()
2243         tg.parallel()
2244         tg.makeTempdir()
2245
2246         // don't let test -i overwrite runtime
2247         tg.wantNotStale("runtime", "", "must be non-stale before test -i")
2248
2249         tg.run("test", "-v", "-i", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
2250         tg.grepBothNot("PASS|FAIL", "test should not have run")
2251         tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
2252 }
2253
2254 // Issue 4568.
2255 func TestSymlinksList(t *testing.T) {
2256         testenv.MustHaveSymlink(t)
2257
2258         tg := testgo(t)
2259         defer tg.cleanup()
2260         // TODO: tg.parallel()
2261         tg.tempDir("src")
2262         tg.must(os.Symlink(tg.path("."), tg.path("src/dir1")))
2263         tg.tempFile("src/dir1/p.go", "package p")
2264         tg.setenv("GOPATH", tg.path("."))
2265         tg.cd(tg.path("src"))
2266         tg.run("list", "-f", "{{.Root}}", "dir1")
2267         if strings.TrimSpace(tg.getStdout()) != tg.path(".") {
2268                 t.Error("confused by symlinks")
2269         }
2270 }
2271
2272 // Issue 14054.
2273 func TestSymlinksVendor(t *testing.T) {
2274         testenv.MustHaveSymlink(t)
2275
2276         tg := testgo(t)
2277         defer tg.cleanup()
2278         // TODO: tg.parallel()
2279         tg.tempDir("gopath/src/dir1/vendor/v")
2280         tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}")
2281         tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v")
2282         tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2283         tg.setenv("GOPATH", tg.path("gopath"))
2284         tg.cd(tg.path("symdir1"))
2285         tg.run("list", "-f", "{{.Root}}", ".")
2286         if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2287                 t.Error("list confused by symlinks")
2288         }
2289
2290         // All of these should succeed, not die in vendor-handling code.
2291         tg.run("run", "p.go")
2292         tg.run("build")
2293         tg.run("install")
2294 }
2295
2296 // Issue 15201.
2297 func TestSymlinksVendor15201(t *testing.T) {
2298         testenv.MustHaveSymlink(t)
2299
2300         tg := testgo(t)
2301         defer tg.cleanup()
2302
2303         tg.tempDir("gopath/src/x/y/_vendor/src/x")
2304         tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y")))
2305         tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n")
2306         tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor")))
2307         tg.tempFile("gopath/src/x/y/z/z.go", "package z\n")
2308
2309         tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath"))
2310         tg.cd(tg.path("gopath/src"))
2311         tg.run("list", "./...")
2312 }
2313
2314 func TestSymlinksInternal(t *testing.T) {
2315         testenv.MustHaveSymlink(t)
2316
2317         tg := testgo(t)
2318         defer tg.cleanup()
2319         tg.tempDir("gopath/src/dir1/internal/v")
2320         tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}")
2321         tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v")
2322         tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1")))
2323         tg.setenv("GOPATH", tg.path("gopath"))
2324         tg.cd(tg.path("symdir1"))
2325         tg.run("list", "-f", "{{.Root}}", ".")
2326         if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") {
2327                 t.Error("list confused by symlinks")
2328         }
2329
2330         // All of these should succeed, not die in internal-handling code.
2331         tg.run("run", "p.go")
2332         tg.run("build")
2333         tg.run("install")
2334 }
2335
2336 // Issue 4515.
2337 func TestInstallWithTags(t *testing.T) {
2338         tooSlow(t)
2339         tg := testgo(t)
2340         defer tg.cleanup()
2341         tg.parallel()
2342         tg.tempDir("bin")
2343         tg.tempFile("src/example/a/main.go", `package main
2344                 func main() {}`)
2345         tg.tempFile("src/example/b/main.go", `// +build mytag
2346
2347                 package main
2348                 func main() {}`)
2349         tg.setenv("GOPATH", tg.path("."))
2350         tg.run("install", "-tags", "mytag", "example/a", "example/b")
2351         tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries")
2352         tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries")
2353         tg.must(os.Remove(tg.path("bin/a" + exeSuffix)))
2354         tg.must(os.Remove(tg.path("bin/b" + exeSuffix)))
2355         tg.run("install", "-tags", "mytag", "example/...")
2356         tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries")
2357         tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries")
2358         tg.run("list", "-tags", "mytag", "example/b...")
2359         if strings.TrimSpace(tg.getStdout()) != "example/b" {
2360                 t.Error("go list example/b did not find example/b")
2361         }
2362 }
2363
2364 // Issue 4773
2365 func TestCaseCollisions(t *testing.T) {
2366         tg := testgo(t)
2367         defer tg.cleanup()
2368         tg.parallel()
2369         tg.tempDir("src/example/a/pkg")
2370         tg.tempDir("src/example/a/Pkg")
2371         tg.tempDir("src/example/b")
2372         tg.setenv("GOPATH", tg.path("."))
2373         tg.tempFile("src/example/a/a.go", `package p
2374                 import (
2375                         _ "example/a/pkg"
2376                         _ "example/a/Pkg"
2377                 )`)
2378         tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`)
2379         tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`)
2380         tg.run("list", "-json", "example/a")
2381         tg.grepStdout("case-insensitive import collision", "go list -json example/a did not report import collision")
2382         tg.runFail("build", "example/a")
2383         tg.grepStderr("case-insensitive import collision", "go build example/a did not report import collision")
2384         tg.tempFile("src/example/b/file.go", `package b`)
2385         tg.tempFile("src/example/b/FILE.go", `package b`)
2386         f, err := os.Open(tg.path("src/example/b"))
2387         tg.must(err)
2388         names, err := f.Readdirnames(0)
2389         tg.must(err)
2390         tg.check(f.Close())
2391         args := []string{"list"}
2392         if len(names) == 2 {
2393                 // case-sensitive file system, let directory read find both files
2394                 args = append(args, "example/b")
2395         } else {
2396                 // case-insensitive file system, list files explicitly on command line
2397                 args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go"))
2398         }
2399         tg.runFail(args...)
2400         tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision")
2401
2402         tg.runFail("list", "example/a/pkg", "example/a/Pkg")
2403         tg.grepStderr("case-insensitive import collision", "go list example/a/pkg example/a/Pkg did not report import collision")
2404         tg.run("list", "-json", "-e", "example/a/pkg", "example/a/Pkg")
2405         tg.grepStdout("case-insensitive import collision", "go list -json -e example/a/pkg example/a/Pkg did not report import collision")
2406         tg.runFail("build", "example/a/pkg", "example/a/Pkg")
2407         tg.grepStderr("case-insensitive import collision", "go build example/a/pkg example/a/Pkg did not report import collision")
2408 }
2409
2410 // Issue 17451, 17662.
2411 func TestSymlinkWarning(t *testing.T) {
2412         tg := testgo(t)
2413         defer tg.cleanup()
2414         tg.parallel()
2415         tg.makeTempdir()
2416         tg.setenv("GOPATH", tg.path("."))
2417
2418         tg.tempDir("src/example/xx")
2419         tg.tempDir("yy/zz")
2420         tg.tempFile("yy/zz/zz.go", "package zz\n")
2421         if err := os.Symlink(tg.path("yy"), tg.path("src/example/xx/yy")); err != nil {
2422                 t.Skipf("symlink failed: %v", err)
2423         }
2424         tg.run("list", "example/xx/z...")
2425         tg.grepStdoutNot(".", "list should not have matched anything")
2426         tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2427         tg.grepStderrNot("symlink", "list should not have reported symlink")
2428
2429         tg.run("list", "example/xx/...")
2430         tg.grepStdoutNot(".", "list should not have matched anything")
2431         tg.grepStderr("matched no packages", "list should have reported that pattern matched no packages")
2432         tg.grepStderr("ignoring symlink", "list should have reported symlink")
2433 }
2434
2435 // Issue 8181.
2436 func TestGoGetDashTIssue8181(t *testing.T) {
2437         testenv.MustHaveExternalNetwork(t)
2438         testenv.MustHaveExecPath(t, "git")
2439
2440         tg := testgo(t)
2441         defer tg.cleanup()
2442         tg.parallel()
2443         tg.makeTempdir()
2444         tg.setenv("GOPATH", tg.path("."))
2445         tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b")
2446         tg.run("list", "...")
2447         tg.grepStdout("x/build/gerrit", "missing expected x/build/gerrit")
2448 }
2449
2450 func TestIssue11307(t *testing.T) {
2451         // go get -u was not working except in checkout directory
2452         testenv.MustHaveExternalNetwork(t)
2453         testenv.MustHaveExecPath(t, "git")
2454
2455         tg := testgo(t)
2456         defer tg.cleanup()
2457         tg.parallel()
2458         tg.makeTempdir()
2459         tg.setenv("GOPATH", tg.path("."))
2460         tg.run("get", "github.com/rsc/go-get-issue-11307")
2461         tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing
2462 }
2463
2464 func TestShadowingLogic(t *testing.T) {
2465         skipIfGccgo(t, "gccgo has no standard packages")
2466         tg := testgo(t)
2467         defer tg.cleanup()
2468         pwd := tg.pwd()
2469         sep := string(filepath.ListSeparator)
2470         tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2"))
2471
2472         // The math in root1 is not "math" because the standard math is.
2473         tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math")
2474         pwdForwardSlash := strings.ReplaceAll(pwd, string(os.PathSeparator), "/")
2475         if !strings.HasPrefix(pwdForwardSlash, "/") {
2476                 pwdForwardSlash = "/" + pwdForwardSlash
2477         }
2478         // The output will have makeImportValid applies, but we only
2479         // bother to deal with characters we might reasonably see.
2480         for _, r := range " :" {
2481                 pwdForwardSlash = strings.ReplaceAll(pwdForwardSlash, string(r), "_")
2482         }
2483         want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")"
2484         if strings.TrimSpace(tg.getStdout()) != want {
2485                 t.Error("shadowed math is not shadowed; looking for", want)
2486         }
2487
2488         // The foo in root1 is "foo".
2489         tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo")
2490         if strings.TrimSpace(tg.getStdout()) != "(foo) ()" {
2491                 t.Error("unshadowed foo is shadowed")
2492         }
2493
2494         // The foo in root2 is not "foo" because the foo in root1 got there first.
2495         tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo")
2496         want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")"
2497         if strings.TrimSpace(tg.getStdout()) != want {
2498                 t.Error("shadowed foo is not shadowed; looking for", want)
2499         }
2500
2501         // The error for go install should mention the conflicting directory.
2502         tg.runFail("install", "./testdata/shadow/root2/src/foo")
2503         want = "go install: no install location for " + filepath.Join(pwd, "testdata", "shadow", "root2", "src", "foo") + ": hidden by " + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo")
2504         if strings.TrimSpace(tg.getStderr()) != want {
2505                 t.Error("wrong shadowed install error; looking for", want)
2506         }
2507 }
2508
2509 // Only succeeds if source order is preserved.
2510 func TestSourceFileNameOrderPreserved(t *testing.T) {
2511         tg := testgo(t)
2512         defer tg.cleanup()
2513         tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go")
2514 }
2515
2516 // Check that coverage analysis works at all.
2517 // Don't worry about the exact numbers but require not 0.0%.
2518 func checkCoverage(tg *testgoData, data string) {
2519         tg.t.Helper()
2520         if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) {
2521                 tg.t.Error("some coverage results are 0.0%")
2522         }
2523 }
2524
2525 func TestCoverageRuns(t *testing.T) {
2526         skipIfGccgo(t, "gccgo has no cover tool")
2527         tooSlow(t)
2528         tg := testgo(t)
2529         defer tg.cleanup()
2530         tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp")
2531         data := tg.getStdout() + tg.getStderr()
2532         tg.run("test", "-short", "-cover", "strings", "math", "regexp")
2533         data += tg.getStdout() + tg.getStderr()
2534         checkCoverage(tg, data)
2535 }
2536
2537 func TestCoverageDotImport(t *testing.T) {
2538         skipIfGccgo(t, "gccgo has no cover tool")
2539         tooSlow(t)
2540         tg := testgo(t)
2541         defer tg.cleanup()
2542         tg.parallel()
2543         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2544         tg.run("test", "-coverpkg=coverdot1,coverdot2", "coverdot2")
2545         data := tg.getStdout() + tg.getStderr()
2546         checkCoverage(tg, data)
2547 }
2548
2549 // Check that coverage analysis uses set mode.
2550 // Also check that coverage profiles merge correctly.
2551 func TestCoverageUsesSetMode(t *testing.T) {
2552         skipIfGccgo(t, "gccgo has no cover tool")
2553         tooSlow(t)
2554         tg := testgo(t)
2555         defer tg.cleanup()
2556         tg.creatingTemp("testdata/cover.out")
2557         tg.run("test", "-short", "-cover", "encoding/binary", "errors", "-coverprofile=testdata/cover.out")
2558         data := tg.getStdout() + tg.getStderr()
2559         if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2560                 t.Error(err)
2561         } else {
2562                 if !bytes.Contains(out, []byte("mode: set")) {
2563                         t.Error("missing mode: set")
2564                 }
2565                 if !bytes.Contains(out, []byte("errors.go")) {
2566                         t.Error("missing errors.go")
2567                 }
2568                 if !bytes.Contains(out, []byte("binary.go")) {
2569                         t.Error("missing binary.go")
2570                 }
2571                 if bytes.Count(out, []byte("mode: set")) != 1 {
2572                         t.Error("too many mode: set")
2573                 }
2574         }
2575         checkCoverage(tg, data)
2576 }
2577
2578 func TestCoverageUsesAtomicModeForRace(t *testing.T) {
2579         tooSlow(t)
2580         if !canRace {
2581                 t.Skip("skipping because race detector not supported")
2582         }
2583         skipIfGccgo(t, "gccgo has no cover tool")
2584
2585         tg := testgo(t)
2586         defer tg.cleanup()
2587         tg.creatingTemp("testdata/cover.out")
2588         tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
2589         data := tg.getStdout() + tg.getStderr()
2590         if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
2591                 t.Error(err)
2592         } else {
2593                 if !bytes.Contains(out, []byte("mode: atomic")) {
2594                         t.Error("missing mode: atomic")
2595                 }
2596         }
2597         checkCoverage(tg, data)
2598 }
2599
2600 func TestCoverageSyncAtomicImport(t *testing.T) {
2601         skipIfGccgo(t, "gccgo has no cover tool")
2602         tooSlow(t)
2603         tg := testgo(t)
2604         defer tg.cleanup()
2605         tg.parallel()
2606         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2607         tg.run("test", "-short", "-cover", "-covermode=atomic", "-coverpkg=coverdep/p1", "coverdep")
2608 }
2609
2610 func TestCoverageDepLoop(t *testing.T) {
2611         tooSlow(t)
2612         tg := testgo(t)
2613         defer tg.cleanup()
2614         tg.parallel()
2615         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2616         // coverdep2/p1's xtest imports coverdep2/p2 which imports coverdep2/p1.
2617         // Make sure that coverage on coverdep2/p2 recompiles coverdep2/p2.
2618         tg.run("test", "-short", "-cover", "coverdep2/p1")
2619         tg.grepStdout("coverage: 100.0% of statements", "expected 100.0% coverage")
2620 }
2621
2622 func TestCoverageNoStatements(t *testing.T) {
2623         tooSlow(t)
2624         tg := testgo(t)
2625         defer tg.cleanup()
2626         tg.run("test", "-cover", "./testdata/testcover/pkg4")
2627         tg.grepStdout("[no statements]", "expected [no statements] for pkg4")
2628 }
2629
2630 func TestCoverageImportMainLoop(t *testing.T) {
2631         skipIfGccgo(t, "gccgo has no cover tool")
2632         tg := testgo(t)
2633         defer tg.cleanup()
2634         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2635         tg.runFail("test", "importmain/test")
2636         tg.grepStderr("not an importable package", "did not detect import main")
2637         tg.runFail("test", "-cover", "importmain/test")
2638         tg.grepStderr("not an importable package", "did not detect import main")
2639 }
2640
2641 func TestCoveragePattern(t *testing.T) {
2642         skipIfGccgo(t, "gccgo has no cover tool")
2643         tooSlow(t)
2644         tg := testgo(t)
2645         defer tg.cleanup()
2646         tg.parallel()
2647         tg.makeTempdir()
2648         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2649
2650         // If coverpkg=sleepy... expands by package loading
2651         // (as opposed to pattern matching on deps)
2652         // then it will try to load sleepybad, which does not compile,
2653         // and the test command will fail.
2654         tg.run("test", "-coverprofile="+tg.path("cover.out"), "-coverpkg=sleepy...", "-run=^$", "sleepy1")
2655 }
2656
2657 func TestCoverageErrorLine(t *testing.T) {
2658         skipIfGccgo(t, "gccgo has no cover tool")
2659         tooSlow(t)
2660         tg := testgo(t)
2661         defer tg.cleanup()
2662         tg.parallel()
2663         tg.makeTempdir()
2664         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2665         tg.setenv("GOTMPDIR", tg.tempdir)
2666
2667         tg.runFail("test", "coverbad")
2668         tg.grepStderr(`coverbad[\\/]p\.go:4`, "did not find coverbad/p.go:4")
2669         if canCgo {
2670                 tg.grepStderr(`coverbad[\\/]p1\.go:6`, "did not find coverbad/p1.go:6")
2671         }
2672         tg.grepStderrNot(regexp.QuoteMeta(tg.tempdir), "found temporary directory in error")
2673         stderr := tg.getStderr()
2674
2675         tg.runFail("test", "-cover", "coverbad")
2676         stderr2 := tg.getStderr()
2677
2678         // It's OK that stderr2 drops the character position in the error,
2679         // because of the //line directive (see golang.org/issue/22662).
2680         stderr = strings.ReplaceAll(stderr, "p.go:4:2:", "p.go:4:")
2681         if stderr != stderr2 {
2682                 t.Logf("test -cover changed error messages:\nbefore:\n%s\n\nafter:\n%s", stderr, stderr2)
2683                 t.Skip("golang.org/issue/22660")
2684                 t.FailNow()
2685         }
2686 }
2687
2688 func TestTestBuildFailureOutput(t *testing.T) {
2689         tooSlow(t)
2690
2691         tg := testgo(t)
2692         defer tg.cleanup()
2693         tg.parallel()
2694         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2695
2696         // Doesn't build, -x output should not claim to run test.
2697         tg.runFail("test", "-x", "coverbad")
2698         tg.grepStderrNot(`[\\/]coverbad\.test( |$)`, "claimed to run test")
2699 }
2700
2701 func TestCoverageFunc(t *testing.T) {
2702         skipIfGccgo(t, "gccgo has no cover tool")
2703         tooSlow(t)
2704         tg := testgo(t)
2705         defer tg.cleanup()
2706         tg.parallel()
2707         tg.makeTempdir()
2708         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2709
2710         tg.run("test", "-outputdir="+tg.tempdir, "-coverprofile=cover.out", "coverasm")
2711         tg.run("tool", "cover", "-func="+tg.path("cover.out"))
2712         tg.grepStdout(`\tg\t*100.0%`, "did not find g 100% covered")
2713         tg.grepStdoutNot(`\tf\t*[0-9]`, "reported coverage for assembly function f")
2714 }
2715
2716 // Issue 24588.
2717 func TestCoverageDashC(t *testing.T) {
2718         skipIfGccgo(t, "gccgo has no cover tool")
2719         tooSlow(t)
2720         tg := testgo(t)
2721         defer tg.cleanup()
2722         tg.parallel()
2723         tg.makeTempdir()
2724         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2725         tg.run("test", "-c", "-o", tg.path("coverdep"), "-coverprofile="+tg.path("no/such/dir/cover.out"), "coverdep")
2726         tg.wantExecutable(tg.path("coverdep"), "go -test -c -coverprofile did not create executable")
2727 }
2728
2729 func TestPluginNonMain(t *testing.T) {
2730         wd, err := os.Getwd()
2731         if err != nil {
2732                 t.Fatal(err)
2733         }
2734
2735         pkg := filepath.Join(wd, "testdata", "testdep", "p2")
2736
2737         tg := testgo(t)
2738         defer tg.cleanup()
2739
2740         tg.runFail("build", "-buildmode=plugin", pkg)
2741 }
2742
2743 func TestTestEmpty(t *testing.T) {
2744         if !canRace {
2745                 t.Skip("no race detector")
2746         }
2747
2748         wd, _ := os.Getwd()
2749         testdata := filepath.Join(wd, "testdata")
2750         for _, dir := range []string{"pkg", "test", "xtest", "pkgtest", "pkgxtest", "pkgtestxtest", "testxtest"} {
2751                 t.Run(dir, func(t *testing.T) {
2752                         tg := testgo(t)
2753                         defer tg.cleanup()
2754                         tg.setenv("GOPATH", testdata)
2755                         tg.cd(filepath.Join(testdata, "src/empty/"+dir))
2756                         tg.run("test", "-cover", "-coverpkg=.", "-race")
2757                 })
2758                 if testing.Short() {
2759                         break
2760                 }
2761         }
2762 }
2763
2764 func TestNoGoError(t *testing.T) {
2765         wd, _ := os.Getwd()
2766         testdata := filepath.Join(wd, "testdata")
2767         for _, dir := range []string{"empty/test", "empty/xtest", "empty/testxtest", "exclude", "exclude/ignore", "exclude/empty"} {
2768                 t.Run(dir, func(t *testing.T) {
2769                         tg := testgo(t)
2770                         defer tg.cleanup()
2771                         tg.setenv("GOPATH", testdata)
2772                         tg.cd(filepath.Join(testdata, "src"))
2773                         tg.runFail("build", "./"+dir)
2774                         var want string
2775                         if strings.Contains(dir, "test") {
2776                                 want = "no non-test Go files in "
2777                         } else if dir == "exclude" {
2778                                 want = "build constraints exclude all Go files in "
2779                         } else {
2780                                 want = "no Go files in "
2781                         }
2782                         tg.grepStderr(want, "wrong reason for failure")
2783                 })
2784         }
2785 }
2786
2787 func TestTestRaceInstall(t *testing.T) {
2788         if !canRace {
2789                 t.Skip("no race detector")
2790         }
2791         tooSlow(t)
2792
2793         tg := testgo(t)
2794         defer tg.cleanup()
2795         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2796
2797         tg.tempDir("pkg")
2798         pkgdir := tg.path("pkg")
2799         tg.run("install", "-race", "-pkgdir="+pkgdir, "std")
2800         tg.run("test", "-race", "-pkgdir="+pkgdir, "-i", "-v", "empty/pkg")
2801         if tg.getStderr() != "" {
2802                 t.Error("go test -i -race: rebuilds cached packages")
2803         }
2804 }
2805
2806 func TestBuildDryRunWithCgo(t *testing.T) {
2807         if !canCgo {
2808                 t.Skip("skipping because cgo not enabled")
2809         }
2810
2811         tg := testgo(t)
2812         defer tg.cleanup()
2813         tg.tempFile("foo.go", `package main
2814
2815 /*
2816 #include <limits.h>
2817 */
2818 import "C"
2819
2820 func main() {
2821         println(C.INT_MAX)
2822 }`)
2823         tg.run("build", "-n", tg.path("foo.go"))
2824         tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file")
2825 }
2826
2827 func TestCoverageWithCgo(t *testing.T) {
2828         skipIfGccgo(t, "gccgo has no cover tool")
2829         tooSlow(t)
2830         if !canCgo {
2831                 t.Skip("skipping because cgo not enabled")
2832         }
2833
2834         for _, dir := range []string{"cgocover", "cgocover2", "cgocover3", "cgocover4"} {
2835                 t.Run(dir, func(t *testing.T) {
2836                         tg := testgo(t)
2837                         tg.parallel()
2838                         defer tg.cleanup()
2839                         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2840                         tg.run("test", "-short", "-cover", dir)
2841                         data := tg.getStdout() + tg.getStderr()
2842                         checkCoverage(tg, data)
2843                 })
2844         }
2845 }
2846
2847 func TestCgoAsmError(t *testing.T) {
2848         if !canCgo {
2849                 t.Skip("skipping because cgo not enabled")
2850         }
2851
2852         tg := testgo(t)
2853         tg.parallel()
2854         defer tg.cleanup()
2855         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
2856         tg.runFail("build", "cgoasm")
2857         tg.grepBoth("package using cgo has Go assembly file", "did not detect Go assembly file")
2858 }
2859
2860 func TestCgoDependsOnSyscall(t *testing.T) {
2861         if testing.Short() {
2862                 t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode")
2863         }
2864         if !canCgo {
2865                 t.Skip("skipping because cgo not enabled")
2866         }
2867         if !canRace {
2868                 t.Skip("skipping because race detector not supported")
2869         }
2870
2871         tg := testgo(t)
2872         defer tg.cleanup()
2873         files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race"))
2874         tg.must(err)
2875         for _, file := range files {
2876                 tg.check(robustio.RemoveAll(file))
2877         }
2878         tg.tempFile("src/foo/foo.go", `
2879                 package foo
2880                 //#include <stdio.h>
2881                 import "C"`)
2882         tg.setenv("GOPATH", tg.path("."))
2883         tg.run("build", "-race", "foo")
2884 }
2885
2886 func TestCgoShowsFullPathNames(t *testing.T) {
2887         if !canCgo {
2888                 t.Skip("skipping because cgo not enabled")
2889         }
2890
2891         tg := testgo(t)
2892         defer tg.cleanup()
2893         tg.parallel()
2894         tg.tempFile("src/x/y/dirname/foo.go", `
2895                 package foo
2896                 import "C"
2897                 func f() {`)
2898         tg.setenv("GOPATH", tg.path("."))
2899         tg.runFail("build", "x/y/dirname")
2900         tg.grepBoth("x/y/dirname", "error did not use full path")
2901 }
2902
2903 func TestCgoHandlesWlORIGIN(t *testing.T) {
2904         tooSlow(t)
2905         if !canCgo {
2906                 t.Skip("skipping because cgo not enabled")
2907         }
2908
2909         tg := testgo(t)
2910         defer tg.cleanup()
2911         tg.parallel()
2912         tg.tempFile("src/origin/origin.go", `package origin
2913                 // #cgo !darwin LDFLAGS: -Wl,-rpath,$ORIGIN
2914                 // void f(void) {}
2915                 import "C"
2916                 func f() { C.f() }`)
2917         tg.setenv("GOPATH", tg.path("."))
2918         tg.run("build", "origin")
2919 }
2920
2921 func TestCgoPkgConfig(t *testing.T) {
2922         tooSlow(t)
2923         if !canCgo {
2924                 t.Skip("skipping because cgo not enabled")
2925         }
2926         tg := testgo(t)
2927         defer tg.cleanup()
2928         tg.parallel()
2929
2930         tg.run("env", "PKG_CONFIG")
2931         pkgConfig := strings.TrimSpace(tg.getStdout())
2932         testenv.MustHaveExecPath(t, pkgConfig)
2933         if out, err := exec.Command(pkgConfig, "--atleast-pkgconfig-version", "0.24").CombinedOutput(); err != nil {
2934                 t.Skipf("%s --atleast-pkgconfig-version 0.24: %v\n%s", pkgConfig, err, out)
2935         }
2936
2937         // OpenBSD's pkg-config is strict about whitespace and only
2938         // supports backslash-escaped whitespace. It does not support
2939         // quotes, which the normal freedesktop.org pkg-config does
2940         // support. See https://man.openbsd.org/pkg-config.1
2941         tg.tempFile("foo.pc", `
2942 Name: foo
2943 Description: The foo library
2944 Version: 1.0.0
2945 Cflags: -Dhello=10 -Dworld=+32 -DDEFINED_FROM_PKG_CONFIG=hello\ world
2946 `)
2947         tg.tempFile("foo.go", `package main
2948
2949 /*
2950 #cgo pkg-config: foo
2951 int value() {
2952         return DEFINED_FROM_PKG_CONFIG;
2953 }
2954 */
2955 import "C"
2956 import "os"
2957
2958 func main() {
2959         if C.value() != 42 {
2960                 println("value() =", C.value(), "wanted 42")
2961                 os.Exit(1)
2962         }
2963 }
2964 `)
2965         tg.setenv("PKG_CONFIG_PATH", tg.path("."))
2966         tg.run("run", tg.path("foo.go"))
2967 }
2968
2969 // "go test -c -test.bench=XXX errors" should not hang.
2970 // "go test -c" should also produce reproducible binaries.
2971 // "go test -c" should also appear to write a new binary every time,
2972 // even if it's really just updating the mtime on an existing up-to-date binary.
2973 func TestIssue6480(t *testing.T) {
2974         skipIfGccgo(t, "gccgo has no standard packages")
2975         tooSlow(t)
2976         tg := testgo(t)
2977         defer tg.cleanup()
2978         // TODO: tg.parallel()
2979         tg.makeTempdir()
2980         tg.cd(tg.path("."))
2981         tg.run("test", "-c", "-test.bench=XXX", "errors")
2982         tg.run("test", "-c", "-o", "errors2.test", "errors")
2983
2984         data1, err := ioutil.ReadFile("errors.test" + exeSuffix)
2985         tg.must(err)
2986         data2, err := ioutil.ReadFile("errors2.test") // no exeSuffix because -o above doesn't have it
2987         tg.must(err)
2988         if !bytes.Equal(data1, data2) {
2989                 t.Fatalf("go test -c errors produced different binaries when run twice")
2990         }
2991
2992         start := time.Now()
2993         tg.run("test", "-x", "-c", "-test.bench=XXX", "errors")
2994         tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
2995         info, err := os.Stat("errors.test" + exeSuffix)
2996         if err != nil {
2997                 t.Fatal(err)
2998         }
2999         start = truncateLike(start, info.ModTime())
3000         if info.ModTime().Before(start) {
3001                 t.Fatalf("mtime of errors.test predates test -c command (%v < %v)", info.ModTime(), start)
3002         }
3003
3004         start = time.Now()
3005         tg.run("test", "-x", "-c", "-o", "errors2.test", "errors")
3006         tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly relinked up-to-date test binary")
3007         info, err = os.Stat("errors2.test")
3008         if err != nil {
3009                 t.Fatal(err)
3010         }
3011         start = truncateLike(start, info.ModTime())
3012         if info.ModTime().Before(start) {
3013                 t.Fatalf("mtime of errors2.test predates test -c command (%v < %v)", info.ModTime(), start)
3014         }
3015 }
3016
3017 // truncateLike returns the result of truncating t to the apparent precision of p.
3018 func truncateLike(t, p time.Time) time.Time {
3019         nano := p.UnixNano()
3020         d := 1 * time.Nanosecond
3021         for nano%int64(d) == 0 && d < 1*time.Second {
3022                 d *= 10
3023         }
3024         for nano%int64(d) == 0 && d < 2*time.Second {
3025                 d *= 2
3026         }
3027         return t.Truncate(d)
3028 }
3029
3030 // cmd/cgo: undefined reference when linking a C-library using gccgo
3031 func TestIssue7573(t *testing.T) {
3032         if !canCgo {
3033                 t.Skip("skipping because cgo not enabled")
3034         }
3035         testenv.MustHaveExecPath(t, "gccgo")
3036
3037         tg := testgo(t)
3038         defer tg.cleanup()
3039         tg.parallel()
3040         tg.tempFile("src/cgoref/cgoref.go", `
3041 package main
3042 // #cgo LDFLAGS: -L alibpath -lalib
3043 // void f(void) {}
3044 import "C"
3045
3046 func main() { C.f() }`)
3047         tg.setenv("GOPATH", tg.path("."))
3048         tg.run("build", "-n", "-compiler", "gccgo", "cgoref")
3049         tg.grepStderr(`gccgo.*\-L [^ ]*alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`)
3050 }
3051
3052 func TestListTemplateContextFunction(t *testing.T) {
3053         t.Parallel()
3054         for _, tt := range []struct {
3055                 v    string
3056                 want string
3057         }{
3058                 {"GOARCH", runtime.GOARCH},
3059                 {"GOOS", runtime.GOOS},
3060                 {"GOROOT", filepath.Clean(runtime.GOROOT())},
3061                 {"GOPATH", os.Getenv("GOPATH")},
3062                 {"CgoEnabled", ""},
3063                 {"UseAllFiles", ""},
3064                 {"Compiler", ""},
3065                 {"BuildTags", ""},
3066                 {"ReleaseTags", ""},
3067                 {"InstallSuffix", ""},
3068         } {
3069                 tt := tt
3070                 t.Run(tt.v, func(t *testing.T) {
3071                         tg := testgo(t)
3072                         tg.parallel()
3073                         defer tg.cleanup()
3074                         tmpl := "{{context." + tt.v + "}}"
3075                         tg.run("list", "-f", tmpl)
3076                         if tt.want == "" {
3077                                 return
3078                         }
3079                         if got := strings.TrimSpace(tg.getStdout()); got != tt.want {
3080                                 t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want)
3081                         }
3082                 })
3083         }
3084 }
3085
3086 // cmd/go: "go test" should fail if package does not build
3087 func TestIssue7108(t *testing.T) {
3088         tg := testgo(t)
3089         defer tg.cleanup()
3090         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3091         tg.runFail("test", "notest")
3092 }
3093
3094 // cmd/go: go test -a foo does not rebuild regexp.
3095 func TestIssue6844(t *testing.T) {
3096         if testing.Short() {
3097                 t.Skip("don't rebuild the standard library in short mode")
3098         }
3099
3100         tg := testgo(t)
3101         defer tg.cleanup()
3102         tg.creatingTemp("deps.test" + exeSuffix)
3103         tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go")
3104         tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp")
3105 }
3106
3107 func TestBuildDashIInstallsDependencies(t *testing.T) {
3108         tooSlow(t)
3109
3110         tg := testgo(t)
3111         defer tg.cleanup()
3112         tg.parallel()
3113         tg.tempFile("src/x/y/foo/foo.go", `package foo
3114                 func F() {}`)
3115         tg.tempFile("src/x/y/bar/bar.go", `package bar
3116                 import "x/y/foo"
3117                 func F() { foo.F() }`)
3118         tg.setenv("GOPATH", tg.path("."))
3119
3120         // don't let build -i overwrite runtime
3121         tg.wantNotStale("runtime", "", "must be non-stale before build -i")
3122
3123         checkbar := func(desc string) {
3124                 tg.run("build", "-v", "-i", "x/y/bar")
3125                 tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo")
3126                 tg.run("build", "-v", "-i", "x/y/bar")
3127                 tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo")
3128         }
3129         checkbar("pkg")
3130
3131         tg.creatingTemp("bar" + exeSuffix)
3132         tg.sleep()
3133         tg.tempFile("src/x/y/foo/foo.go", `package foo
3134                 func F() { F() }`)
3135         tg.tempFile("src/x/y/bar/bar.go", `package main
3136                 import "x/y/foo"
3137                 func main() { foo.F() }`)
3138         checkbar("cmd")
3139 }
3140
3141 func TestGoBuildTestOnly(t *testing.T) {
3142         tg := testgo(t)
3143         defer tg.cleanup()
3144         tg.makeTempdir()
3145         tg.setenv("GOPATH", tg.path("."))
3146         tg.tempFile("src/testonly/t_test.go", `package testonly`)
3147         tg.tempFile("src/testonly2/t.go", `package testonly2`)
3148         tg.cd(tg.path("src"))
3149
3150         // Named explicitly, test-only packages should be reported as unbuildable/uninstallable,
3151         // even if there is a wildcard also matching.
3152         tg.runFail("build", "testonly", "testonly...")
3153         tg.grepStderr("no non-test Go files in", "go build ./xtestonly produced unexpected error")
3154         tg.runFail("install", "./testonly")
3155         tg.grepStderr("no non-test Go files in", "go install ./testonly produced unexpected error")
3156
3157         // Named through a wildcards, the test-only packages should be silently ignored.
3158         tg.run("build", "testonly...")
3159         tg.run("install", "./testonly...")
3160 }
3161
3162 func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) {
3163         tg := testgo(t)
3164         defer tg.cleanup()
3165         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3166         tg.runFail("test", "-c", "testcycle/p3")
3167         tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error")
3168
3169         tg.runFail("test", "-c", "testcycle/q1")
3170         tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error")
3171 }
3172
3173 func TestGoTestFooTestWorks(t *testing.T) {
3174         tg := testgo(t)
3175         defer tg.cleanup()
3176         tg.run("test", "testdata/standalone_test.go")
3177 }
3178
3179 // Issue 22388
3180 func TestGoTestMainWithWrongSignature(t *testing.T) {
3181         tg := testgo(t)
3182         defer tg.cleanup()
3183         tg.runFail("test", "testdata/standalone_main_wrong_test.go")
3184         tg.grepStderr(`wrong signature for TestMain, must be: func TestMain\(m \*testing.M\)`, "detected wrong error message")
3185 }
3186
3187 func TestGoTestMainAsNormalTest(t *testing.T) {
3188         tg := testgo(t)
3189         defer tg.cleanup()
3190         tg.run("test", "testdata/standalone_main_normal_test.go")
3191         tg.grepBoth(okPattern, "go test did not say ok")
3192 }
3193
3194 func TestGoTestMainTwice(t *testing.T) {
3195         if testing.Short() {
3196                 t.Skip("Skipping in short mode")
3197         }
3198         tg := testgo(t)
3199         defer tg.cleanup()
3200         tg.makeTempdir()
3201         tg.setenv("GOCACHE", tg.tempdir)
3202         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3203         tg.run("test", "-v", "multimain")
3204         if strings.Count(tg.getStdout(), "notwithstanding") != 2 {
3205                 t.Fatal("tests did not run twice")
3206         }
3207 }
3208
3209 func TestGoTestFlagsAfterPackage(t *testing.T) {
3210         tooSlow(t)
3211         tg := testgo(t)
3212         defer tg.cleanup()
3213         tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags.
3214         tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags.
3215 }
3216
3217 func TestGoTestXtestonlyWorks(t *testing.T) {
3218         tg := testgo(t)
3219         defer tg.cleanup()
3220         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3221         tg.run("clean", "-i", "xtestonly")
3222         tg.run("test", "xtestonly")
3223 }
3224
3225 func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) {
3226         tg := testgo(t)
3227         defer tg.cleanup()
3228         tg.run("test", "-v", "./testdata/norunexample")
3229         tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built")
3230 }
3231
3232 func TestGoGenerateHandlesSimpleCommand(t *testing.T) {
3233         if runtime.GOOS == "windows" {
3234                 t.Skip("skipping because windows has no echo command")
3235         }
3236
3237         tg := testgo(t)
3238         defer tg.cleanup()
3239         tg.run("generate", "./testdata/generate/test1.go")
3240         tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output")
3241 }
3242
3243 func TestGoGenerateHandlesCommandAlias(t *testing.T) {
3244         if runtime.GOOS == "windows" {
3245                 t.Skip("skipping because windows has no echo command")
3246         }
3247
3248         tg := testgo(t)
3249         defer tg.cleanup()
3250         tg.run("generate", "./testdata/generate/test2.go")
3251         tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output")
3252 }
3253
3254 func TestGoGenerateVariableSubstitution(t *testing.T) {
3255         if runtime.GOOS == "windows" {
3256                 t.Skip("skipping because windows has no echo command")
3257         }
3258
3259         tg := testgo(t)
3260         defer tg.cleanup()
3261         tg.run("generate", "./testdata/generate/test3.go")
3262         tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output")
3263 }
3264
3265 func TestGoGenerateRunFlag(t *testing.T) {
3266         if runtime.GOOS == "windows" {
3267                 t.Skip("skipping because windows has no echo command")
3268         }
3269
3270         tg := testgo(t)
3271         defer tg.cleanup()
3272         tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go")
3273         tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes")
3274         tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no")
3275 }
3276
3277 func TestGoGenerateEnv(t *testing.T) {
3278         switch runtime.GOOS {
3279         case "plan9", "windows":
3280                 t.Skipf("skipping because %s does not have the env command", runtime.GOOS)
3281         }
3282         tg := testgo(t)
3283         defer tg.cleanup()
3284         tg.parallel()
3285         tg.tempFile("env.go", "package main\n\n//go:generate env")
3286         tg.run("generate", tg.path("env.go"))
3287         for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} {
3288                 tg.grepStdout("^"+v+"=", "go generate environment missing "+v)
3289         }
3290 }
3291
3292 func TestGoGenerateXTestPkgName(t *testing.T) {
3293         if runtime.GOOS == "windows" {
3294                 t.Skip("skipping because windows has no echo command")
3295         }
3296
3297         tg := testgo(t)
3298         defer tg.cleanup()
3299         tg.parallel()
3300         tg.tempFile("env_test.go", "package main_test\n\n//go:generate echo $GOPACKAGE")
3301         tg.run("generate", tg.path("env_test.go"))
3302         want := "main_test"
3303         if got := strings.TrimSpace(tg.getStdout()); got != want {
3304                 t.Errorf("go generate in XTest file got package name %q; want %q", got, want)
3305         }
3306 }
3307
3308 func TestGoGenerateBadImports(t *testing.T) {
3309         if runtime.GOOS == "windows" {
3310                 t.Skip("skipping because windows has no echo command")
3311         }
3312
3313         // This package has an invalid import causing an import cycle,
3314         // but go generate is supposed to still run.
3315         tg := testgo(t)
3316         defer tg.cleanup()
3317         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3318         tg.run("generate", "gencycle")
3319         tg.grepStdout("hello world", "go generate gencycle did not run generator")
3320 }
3321
3322 func TestGoGetCustomDomainWildcard(t *testing.T) {
3323         testenv.MustHaveExternalNetwork(t)
3324         testenv.MustHaveExecPath(t, "git")
3325
3326         tg := testgo(t)
3327         defer tg.cleanup()
3328         tg.makeTempdir()
3329         tg.setenv("GOPATH", tg.path("."))
3330         tg.run("get", "-u", "rsc.io/pdf/...")
3331         tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd")
3332 }
3333
3334 func TestGoGetInternalWildcard(t *testing.T) {
3335         testenv.MustHaveExternalNetwork(t)
3336         testenv.MustHaveExecPath(t, "git")
3337
3338         tg := testgo(t)
3339         defer tg.cleanup()
3340         tg.makeTempdir()
3341         tg.setenv("GOPATH", tg.path("."))
3342         // used to fail with errors about internal packages
3343         tg.run("get", "github.com/rsc/go-get-issue-11960/...")
3344 }
3345
3346 func TestGoVetWithExternalTests(t *testing.T) {
3347         tg := testgo(t)
3348         defer tg.cleanup()
3349         tg.makeTempdir()
3350         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3351         tg.runFail("vet", "vetpkg")
3352         tg.grepBoth("Printf", "go vet vetpkg did not find missing argument for Printf")
3353 }
3354
3355 func TestGoVetWithTags(t *testing.T) {
3356         tg := testgo(t)
3357         defer tg.cleanup()
3358         tg.makeTempdir()
3359         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3360         tg.runFail("vet", "-tags", "tagtest", "vetpkg")
3361         tg.grepBoth(`c\.go.*Printf`, "go vet vetpkg did not run scan tagged file")
3362 }
3363
3364 func TestGoVetWithFlagsOn(t *testing.T) {
3365         tg := testgo(t)
3366         defer tg.cleanup()
3367         tg.makeTempdir()
3368         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3369         tg.runFail("vet", "-printf", "vetpkg")
3370         tg.grepBoth("Printf", "go vet -printf vetpkg did not find missing argument for Printf")
3371 }
3372
3373 func TestGoVetWithFlagsOff(t *testing.T) {
3374         tg := testgo(t)
3375         defer tg.cleanup()
3376         tg.makeTempdir()
3377         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3378         tg.run("vet", "-printf=false", "vetpkg")
3379 }
3380
3381 // Issue 23395.
3382 func TestGoVetWithOnlyTestFiles(t *testing.T) {
3383         tg := testgo(t)
3384         defer tg.cleanup()
3385         tg.parallel()
3386         tg.tempFile("src/p/p_test.go", "package p; import \"testing\"; func TestMe(*testing.T) {}")
3387         tg.setenv("GOPATH", tg.path("."))
3388         tg.run("vet", "p")
3389 }
3390
3391 // Issue 24193.
3392 func TestVetWithOnlyCgoFiles(t *testing.T) {
3393         if !canCgo {
3394                 t.Skip("skipping because cgo not enabled")
3395         }
3396         tooSlow(t)
3397
3398         tg := testgo(t)
3399         defer tg.cleanup()
3400         tg.parallel()
3401         tg.tempFile("src/p/p.go", "package p; import \"C\"; func F() {}")
3402         tg.setenv("GOPATH", tg.path("."))
3403         tg.run("vet", "p")
3404 }
3405
3406 // Issue 9767, 19769.
3407 func TestGoGetDotSlashDownload(t *testing.T) {
3408         testenv.MustHaveExternalNetwork(t)
3409         testenv.MustHaveExecPath(t, "git")
3410
3411         tg := testgo(t)
3412         defer tg.cleanup()
3413         tg.tempDir("src/rsc.io")
3414         tg.setenv("GOPATH", tg.path("."))
3415         tg.cd(tg.path("src/rsc.io"))
3416         tg.run("get", "./pprof_mac_fix")
3417 }
3418
3419 // Test that you cannot import a main package.
3420 // See golang.org/issue/4210 and golang.org/issue/17475.
3421 func TestImportMain(t *testing.T) {
3422         tooSlow(t)
3423
3424         tg := testgo(t)
3425         tg.parallel()
3426         defer tg.cleanup()
3427
3428         // Importing package main from that package main's test should work.
3429         tg.tempFile("src/x/main.go", `package main
3430                 var X int
3431                 func main() {}`)
3432         tg.tempFile("src/x/main_test.go", `package main_test
3433                 import xmain "x"
3434                 import "testing"
3435                 var _ = xmain.X
3436                 func TestFoo(t *testing.T) {}
3437         `)
3438         tg.setenv("GOPATH", tg.path("."))
3439         tg.creatingTemp("x" + exeSuffix)
3440         tg.run("build", "x")
3441         tg.run("test", "x")
3442
3443         // Importing package main from another package should fail.
3444         tg.tempFile("src/p1/p.go", `package p1
3445                 import xmain "x"
3446                 var _ = xmain.X
3447         `)
3448         tg.runFail("build", "p1")
3449         tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3450
3451         // ... even in that package's test.
3452         tg.tempFile("src/p2/p.go", `package p2
3453         `)
3454         tg.tempFile("src/p2/p_test.go", `package p2
3455                 import xmain "x"
3456                 import "testing"
3457                 var _ = xmain.X
3458                 func TestFoo(t *testing.T) {}
3459         `)
3460         tg.run("build", "p2")
3461         tg.runFail("test", "p2")
3462         tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3463
3464         // ... even if that package's test is an xtest.
3465         tg.tempFile("src/p3/p.go", `package p
3466         `)
3467         tg.tempFile("src/p3/p_test.go", `package p_test
3468                 import xmain "x"
3469                 import "testing"
3470                 var _ = xmain.X
3471                 func TestFoo(t *testing.T) {}
3472         `)
3473         tg.run("build", "p3")
3474         tg.runFail("test", "p3")
3475         tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3476
3477         // ... even if that package is a package main
3478         tg.tempFile("src/p4/p.go", `package main
3479         func main() {}
3480         `)
3481         tg.tempFile("src/p4/p_test.go", `package main
3482                 import xmain "x"
3483                 import "testing"
3484                 var _ = xmain.X
3485                 func TestFoo(t *testing.T) {}
3486         `)
3487         tg.creatingTemp("p4" + exeSuffix)
3488         tg.run("build", "p4")
3489         tg.runFail("test", "p4")
3490         tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3491
3492         // ... even if that package is a package main using an xtest.
3493         tg.tempFile("src/p5/p.go", `package main
3494         func main() {}
3495         `)
3496         tg.tempFile("src/p5/p_test.go", `package main_test
3497                 import xmain "x"
3498                 import "testing"
3499                 var _ = xmain.X
3500                 func TestFoo(t *testing.T) {}
3501         `)
3502         tg.creatingTemp("p5" + exeSuffix)
3503         tg.run("build", "p5")
3504         tg.runFail("test", "p5")
3505         tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main")
3506 }
3507
3508 // Test that you cannot use a local import in a package
3509 // accessed by a non-local import (found in a GOPATH/GOROOT).
3510 // See golang.org/issue/17475.
3511 func TestImportLocal(t *testing.T) {
3512         tooSlow(t)
3513
3514         tg := testgo(t)
3515         tg.parallel()
3516         defer tg.cleanup()
3517
3518         tg.tempFile("src/dir/x/x.go", `package x
3519                 var X int
3520         `)
3521         tg.setenv("GOPATH", tg.path("."))
3522         tg.run("build", "dir/x")
3523
3524         // Ordinary import should work.
3525         tg.tempFile("src/dir/p0/p.go", `package p0
3526                 import "dir/x"
3527                 var _ = x.X
3528         `)
3529         tg.run("build", "dir/p0")
3530
3531         // Relative import should not.
3532         tg.tempFile("src/dir/p1/p.go", `package p1
3533                 import "../x"
3534                 var _ = x.X
3535         `)
3536         tg.runFail("build", "dir/p1")
3537         tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3538
3539         // ... even in a test.
3540         tg.tempFile("src/dir/p2/p.go", `package p2
3541         `)
3542         tg.tempFile("src/dir/p2/p_test.go", `package p2
3543                 import "../x"
3544                 import "testing"
3545                 var _ = x.X
3546                 func TestFoo(t *testing.T) {}
3547         `)
3548         tg.run("build", "dir/p2")
3549         tg.runFail("test", "dir/p2")
3550         tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3551
3552         // ... even in an xtest.
3553         tg.tempFile("src/dir/p2/p_test.go", `package p2_test
3554                 import "../x"
3555                 import "testing"
3556                 var _ = x.X
3557                 func TestFoo(t *testing.T) {}
3558         `)
3559         tg.run("build", "dir/p2")
3560         tg.runFail("test", "dir/p2")
3561         tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3562
3563         // Relative import starting with ./ should not work either.
3564         tg.tempFile("src/dir/d.go", `package dir
3565                 import "./x"
3566                 var _ = x.X
3567         `)
3568         tg.runFail("build", "dir")
3569         tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3570
3571         // ... even in a test.
3572         tg.tempFile("src/dir/d.go", `package dir
3573         `)
3574         tg.tempFile("src/dir/d_test.go", `package dir
3575                 import "./x"
3576                 import "testing"
3577                 var _ = x.X
3578                 func TestFoo(t *testing.T) {}
3579         `)
3580         tg.run("build", "dir")
3581         tg.runFail("test", "dir")
3582         tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3583
3584         // ... even in an xtest.
3585         tg.tempFile("src/dir/d_test.go", `package dir_test
3586                 import "./x"
3587                 import "testing"
3588                 var _ = x.X
3589                 func TestFoo(t *testing.T) {}
3590         `)
3591         tg.run("build", "dir")
3592         tg.runFail("test", "dir")
3593         tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3594
3595         // Relative import plain ".." should not work.
3596         tg.tempFile("src/dir/x/y/y.go", `package dir
3597                 import ".."
3598                 var _ = x.X
3599         `)
3600         tg.runFail("build", "dir/x/y")
3601         tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3602
3603         // ... even in a test.
3604         tg.tempFile("src/dir/x/y/y.go", `package y
3605         `)
3606         tg.tempFile("src/dir/x/y/y_test.go", `package y
3607                 import ".."
3608                 import "testing"
3609                 var _ = x.X
3610                 func TestFoo(t *testing.T) {}
3611         `)
3612         tg.run("build", "dir/x/y")
3613         tg.runFail("test", "dir/x/y")
3614         tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3615
3616         // ... even in an x test.
3617         tg.tempFile("src/dir/x/y/y_test.go", `package y_test
3618                 import ".."
3619                 import "testing"
3620                 var _ = x.X
3621                 func TestFoo(t *testing.T) {}
3622         `)
3623         tg.run("build", "dir/x/y")
3624         tg.runFail("test", "dir/x/y")
3625         tg.grepStderr("local import.*in non-local package", "did not diagnose local import")
3626
3627         // Relative import "." should not work.
3628         tg.tempFile("src/dir/x/xx.go", `package x
3629                 import "."
3630                 var _ = x.X
3631         `)
3632         tg.runFail("build", "dir/x")
3633         tg.grepStderr("cannot import current directory", "did not diagnose import current directory")
3634
3635         // ... even in a test.
3636         tg.tempFile("src/dir/x/xx.go", `package x
3637         `)
3638         tg.tempFile("src/dir/x/xx_test.go", `package x
3639                 import "."
3640                 import "testing"
3641                 var _ = x.X
3642                 func TestFoo(t *testing.T) {}
3643         `)
3644         tg.run("build", "dir/x")
3645         tg.runFail("test", "dir/x")
3646         tg.grepStderr("cannot import current directory", "did not diagnose import current directory")
3647
3648         // ... even in an xtest.
3649         tg.tempFile("src/dir/x/xx.go", `package x
3650         `)
3651         tg.tempFile("src/dir/x/xx_test.go", `package x_test
3652                 import "."
3653                 import "testing"
3654                 var _ = x.X
3655                 func TestFoo(t *testing.T) {}
3656         `)
3657         tg.run("build", "dir/x")
3658         tg.runFail("test", "dir/x")
3659         tg.grepStderr("cannot import current directory", "did not diagnose import current directory")
3660 }
3661
3662 func TestGoGetInsecure(t *testing.T) {
3663         test := func(t *testing.T, modules bool) {
3664                 testenv.MustHaveExternalNetwork(t)
3665                 testenv.MustHaveExecPath(t, "git")
3666
3667                 tg := testgo(t)
3668                 defer tg.cleanup()
3669                 tg.makeTempdir()
3670                 tg.failSSH()
3671
3672                 if modules {
3673                         tg.setenv("GOPATH", tg.path("gp"))
3674                         tg.tempFile("go.mod", "module m")
3675                         tg.cd(tg.path("."))
3676                         tg.setenv("GO111MODULE", "on")
3677                         tg.setenv("GOPROXY", "")
3678                 } else {
3679                         tg.setenv("GOPATH", tg.path("."))
3680                         tg.setenv("GO111MODULE", "off")
3681                 }
3682
3683                 const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3684
3685                 // Try go get -d of HTTP-only repo (should fail).
3686                 tg.runFail("get", "-d", repo)
3687
3688                 // Try again with -insecure (should succeed).
3689                 tg.run("get", "-d", "-insecure", repo)
3690
3691                 // Try updating without -insecure (should fail).
3692                 tg.runFail("get", "-d", "-u", "-f", repo)
3693
3694                 if modules {
3695                         tg.run("list", "-m", "...")
3696                         tg.grepStdout("insecure.go-get-issue", "should find insecure module")
3697                 }
3698         }
3699
3700         t.Run("gopath", func(t *testing.T) { test(t, false) })
3701         t.Run("modules", func(t *testing.T) { test(t, true) })
3702 }
3703
3704 func TestGoGetUpdateInsecure(t *testing.T) {
3705         testenv.MustHaveExternalNetwork(t)
3706         testenv.MustHaveExecPath(t, "git")
3707
3708         tg := testgo(t)
3709         defer tg.cleanup()
3710         tg.makeTempdir()
3711         tg.setenv("GOPATH", tg.path("."))
3712
3713         const repo = "github.com/golang/example"
3714
3715         // Clone the repo via HTTP manually.
3716         cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
3717         if out, err := cmd.CombinedOutput(); err != nil {
3718                 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3719         }
3720
3721         // Update without -insecure should fail.
3722         // Update with -insecure should succeed.
3723         // We need -f to ignore import comments.
3724         const pkg = repo + "/hello"
3725         tg.runFail("get", "-d", "-u", "-f", pkg)
3726         tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
3727 }
3728
3729 func TestGoGetUpdateUnknownProtocol(t *testing.T) {
3730         testenv.MustHaveExternalNetwork(t)
3731         testenv.MustHaveExecPath(t, "git")
3732
3733         tg := testgo(t)
3734         defer tg.cleanup()
3735         tg.makeTempdir()
3736         tg.setenv("GOPATH", tg.path("."))
3737
3738         const repo = "github.com/golang/example"
3739
3740         // Clone the repo via HTTPS manually.
3741         repoDir := tg.path("src/" + repo)
3742         cmd := exec.Command("git", "clone", "-q", "https://"+repo, repoDir)
3743         if out, err := cmd.CombinedOutput(); err != nil {
3744                 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
3745         }
3746
3747         // Configure the repo to use a protocol unknown to cmd/go
3748         // that still actually works.
3749         cmd = exec.Command("git", "remote", "set-url", "origin", "xyz://"+repo)
3750         cmd.Dir = repoDir
3751         if out, err := cmd.CombinedOutput(); err != nil {
3752                 t.Fatalf("git remote set-url: %v\n%s", err, out)
3753         }
3754         cmd = exec.Command("git", "config", "--local", "url.https://github.com/.insteadOf", "xyz://github.com/")
3755         cmd.Dir = repoDir
3756         if out, err := cmd.CombinedOutput(); err != nil {
3757                 t.Fatalf("git config: %v\n%s", err, out)
3758         }
3759
3760         // We need -f to ignore import comments.
3761         tg.run("get", "-d", "-u", "-f", repo+"/hello")
3762 }
3763
3764 func TestGoGetInsecureCustomDomain(t *testing.T) {
3765         testenv.MustHaveExternalNetwork(t)
3766         testenv.MustHaveExecPath(t, "git")
3767
3768         tg := testgo(t)
3769         defer tg.cleanup()
3770         tg.makeTempdir()
3771         tg.setenv("GOPATH", tg.path("."))
3772
3773         const repo = "insecure.go-get-issue-15410.appspot.com/pkg/p"
3774         tg.runFail("get", "-d", repo)
3775         tg.run("get", "-d", "-insecure", repo)
3776 }
3777
3778 func TestGoRunDirs(t *testing.T) {
3779         tg := testgo(t)
3780         defer tg.cleanup()
3781         tg.cd("testdata/rundir")
3782         tg.runFail("run", "x.go", "sub/sub.go")
3783         tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
3784         tg.runFail("run", "sub/sub.go", "x.go")
3785         tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
3786 }
3787
3788 func TestGoInstallPkgdir(t *testing.T) {
3789         skipIfGccgo(t, "gccgo has no standard packages")
3790         tooSlow(t)
3791
3792         tg := testgo(t)
3793         tg.parallel()
3794         defer tg.cleanup()
3795         tg.makeTempdir()
3796         pkg := tg.path(".")
3797         tg.run("install", "-pkgdir", pkg, "sync")
3798         tg.mustExist(filepath.Join(pkg, "sync.a"))
3799         tg.mustNotExist(filepath.Join(pkg, "sync/atomic.a"))
3800         tg.run("install", "-i", "-pkgdir", pkg, "sync")
3801         tg.mustExist(filepath.Join(pkg, "sync.a"))
3802         tg.mustExist(filepath.Join(pkg, "sync/atomic.a"))
3803 }
3804
3805 func TestGoTestRaceInstallCgo(t *testing.T) {
3806         if !canRace {
3807                 t.Skip("skipping because race detector not supported")
3808         }
3809
3810         // golang.org/issue/10500.
3811         // This used to install a race-enabled cgo.
3812         tg := testgo(t)
3813         defer tg.cleanup()
3814         tg.run("tool", "-n", "cgo")
3815         cgo := strings.TrimSpace(tg.stdout.String())
3816         old, err := os.Stat(cgo)
3817         tg.must(err)
3818         tg.run("test", "-race", "-i", "runtime/race")
3819         new, err := os.Stat(cgo)
3820         tg.must(err)
3821         if !new.ModTime().Equal(old.ModTime()) {
3822                 t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
3823         }
3824 }
3825
3826 func TestGoTestRaceFailures(t *testing.T) {
3827         tooSlow(t)
3828
3829         if !canRace {
3830                 t.Skip("skipping because race detector not supported")
3831         }
3832
3833         tg := testgo(t)
3834         tg.parallel()
3835         defer tg.cleanup()
3836         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3837
3838         tg.run("test", "testrace")
3839
3840         tg.runFail("test", "-race", "testrace")
3841         tg.grepStdout("FAIL: TestRace", "TestRace did not fail")
3842         tg.grepBothNot("PASS", "something passed")
3843
3844         tg.runFail("test", "-race", "testrace", "-run", "XXX", "-bench", ".")
3845         tg.grepStdout("FAIL: BenchmarkRace", "BenchmarkRace did not fail")
3846         tg.grepBothNot("PASS", "something passed")
3847 }
3848
3849 func TestGoTestImportErrorStack(t *testing.T) {
3850         const out = `package testdep/p1 (test)
3851         imports testdep/p2
3852         imports testdep/p3: build constraints exclude all Go files `
3853
3854         tg := testgo(t)
3855         defer tg.cleanup()
3856         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
3857         tg.runFail("test", "testdep/p1")
3858         if !strings.Contains(tg.stderr.String(), out) {
3859                 t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String())
3860         }
3861 }
3862
3863 func TestGoGetUpdate(t *testing.T) {
3864         // golang.org/issue/9224.
3865         // The recursive updating was trying to walk to
3866         // former dependencies, not current ones.
3867
3868         testenv.MustHaveExternalNetwork(t)
3869         testenv.MustHaveExecPath(t, "git")
3870
3871         tg := testgo(t)
3872         defer tg.cleanup()
3873         tg.makeTempdir()
3874         tg.setenv("GOPATH", tg.path("."))
3875
3876         rewind := func() {
3877                 tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
3878                 cmd := exec.Command("git", "reset", "--hard", "HEAD~")
3879                 cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
3880                 out, err := cmd.CombinedOutput()
3881                 if err != nil {
3882                         t.Fatalf("git: %v\n%s", err, out)
3883                 }
3884         }
3885
3886         rewind()
3887         tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3888
3889         // Again with -d -u.
3890         rewind()
3891         tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
3892 }
3893
3894 // Issue #20512.
3895 func TestGoGetRace(t *testing.T) {
3896         testenv.MustHaveExternalNetwork(t)
3897         testenv.MustHaveExecPath(t, "git")
3898         if !canRace {
3899                 t.Skip("skipping because race detector not supported")
3900         }
3901
3902         tg := testgo(t)
3903         defer tg.cleanup()
3904         tg.makeTempdir()
3905         tg.setenv("GOPATH", tg.path("."))
3906         tg.run("get", "-race", "github.com/rsc/go-get-issue-9224-cmd")
3907 }
3908
3909 func TestGoGetDomainRoot(t *testing.T) {
3910         // golang.org/issue/9357.
3911         // go get foo.io (not foo.io/subdir) was not working consistently.
3912
3913         testenv.MustHaveExternalNetwork(t)
3914         testenv.MustHaveExecPath(t, "git")
3915
3916         tg := testgo(t)
3917         defer tg.cleanup()
3918         tg.makeTempdir()
3919         tg.setenv("GOPATH", tg.path("."))
3920
3921         // go-get-issue-9357.appspot.com is running
3922         // the code at github.com/rsc/go-get-issue-9357,
3923         // a trivial Go on App Engine app that serves a
3924         // <meta> tag for the domain root.
3925         tg.run("get", "-d", "go-get-issue-9357.appspot.com")
3926         tg.run("get", "go-get-issue-9357.appspot.com")
3927         tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3928
3929         tg.must(robustio.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3930         tg.run("get", "go-get-issue-9357.appspot.com")
3931
3932         tg.must(robustio.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
3933         tg.run("get", "-u", "go-get-issue-9357.appspot.com")
3934 }
3935
3936 func TestGoInstallShadowedGOPATH(t *testing.T) {
3937         // golang.org/issue/3652.
3938         // go get foo.io (not foo.io/subdir) was not working consistently.
3939
3940         testenv.MustHaveExternalNetwork(t)
3941
3942         tg := testgo(t)
3943         defer tg.cleanup()
3944         tg.makeTempdir()
3945         tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
3946
3947         tg.tempDir("gopath1/src/test")
3948         tg.tempDir("gopath2/src/test")
3949         tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
3950
3951         tg.cd(tg.path("gopath2/src/test"))
3952         tg.runFail("install")
3953         tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
3954 }
3955
3956 func TestGoBuildGOPATHOrder(t *testing.T) {
3957         // golang.org/issue/14176#issuecomment-179895769
3958         // golang.org/issue/14192
3959         // -I arguments to compiler could end up not in GOPATH order,
3960         // leading to unexpected import resolution in the compiler.
3961         // This is still not a complete fix (see golang.org/issue/14271 and next test)
3962         // but it is clearly OK and enough to fix both of the two reported
3963         // instances of the underlying problem. It will have to do for now.
3964
3965         tg := testgo(t)
3966         defer tg.cleanup()
3967         tg.makeTempdir()
3968         tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2"))
3969
3970         tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3971         tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3972         tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3973         tg.tempFile("p1/src/bar/bar.go", `
3974                 package bar
3975                 import _ "baz"
3976                 import _ "foo"
3977         `)
3978
3979         tg.run("install", "-x", "bar")
3980 }
3981
3982 func TestGoBuildGOPATHOrderBroken(t *testing.T) {
3983         // This test is known not to work.
3984         // See golang.org/issue/14271.
3985         t.Skip("golang.org/issue/14271")
3986
3987         tg := testgo(t)
3988         defer tg.cleanup()
3989         tg.makeTempdir()
3990
3991         tg.tempFile("p1/src/foo/foo.go", "package foo\n")
3992         tg.tempFile("p2/src/baz/baz.go", "package baz\n")
3993         tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n")
3994         tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n")
3995         tg.tempFile("p1/src/bar/bar.go", `
3996                 package bar
3997                 import _ "baz"
3998                 import _ "foo"
3999         `)
4000
4001         colon := string(filepath.ListSeparator)
4002         tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2"))
4003         tg.run("install", "-x", "bar")
4004
4005         tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1"))
4006         tg.run("install", "-x", "bar")
4007 }
4008
4009 func TestIssue11709(t *testing.T) {
4010         tg := testgo(t)
4011         defer tg.cleanup()
4012         tg.tempFile("run.go", `
4013                 package main
4014                 import "os"
4015                 func main() {
4016                         if os.Getenv("TERM") != "" {
4017                                 os.Exit(1)
4018                         }
4019                 }`)
4020         tg.unsetenv("TERM")
4021         tg.run("run", tg.path("run.go"))
4022 }
4023
4024 func TestIssue12096(t *testing.T) {
4025         tg := testgo(t)
4026         defer tg.cleanup()
4027         tg.tempFile("test_test.go", `
4028                 package main
4029                 import ("os"; "testing")
4030                 func TestEnv(t *testing.T) {
4031                         if os.Getenv("TERM") != "" {
4032                                 t.Fatal("TERM is set")
4033                         }
4034                 }`)
4035         tg.unsetenv("TERM")
4036         tg.run("test", tg.path("test_test.go"))
4037 }
4038
4039 func TestGoBuildOutput(t *testing.T) {
4040         skipIfGccgo(t, "gccgo has no standard packages")
4041         tooSlow(t)
4042         tg := testgo(t)
4043         defer tg.cleanup()
4044
4045         tg.makeTempdir()
4046         tg.cd(tg.path("."))
4047
4048         nonExeSuffix := ".exe"
4049         if exeSuffix == ".exe" {
4050                 nonExeSuffix = ""
4051         }
4052
4053         tg.tempFile("x.go", "package main\nfunc main(){}\n")
4054         tg.run("build", "x.go")
4055         tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
4056         tg.must(os.Remove(tg.path("x" + exeSuffix)))
4057         tg.mustNotExist("x" + nonExeSuffix)
4058
4059         tg.run("build", "-o", "myprog", "x.go")
4060         tg.mustNotExist("x")
4061         tg.mustNotExist("x.exe")
4062         tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
4063         tg.mustNotExist("myprog.exe")
4064
4065         tg.tempFile("p.go", "package p\n")
4066         tg.run("build", "p.go")
4067         tg.mustNotExist("p")
4068         tg.mustNotExist("p.a")
4069         tg.mustNotExist("p.o")
4070         tg.mustNotExist("p.exe")
4071
4072         tg.run("build", "-o", "p.a", "p.go")
4073         tg.wantArchive("p.a")
4074
4075         tg.run("build", "cmd/gofmt")
4076         tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
4077         tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
4078         tg.mustNotExist("gofmt" + nonExeSuffix)
4079
4080         tg.run("build", "-o", "mygofmt", "cmd/gofmt")
4081         tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
4082         tg.mustNotExist("mygofmt.exe")
4083         tg.mustNotExist("gofmt")
4084         tg.mustNotExist("gofmt.exe")
4085
4086         tg.run("build", "sync/atomic")
4087         tg.mustNotExist("atomic")
4088         tg.mustNotExist("atomic.exe")
4089
4090         tg.run("build", "-o", "myatomic.a", "sync/atomic")
4091         tg.wantArchive("myatomic.a")
4092         tg.mustNotExist("atomic")
4093         tg.mustNotExist("atomic.a")
4094         tg.mustNotExist("atomic.exe")
4095
4096         tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
4097         tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
4098 }
4099
4100 func TestGoBuildARM(t *testing.T) {
4101         if testing.Short() {
4102                 t.Skip("skipping cross-compile in short mode")
4103         }
4104
4105         tg := testgo(t)
4106         defer tg.cleanup()
4107
4108         tg.makeTempdir()
4109         tg.cd(tg.path("."))
4110
4111         tg.setenv("GOARCH", "arm")
4112         tg.setenv("GOOS", "linux")
4113         tg.setenv("GOARM", "5")
4114         tg.tempFile("hello.go", `package main
4115                 func main() {}`)
4116         tg.run("build", "hello.go")
4117         tg.grepStderrNot("unable to find math.a", "did not build math.a correctly")
4118 }
4119
4120 // For issue 14337.
4121 func TestParallelTest(t *testing.T) {
4122         tooSlow(t)
4123         tg := testgo(t)
4124         tg.parallel()
4125         defer tg.cleanup()
4126         tg.makeTempdir()
4127         const testSrc = `package package_test
4128                 import (
4129                         "testing"
4130                 )
4131                 func TestTest(t *testing.T) {
4132                 }`
4133         tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1))
4134         tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1))
4135         tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1))
4136         tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1))
4137         tg.setenv("GOPATH", tg.path("."))
4138         tg.run("test", "-p=4", "p1", "p2", "p3", "p4")
4139 }
4140
4141 func TestCgoConsistentResults(t *testing.T) {
4142         tooSlow(t)
4143         if !canCgo {
4144                 t.Skip("skipping because cgo not enabled")
4145         }
4146         switch runtime.GOOS {
4147         case "solaris", "illumos":
4148                 testenv.SkipFlaky(t, 13247)
4149         }
4150
4151         tg := testgo(t)
4152         defer tg.cleanup()
4153         tg.parallel()
4154         tg.makeTempdir()
4155         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4156         exe1 := tg.path("cgotest1" + exeSuffix)
4157         exe2 := tg.path("cgotest2" + exeSuffix)
4158         tg.run("build", "-o", exe1, "cgotest")
4159         tg.run("build", "-x", "-o", exe2, "cgotest")
4160         b1, err := ioutil.ReadFile(exe1)
4161         tg.must(err)
4162         b2, err := ioutil.ReadFile(exe2)
4163         tg.must(err)
4164
4165         if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) {
4166                 t.Skip("skipping because C compiler does not support -fdebug-prefix-map")
4167         }
4168         if !bytes.Equal(b1, b2) {
4169                 t.Error("building cgotest twice did not produce the same output")
4170         }
4171 }
4172
4173 // Issue 14444: go get -u .../ duplicate loads errors
4174 func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) {
4175         testenv.MustHaveExternalNetwork(t)
4176
4177         tg := testgo(t)
4178         defer tg.cleanup()
4179         tg.makeTempdir()
4180         tg.setenv("GOPATH", tg.path("."))
4181         tg.run("get", "-u", ".../")
4182         tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache")
4183 }
4184
4185 // Issue 17119 more duplicate load errors
4186 func TestIssue17119(t *testing.T) {
4187         testenv.MustHaveExternalNetwork(t)
4188
4189         tg := testgo(t)
4190         defer tg.cleanup()
4191         tg.parallel()
4192         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4193         tg.runFail("build", "dupload")
4194         tg.grepBothNot("duplicate load|internal error", "internal error")
4195 }
4196
4197 func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) {
4198         tg := testgo(t)
4199         defer tg.cleanup()
4200         // TODO: tg.parallel()
4201         tg.runFail("test", "-run", "^$", "-bench", ".", "./testdata/src/benchfatal")
4202         tg.grepBothNot("^ok", "test passed unexpectedly")
4203         tg.grepBoth("FAIL.*benchfatal", "test did not run everything")
4204 }
4205
4206 func TestBinaryOnlyPackages(t *testing.T) {
4207         tooSlow(t)
4208
4209         tg := testgo(t)
4210         defer tg.cleanup()
4211         tg.parallel()
4212         tg.makeTempdir()
4213         tg.setenv("GOPATH", tg.path("."))
4214
4215         tg.tempFile("src/p1/p1.go", `//go:binary-only-package
4216
4217                 package p1
4218         `)
4219         tg.wantStale("p1", "binary-only packages are no longer supported", "p1 is binary-only, and this message should always be printed")
4220         tg.runFail("install", "p1")
4221         tg.grepStderr("binary-only packages are no longer supported", "did not report attempt to compile binary-only package")
4222
4223         tg.tempFile("src/p1/p1.go", `
4224                 package p1
4225                 import "fmt"
4226                 func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } }
4227         `)
4228         tg.run("install", "p1")
4229         os.Remove(tg.path("src/p1/p1.go"))
4230         tg.mustNotExist(tg.path("src/p1/p1.go"))
4231
4232         tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great
4233
4234                 package p2
4235                 import "p1"
4236                 func F() { p1.F(true) }
4237         `)
4238         tg.runFail("install", "p2")
4239         tg.grepStderr("no Go files", "did not complain about missing sources")
4240
4241         tg.tempFile("src/p1/missing.go", `//go:binary-only-package
4242
4243                 package p1
4244                 import _ "fmt"
4245                 func G()
4246         `)
4247         tg.wantStale("p1", "binary-only package", "should NOT want to rebuild p1 (first)")
4248         tg.runFail("install", "p2")
4249         tg.grepStderr("p1: binary-only packages are no longer supported", "did not report error for binary-only p1")
4250
4251         tg.run("list", "-deps", "-f", "{{.ImportPath}}: {{.BinaryOnly}}", "p2")
4252         tg.grepStdout("p1: true", "p1 not listed as BinaryOnly")
4253         tg.grepStdout("p2: false", "p2 listed as BinaryOnly")
4254 }
4255
4256 // Issue 16050 and 21884.
4257 func TestLinkSysoFiles(t *testing.T) {
4258         if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" {
4259                 t.Skip("not linux/amd64")
4260         }
4261
4262         tg := testgo(t)
4263         defer tg.cleanup()
4264         tg.parallel()
4265         tg.tempDir("src/syso")
4266         tg.tempFile("src/syso/a.syso", ``)
4267         tg.tempFile("src/syso/b.go", `package syso`)
4268         tg.setenv("GOPATH", tg.path("."))
4269
4270         // We should see the .syso file regardless of the setting of
4271         // CGO_ENABLED.
4272
4273         tg.setenv("CGO_ENABLED", "1")
4274         tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4275         tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1")
4276
4277         tg.setenv("CGO_ENABLED", "0")
4278         tg.run("list", "-f", "{{.SysoFiles}}", "syso")
4279         tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0")
4280
4281         tg.setenv("CGO_ENABLED", "1")
4282         tg.run("list", "-msan", "-f", "{{.SysoFiles}}", "syso")
4283         tg.grepStdoutNot("a.syso", "unexpected syso file with -msan")
4284 }
4285
4286 // Issue 16120.
4287 func TestGenerateUsesBuildContext(t *testing.T) {
4288         if runtime.GOOS == "windows" {
4289                 t.Skip("this test won't run under Windows")
4290         }
4291
4292         tg := testgo(t)
4293         defer tg.cleanup()
4294         tg.parallel()
4295         tg.tempDir("src/gen")
4296         tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n")
4297         tg.setenv("GOPATH", tg.path("."))
4298
4299         tg.setenv("GOOS", "linux")
4300         tg.setenv("GOARCH", "amd64")
4301         tg.run("generate", "gen")
4302         tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination")
4303
4304         tg.setenv("GOOS", "darwin")
4305         tg.setenv("GOARCH", "386")
4306         tg.run("generate", "gen")
4307         tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination")
4308 }
4309
4310 // Issue 14450: go get -u .../ tried to import not downloaded package
4311 func TestGoGetUpdateWithWildcard(t *testing.T) {
4312         testenv.MustHaveExternalNetwork(t)
4313         testenv.MustHaveExecPath(t, "git")
4314
4315         tg := testgo(t)
4316         defer tg.cleanup()
4317         tg.parallel()
4318         tg.makeTempdir()
4319         tg.setenv("GOPATH", tg.path("."))
4320         const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a"
4321         tg.run("get", aPkgImportPath)
4322         tg.runFail("get", "-u", ".../")
4323         tg.grepStderr("cannot find package.*d-dependency/e", "should have detected e missing")
4324
4325         // Even though get -u failed, the source for others should be downloaded.
4326         var expectedPkgPaths = []string{
4327                 "src/github.com/tmwh/go-get-issue-14450/b",
4328                 "src/github.com/tmwh/go-get-issue-14450-b-dependency/c",
4329                 "src/github.com/tmwh/go-get-issue-14450-b-dependency/d",
4330         }
4331
4332         for _, importPath := range expectedPkgPaths {
4333                 _, err := os.Stat(tg.path(importPath))
4334                 tg.must(err)
4335         }
4336         const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e"
4337         tg.mustNotExist(tg.path(notExpectedPkgPath))
4338 }
4339
4340 func TestGoEnv(t *testing.T) {
4341         tg := testgo(t)
4342         tg.parallel()
4343         defer tg.cleanup()
4344         tg.setenv("GOOS", "freebsd") // to avoid invalid pair errors
4345         tg.setenv("GOARCH", "arm")
4346         tg.run("env", "GOARCH")
4347         tg.grepStdout("^arm$", "GOARCH not honored")
4348
4349         tg.run("env", "GCCGO")
4350         tg.grepStdout(".", "GCCGO unexpectedly empty")
4351
4352         tg.run("env", "CGO_CFLAGS")
4353         tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty")
4354
4355         tg.setenv("CGO_CFLAGS", "-foobar")
4356         tg.run("env", "CGO_CFLAGS")
4357         tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored")
4358
4359         tg.setenv("CC", "gcc -fmust -fgo -ffaster")
4360         tg.run("env", "CC")
4361         tg.grepStdout("gcc", "CC not found")
4362         tg.run("env", "GOGCCFLAGS")
4363         tg.grepStdout("-ffaster", "CC arguments not found")
4364 }
4365
4366 const (
4367         noMatchesPattern = `(?m)^ok.*\[no tests to run\]`
4368         okPattern        = `(?m)^ok`
4369 )
4370
4371 func TestMatchesNoTests(t *testing.T) {
4372         tg := testgo(t)
4373         defer tg.cleanup()
4374         // TODO: tg.parallel()
4375         tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go")
4376         tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4377 }
4378
4379 func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) {
4380         tg := testgo(t)
4381         defer tg.cleanup()
4382         tg.parallel()
4383         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4384         tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror")
4385         tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4386         tg.grepBoth("FAIL", "go test did not say FAIL")
4387 }
4388
4389 func TestMatchesNoBenchmarksIsOK(t *testing.T) {
4390         tg := testgo(t)
4391         defer tg.cleanup()
4392         // TODO: tg.parallel()
4393         tg.run("test", "-run", "^$", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go")
4394         tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4395         tg.grepBoth(okPattern, "go test did not say ok")
4396 }
4397
4398 func TestMatchesOnlyExampleIsOK(t *testing.T) {
4399         tg := testgo(t)
4400         defer tg.cleanup()
4401         // TODO: tg.parallel()
4402         tg.run("test", "-run", "Example", "testdata/example1_test.go")
4403         tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4404         tg.grepBoth(okPattern, "go test did not say ok")
4405 }
4406
4407 func TestMatchesOnlyBenchmarkIsOK(t *testing.T) {
4408         tg := testgo(t)
4409         defer tg.cleanup()
4410         // TODO: tg.parallel()
4411         tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4412         tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4413         tg.grepBoth(okPattern, "go test did not say ok")
4414 }
4415
4416 func TestBenchmarkLabels(t *testing.T) {
4417         tg := testgo(t)
4418         defer tg.cleanup()
4419         // TODO: tg.parallel()
4420         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4421         tg.run("test", "-run", "^$", "-bench", ".", "bench")
4422         tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4423         tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4424         tg.grepStdout(`(?m)^pkg: bench`, "go test did not say pkg: bench")
4425         tg.grepBothNot(`(?s)pkg:.*pkg:`, "go test said pkg multiple times")
4426 }
4427
4428 func TestBenchmarkLabelsOutsideGOPATH(t *testing.T) {
4429         tg := testgo(t)
4430         defer tg.cleanup()
4431         // TODO: tg.parallel()
4432         tg.run("test", "-run", "^$", "-bench", ".", "testdata/standalone_benchmark_test.go")
4433         tg.grepStdout(`(?m)^goos: `+runtime.GOOS, "go test did not print goos")
4434         tg.grepStdout(`(?m)^goarch: `+runtime.GOARCH, "go test did not print goarch")
4435         tg.grepBothNot(`(?m)^pkg:`, "go test did say pkg:")
4436 }
4437
4438 func TestMatchesOnlyTestIsOK(t *testing.T) {
4439         tg := testgo(t)
4440         defer tg.cleanup()
4441         // TODO: tg.parallel()
4442         tg.run("test", "-run", "Test", "testdata/standalone_test.go")
4443         tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4444         tg.grepBoth(okPattern, "go test did not say ok")
4445 }
4446
4447 func TestMatchesNoTestsWithSubtests(t *testing.T) {
4448         tg := testgo(t)
4449         defer tg.cleanup()
4450         tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go")
4451         tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4452 }
4453
4454 func TestMatchesNoSubtestsMatch(t *testing.T) {
4455         tg := testgo(t)
4456         defer tg.cleanup()
4457         tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go")
4458         tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4459 }
4460
4461 func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) {
4462         tg := testgo(t)
4463         defer tg.cleanup()
4464         tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go")
4465         tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4466         tg.grepBoth("FAIL", "go test did not say FAIL")
4467 }
4468
4469 func TestMatchesOnlySubtestIsOK(t *testing.T) {
4470         tg := testgo(t)
4471         defer tg.cleanup()
4472         tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go")
4473         tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4474         tg.grepBoth(okPattern, "go test did not say ok")
4475 }
4476
4477 func TestMatchesNoSubtestsParallel(t *testing.T) {
4478         tg := testgo(t)
4479         defer tg.cleanup()
4480         tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go")
4481         tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]")
4482 }
4483
4484 func TestMatchesOnlySubtestParallelIsOK(t *testing.T) {
4485         tg := testgo(t)
4486         defer tg.cleanup()
4487         tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go")
4488         tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]")
4489         tg.grepBoth(okPattern, "go test did not say ok")
4490 }
4491
4492 // Issue 18845
4493 func TestBenchTimeout(t *testing.T) {
4494         tooSlow(t)
4495         tg := testgo(t)
4496         defer tg.cleanup()
4497         tg.run("test", "-bench", ".", "-timeout", "750ms", "testdata/timeoutbench_test.go")
4498 }
4499
4500 // Issue 19394
4501 func TestWriteProfilesOnTimeout(t *testing.T) {
4502         tooSlow(t)
4503         tg := testgo(t)
4504         defer tg.cleanup()
4505         tg.tempDir("profiling")
4506         tg.tempFile("profiling/timeouttest_test.go", `package timeouttest_test
4507 import "testing"
4508 import "time"
4509 func TestSleep(t *testing.T) { time.Sleep(time.Second) }`)
4510         tg.cd(tg.path("profiling"))
4511         tg.runFail(
4512                 "test",
4513                 "-cpuprofile", tg.path("profiling/cpu.pprof"), "-memprofile", tg.path("profiling/mem.pprof"),
4514                 "-timeout", "1ms")
4515         tg.mustHaveContent(tg.path("profiling/cpu.pprof"))
4516         tg.mustHaveContent(tg.path("profiling/mem.pprof"))
4517 }
4518
4519 func TestLinkXImportPathEscape(t *testing.T) {
4520         // golang.org/issue/16710
4521         skipIfGccgo(t, "gccgo does not support -ldflags -X")
4522         tg := testgo(t)
4523         defer tg.cleanup()
4524         tg.parallel()
4525         tg.makeTempdir()
4526         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4527         exe := tg.path("linkx" + exeSuffix)
4528         tg.creatingTemp(exe)
4529         tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main")
4530         out, err := exec.Command(exe).CombinedOutput()
4531         if err != nil {
4532                 tg.t.Fatal(err)
4533         }
4534         if string(out) != "linkXworked\n" {
4535                 tg.t.Log(string(out))
4536                 tg.t.Fatal(`incorrect output: expected "linkXworked\n"`)
4537         }
4538 }
4539
4540 // Issue 18044.
4541 func TestLdBindNow(t *testing.T) {
4542         tg := testgo(t)
4543         defer tg.cleanup()
4544         tg.parallel()
4545         tg.setenv("LD_BIND_NOW", "1")
4546         tg.run("help")
4547 }
4548
4549 // Issue 18225.
4550 // This is really a cmd/asm issue but this is a convenient place to test it.
4551 func TestConcurrentAsm(t *testing.T) {
4552         skipIfGccgo(t, "gccgo does not use cmd/asm")
4553         tg := testgo(t)
4554         defer tg.cleanup()
4555         tg.parallel()
4556         asm := `DATA Â·constants<>+0x0(SB)/8,$0
4557 GLOBL Â·constants<>(SB),8,$8
4558 `
4559         tg.tempFile("go/src/p/a.s", asm)
4560         tg.tempFile("go/src/p/b.s", asm)
4561         tg.tempFile("go/src/p/p.go", `package p`)
4562         tg.setenv("GOPATH", tg.path("go"))
4563         tg.run("build", "p")
4564 }
4565
4566 // Issue 18778.
4567 func TestDotDotDotOutsideGOPATH(t *testing.T) {
4568         tg := testgo(t)
4569         defer tg.cleanup()
4570
4571         tg.tempFile("pkgs/a.go", `package x`)
4572         tg.tempFile("pkgs/a_test.go", `package x_test
4573 import "testing"
4574 func TestX(t *testing.T) {}`)
4575
4576         tg.tempFile("pkgs/a/a.go", `package a`)
4577         tg.tempFile("pkgs/a/a_test.go", `package a_test
4578 import "testing"
4579 func TestA(t *testing.T) {}`)
4580
4581         tg.cd(tg.path("pkgs"))
4582         tg.run("build", "./...")
4583         tg.run("test", "./...")
4584         tg.run("list", "./...")
4585         tg.grepStdout("pkgs$", "expected package not listed")
4586         tg.grepStdout("pkgs/a", "expected package not listed")
4587 }
4588
4589 // Issue 18975.
4590 func TestFFLAGS(t *testing.T) {
4591         if !canCgo {
4592                 t.Skip("skipping because cgo not enabled")
4593         }
4594
4595         tg := testgo(t)
4596         defer tg.cleanup()
4597         tg.parallel()
4598
4599         tg.tempFile("p/src/p/main.go", `package main
4600                 // #cgo FFLAGS: -no-such-fortran-flag
4601                 import "C"
4602                 func main() {}
4603         `)
4604         tg.tempFile("p/src/p/a.f", `! comment`)
4605         tg.setenv("GOPATH", tg.path("p"))
4606
4607         // This should normally fail because we are passing an unknown flag,
4608         // but issue #19080 points to Fortran compilers that succeed anyhow.
4609         // To work either way we call doRun directly rather than run or runFail.
4610         tg.doRun([]string{"build", "-x", "p"})
4611
4612         tg.grepStderr("no-such-fortran-flag", `missing expected "-no-such-fortran-flag"`)
4613 }
4614
4615 // Issue 19198.
4616 // This is really a cmd/link issue but this is a convenient place to test it.
4617 func TestDuplicateGlobalAsmSymbols(t *testing.T) {
4618         skipIfGccgo(t, "gccgo does not use cmd/asm")
4619         tooSlow(t)
4620         if runtime.GOARCH != "386" && runtime.GOARCH != "amd64" {
4621                 t.Skipf("skipping test on %s", runtime.GOARCH)
4622         }
4623         if !canCgo {
4624                 t.Skip("skipping because cgo not enabled")
4625         }
4626
4627         tg := testgo(t)
4628         defer tg.cleanup()
4629         tg.parallel()
4630
4631         asm := `
4632 #include "textflag.h"
4633
4634 DATA sym<>+0x0(SB)/8,$0
4635 GLOBL sym<>(SB),(NOPTR+RODATA),$8
4636
4637 TEXT Â·Data(SB),NOSPLIT,$0
4638         MOVB sym<>(SB), AX
4639         MOVB AX, ret+0(FP)
4640         RET
4641 `
4642         tg.tempFile("go/src/a/a.s", asm)
4643         tg.tempFile("go/src/a/a.go", `package a; func Data() uint8`)
4644         tg.tempFile("go/src/b/b.s", asm)
4645         tg.tempFile("go/src/b/b.go", `package b; func Data() uint8`)
4646         tg.tempFile("go/src/p/p.go", `
4647 package main
4648 import "a"
4649 import "b"
4650 import "C"
4651 func main() {
4652         _ = a.Data() + b.Data()
4653 }
4654 `)
4655         tg.setenv("GOPATH", tg.path("go"))
4656         exe := tg.path("p.exe")
4657         tg.creatingTemp(exe)
4658         tg.run("build", "-o", exe, "p")
4659 }
4660
4661 func TestBuildTagsNoComma(t *testing.T) {
4662         skipIfGccgo(t, "gccgo has no standard packages")
4663         tg := testgo(t)
4664         defer tg.cleanup()
4665         tg.makeTempdir()
4666         tg.setenv("GOPATH", tg.path("go"))
4667         tg.run("build", "-tags", "tag1 tag2", "math")
4668         tg.runFail("build", "-tags", "tag1,tag2 tag3", "math")
4669         tg.grepBoth("space-separated list contains comma", "-tags with a comma-separated list didn't error")
4670 }
4671
4672 func copyFile(src, dst string, perm os.FileMode) error {
4673         sf, err := os.Open(src)
4674         if err != nil {
4675                 return err
4676         }
4677         defer sf.Close()
4678
4679         df, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
4680         if err != nil {
4681                 return err
4682         }
4683
4684         _, err = io.Copy(df, sf)
4685         err2 := df.Close()
4686         if err != nil {
4687                 return err
4688         }
4689         return err2
4690 }
4691
4692 func TestExecutableGOROOT(t *testing.T) {
4693         skipIfGccgo(t, "gccgo has no GOROOT")
4694         if runtime.GOOS == "openbsd" {
4695                 t.Skipf("test case does not work on %s, missing os.Executable", runtime.GOOS)
4696         }
4697
4698         // Env with no GOROOT.
4699         var env []string
4700         for _, e := range os.Environ() {
4701                 if !strings.HasPrefix(e, "GOROOT=") {
4702                         env = append(env, e)
4703                 }
4704         }
4705
4706         check := func(t *testing.T, exe, want string) {
4707                 cmd := exec.Command(exe, "env", "GOROOT")
4708                 cmd.Env = env
4709                 out, err := cmd.CombinedOutput()
4710                 if err != nil {
4711                         t.Fatalf("%s env GOROOT: %v, %s", exe, err, out)
4712                 }
4713                 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4714                 if err != nil {
4715                         t.Fatal(err)
4716                 }
4717                 want, err = filepath.EvalSymlinks(want)
4718                 if err != nil {
4719                         t.Fatal(err)
4720                 }
4721                 if !strings.EqualFold(goroot, want) {
4722                         t.Errorf("go env GOROOT:\nhave %s\nwant %s", goroot, want)
4723                 } else {
4724                         t.Logf("go env GOROOT: %s", goroot)
4725                 }
4726         }
4727
4728         // Note: Must not call tg methods inside subtests: tg is attached to outer t.
4729         tg := testgo(t)
4730         defer tg.cleanup()
4731
4732         tg.makeTempdir()
4733         tg.tempDir("new/bin")
4734         newGoTool := tg.path("new/bin/go" + exeSuffix)
4735         tg.must(copyFile(tg.goTool(), newGoTool, 0775))
4736         newRoot := tg.path("new")
4737
4738         t.Run("RelocatedExe", func(t *testing.T) {
4739                 // Should fall back to default location in binary,
4740                 // which is the GOROOT we used when building testgo.exe.
4741                 check(t, newGoTool, testGOROOT)
4742         })
4743
4744         // If the binary is sitting in a bin dir next to ../pkg/tool, that counts as a GOROOT,
4745         // so it should find the new tree.
4746         tg.tempDir("new/pkg/tool")
4747         t.Run("RelocatedTree", func(t *testing.T) {
4748                 check(t, newGoTool, newRoot)
4749         })
4750
4751         tg.tempDir("other/bin")
4752         symGoTool := tg.path("other/bin/go" + exeSuffix)
4753
4754         // Symlink into go tree should still find go tree.
4755         t.Run("SymlinkedExe", func(t *testing.T) {
4756                 testenv.MustHaveSymlink(t)
4757                 if err := os.Symlink(newGoTool, symGoTool); err != nil {
4758                         t.Fatal(err)
4759                 }
4760                 check(t, symGoTool, newRoot)
4761         })
4762
4763         tg.must(robustio.RemoveAll(tg.path("new/pkg")))
4764
4765         // Binaries built in the new tree should report the
4766         // new tree when they call runtime.GOROOT.
4767         t.Run("RuntimeGoroot", func(t *testing.T) {
4768                 // Build a working GOROOT the easy way, with symlinks.
4769                 testenv.MustHaveSymlink(t)
4770                 if err := os.Symlink(filepath.Join(testGOROOT, "src"), tg.path("new/src")); err != nil {
4771                         t.Fatal(err)
4772                 }
4773                 if err := os.Symlink(filepath.Join(testGOROOT, "pkg"), tg.path("new/pkg")); err != nil {
4774                         t.Fatal(err)
4775                 }
4776
4777                 cmd := exec.Command(newGoTool, "run", "testdata/print_goroot.go")
4778                 cmd.Env = env
4779                 out, err := cmd.CombinedOutput()
4780                 if err != nil {
4781                         t.Fatalf("%s run testdata/print_goroot.go: %v, %s", newGoTool, err, out)
4782                 }
4783                 goroot, err := filepath.EvalSymlinks(strings.TrimSpace(string(out)))
4784                 if err != nil {
4785                         t.Fatal(err)
4786                 }
4787                 want, err := filepath.EvalSymlinks(tg.path("new"))
4788                 if err != nil {
4789                         t.Fatal(err)
4790                 }
4791                 if !strings.EqualFold(goroot, want) {
4792                         t.Errorf("go run testdata/print_goroot.go:\nhave %s\nwant %s", goroot, want)
4793                 } else {
4794                         t.Logf("go run testdata/print_goroot.go: %s", goroot)
4795                 }
4796         })
4797 }
4798
4799 func TestNeedVersion(t *testing.T) {
4800         skipIfGccgo(t, "gccgo does not use cmd/compile")
4801         tg := testgo(t)
4802         defer tg.cleanup()
4803         tg.parallel()
4804         tg.tempFile("goversion.go", `package main; func main() {}`)
4805         path := tg.path("goversion.go")
4806         tg.setenv("TESTGO_VERSION", "go1.testgo")
4807         tg.runFail("run", path)
4808         tg.grepStderr("compile", "does not match go tool version")
4809 }
4810
4811 // Test that user can override default code generation flags.
4812 func TestUserOverrideFlags(t *testing.T) {
4813         skipIfGccgo(t, "gccgo does not use -gcflags")
4814         if !canCgo {
4815                 t.Skip("skipping because cgo not enabled")
4816         }
4817         if runtime.GOOS != "linux" {
4818                 // We are testing platform-independent code, so it's
4819                 // OK to skip cases that work differently.
4820                 t.Skipf("skipping on %s because test only works if c-archive implies -shared", runtime.GOOS)
4821         }
4822
4823         tg := testgo(t)
4824         defer tg.cleanup()
4825         // Don't call tg.parallel, as creating override.h and override.a may
4826         // confuse other tests.
4827         tg.tempFile("override.go", `package main
4828
4829 import "C"
4830
4831 //export GoFunc
4832 func GoFunc() {}
4833
4834 func main() {}`)
4835         tg.creatingTemp("override.a")
4836         tg.creatingTemp("override.h")
4837         tg.run("build", "-x", "-buildmode=c-archive", "-gcflags=all=-shared=false", tg.path("override.go"))
4838         tg.grepStderr("compile .*-shared .*-shared=false", "user can not override code generation flag")
4839 }
4840
4841 func TestCgoFlagContainsSpace(t *testing.T) {
4842         tooSlow(t)
4843         if !canCgo {
4844                 t.Skip("skipping because cgo not enabled")
4845         }
4846         tg := testgo(t)
4847         defer tg.cleanup()
4848
4849         tg.makeTempdir()
4850         tg.cd(tg.path("."))
4851         tg.tempFile("main.go", `package main
4852                 // #cgo CFLAGS: -I"c flags"
4853                 // #cgo LDFLAGS: -L"ld flags"
4854                 import "C"
4855                 func main() {}
4856         `)
4857         tg.run("run", "-x", "main.go")
4858         tg.grepStderr(`"-I[^"]+c flags"`, "did not find quoted c flags")
4859         tg.grepStderrNot(`"-I[^"]+c flags".*"-I[^"]+c flags"`, "found too many quoted c flags")
4860         tg.grepStderr(`"-L[^"]+ld flags"`, "did not find quoted ld flags")
4861         tg.grepStderrNot(`"-L[^"]+c flags".*"-L[^"]+c flags"`, "found too many quoted ld flags")
4862 }
4863
4864 // Issue #20435.
4865 func TestGoTestRaceCoverModeFailures(t *testing.T) {
4866         tooSlow(t)
4867         if !canRace {
4868                 t.Skip("skipping because race detector not supported")
4869         }
4870
4871         tg := testgo(t)
4872         tg.parallel()
4873         defer tg.cleanup()
4874         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4875
4876         tg.run("test", "testrace")
4877
4878         tg.runFail("test", "-race", "-covermode=set", "testrace")
4879         tg.grepStderr(`-covermode must be "atomic", not "set", when -race is enabled`, "-race -covermode=set was allowed")
4880         tg.grepBothNot("PASS", "something passed")
4881 }
4882
4883 // Issue 9737: verify that GOARM and GO386 affect the computed build ID.
4884 func TestBuildIDContainsArchModeEnv(t *testing.T) {
4885         if testing.Short() {
4886                 t.Skip("skipping in short mode")
4887         }
4888
4889         var tg *testgoData
4890         testWith := func(before, after func()) func(*testing.T) {
4891                 return func(t *testing.T) {
4892                         tg = testgo(t)
4893                         defer tg.cleanup()
4894                         tg.tempFile("src/mycmd/x.go", `package main
4895 func main() {}`)
4896                         tg.setenv("GOPATH", tg.path("."))
4897
4898                         tg.cd(tg.path("src/mycmd"))
4899                         tg.setenv("GOOS", "linux")
4900                         before()
4901                         tg.run("install", "mycmd")
4902                         after()
4903                         tg.wantStale("mycmd", "stale dependency", "should be stale after environment variable change")
4904                 }
4905         }
4906
4907         t.Run("386", testWith(func() {
4908                 tg.setenv("GOARCH", "386")
4909                 tg.setenv("GO386", "387")
4910         }, func() {
4911                 tg.setenv("GO386", "sse2")
4912         }))
4913
4914         t.Run("arm", testWith(func() {
4915                 tg.setenv("GOARCH", "arm")
4916                 tg.setenv("GOARM", "5")
4917         }, func() {
4918                 tg.setenv("GOARM", "7")
4919         }))
4920 }
4921
4922 func TestTestRegexps(t *testing.T) {
4923         tg := testgo(t)
4924         defer tg.cleanup()
4925         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
4926         tg.run("test", "-cpu=1", "-run=X/Y", "-bench=X/Y", "-count=2", "-v", "testregexp")
4927         var lines []string
4928         for _, line := range strings.SplitAfter(tg.getStdout(), "\n") {
4929                 if strings.Contains(line, "=== RUN") || strings.Contains(line, "--- BENCH") || strings.Contains(line, "LOG") {
4930                         lines = append(lines, line)
4931                 }
4932         }
4933
4934         // Important parts:
4935         //      TestX is run, twice
4936         //      TestX/Y is run, twice
4937         //      TestXX is run, twice
4938         //      TestZ is not run
4939         //      BenchmarkX is run but only with N=1, once
4940         //      BenchmarkXX is run but only with N=1, once
4941         //      BenchmarkX/Y is run in full, twice
4942         want := `=== RUN   TestX
4943 === RUN   TestX/Y
4944     x_test.go:6: LOG: X running
4945         x_test.go:8: LOG: Y running
4946 === RUN   TestXX
4947     z_test.go:10: LOG: XX running
4948 === RUN   TestX
4949 === RUN   TestX/Y
4950     x_test.go:6: LOG: X running
4951         x_test.go:8: LOG: Y running
4952 === RUN   TestXX
4953     z_test.go:10: LOG: XX running
4954 --- BENCH: BenchmarkX/Y
4955     x_test.go:15: LOG: Y running N=1
4956     x_test.go:15: LOG: Y running N=100
4957     x_test.go:15: LOG: Y running N=10000
4958     x_test.go:15: LOG: Y running N=1000000
4959     x_test.go:15: LOG: Y running N=100000000
4960     x_test.go:15: LOG: Y running N=1000000000
4961 --- BENCH: BenchmarkX/Y
4962     x_test.go:15: LOG: Y running N=1
4963     x_test.go:15: LOG: Y running N=100
4964     x_test.go:15: LOG: Y running N=10000
4965     x_test.go:15: LOG: Y running N=1000000
4966     x_test.go:15: LOG: Y running N=100000000
4967     x_test.go:15: LOG: Y running N=1000000000
4968 --- BENCH: BenchmarkX
4969     x_test.go:13: LOG: X running N=1
4970 --- BENCH: BenchmarkXX
4971     z_test.go:18: LOG: XX running N=1
4972 `
4973
4974         have := strings.Join(lines, "")
4975         if have != want {
4976                 t.Errorf("reduced output:<<<\n%s>>> want:<<<\n%s>>>", have, want)
4977         }
4978 }
4979
4980 func TestListTests(t *testing.T) {
4981         tooSlow(t)
4982         var tg *testgoData
4983         testWith := func(listName, expected string) func(*testing.T) {
4984                 return func(t *testing.T) {
4985                         tg = testgo(t)
4986                         defer tg.cleanup()
4987                         tg.run("test", "./testdata/src/testlist/...", fmt.Sprintf("-list=%s", listName))
4988                         tg.grepStdout(expected, fmt.Sprintf("-test.list=%s returned %q, expected %s", listName, tg.getStdout(), expected))
4989                 }
4990         }
4991
4992         t.Run("Test", testWith("Test", "TestSimple"))
4993         t.Run("Bench", testWith("Benchmark", "BenchmarkSimple"))
4994         t.Run("Example1", testWith("Example", "ExampleSimple"))
4995         t.Run("Example2", testWith("Example", "ExampleWithEmptyOutput"))
4996 }
4997
4998 func TestBuildmodePIE(t *testing.T) {
4999         if testing.Short() && testenv.Builder() == "" {
5000                 t.Skipf("skipping in -short mode on non-builder")
5001         }
5002
5003         platform := fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
5004         switch platform {
5005         case "linux/386", "linux/amd64", "linux/arm", "linux/arm64", "linux/ppc64le", "linux/s390x",
5006                 "android/amd64", "android/arm", "android/arm64", "android/386",
5007                 "freebsd/amd64":
5008         case "darwin/amd64":
5009         default:
5010                 t.Skipf("skipping test because buildmode=pie is not supported on %s", platform)
5011         }
5012
5013         tg := testgo(t)
5014         defer tg.cleanup()
5015
5016         tg.tempFile("main.go", `package main; func main() { print("hello") }`)
5017         src := tg.path("main.go")
5018         obj := tg.path("main")
5019         tg.run("build", "-buildmode=pie", "-o", obj, src)
5020
5021         switch runtime.GOOS {
5022         case "linux", "android", "freebsd":
5023                 f, err := elf.Open(obj)
5024                 if err != nil {
5025                         t.Fatal(err)
5026                 }
5027                 defer f.Close()
5028                 if f.Type != elf.ET_DYN {
5029                         t.Errorf("PIE type must be ET_DYN, but %s", f.Type)
5030                 }
5031         case "darwin":
5032                 f, err := macho.Open(obj)
5033                 if err != nil {
5034                         t.Fatal(err)
5035                 }
5036                 defer f.Close()
5037                 if f.Flags&macho.FlagDyldLink == 0 {
5038                         t.Error("PIE must have DyldLink flag, but not")
5039                 }
5040                 if f.Flags&macho.FlagPIE == 0 {
5041                         t.Error("PIE must have PIE flag, but not")
5042                 }
5043         default:
5044                 panic("unreachable")
5045         }
5046
5047         out, err := exec.Command(obj).CombinedOutput()
5048         if err != nil {
5049                 t.Fatal(err)
5050         }
5051
5052         if string(out) != "hello" {
5053                 t.Errorf("got %q; want %q", out, "hello")
5054         }
5055 }
5056
5057 func TestExecBuildX(t *testing.T) {
5058         tooSlow(t)
5059         if !canCgo {
5060                 t.Skip("skipping because cgo not enabled")
5061         }
5062
5063         testenv.MustHaveExecPath(t, "/usr/bin/env")
5064         testenv.MustHaveExecPath(t, "bash")
5065
5066         tg := testgo(t)
5067         defer tg.cleanup()
5068
5069         tg.tempDir("cache")
5070         tg.setenv("GOCACHE", tg.path("cache"))
5071
5072         tg.tempFile("main.go", `package main; import "C"; func main() { print("hello") }`)
5073         src := tg.path("main.go")
5074         obj := tg.path("main")
5075         tg.run("build", "-x", "-o", obj, src)
5076         sh := tg.path("test.sh")
5077         cmds := tg.getStderr()
5078         err := ioutil.WriteFile(sh, []byte("set -e\n"+cmds), 0666)
5079         if err != nil {
5080                 t.Fatal(err)
5081         }
5082
5083         out, err := exec.Command(obj).CombinedOutput()
5084         if err != nil {
5085                 t.Fatal(err)
5086         }
5087         if string(out) != "hello" {
5088                 t.Fatalf("got %q; want %q", out, "hello")
5089         }
5090
5091         err = os.Remove(obj)
5092         if err != nil {
5093                 t.Fatal(err)
5094         }
5095
5096         out, err = exec.Command("/usr/bin/env", "bash", "-x", sh).CombinedOutput()
5097         if err != nil {
5098                 t.Fatalf("/bin/sh %s: %v\n%s", sh, err, out)
5099         }
5100         t.Logf("shell output:\n%s", out)
5101
5102         out, err = exec.Command(obj).CombinedOutput()
5103         if err != nil {
5104                 t.Fatal(err)
5105         }
5106         if string(out) != "hello" {
5107                 t.Fatalf("got %q; want %q", out, "hello")
5108         }
5109
5110         matches := regexp.MustCompile(`^WORK=(.*)\n`).FindStringSubmatch(cmds)
5111         if len(matches) == 0 {
5112                 t.Fatal("no WORK directory")
5113         }
5114         tg.must(robustio.RemoveAll(matches[1]))
5115 }
5116
5117 func TestParallelNumber(t *testing.T) {
5118         tooSlow(t)
5119         for _, n := range [...]string{"-1", "0"} {
5120                 t.Run(n, func(t *testing.T) {
5121                         tg := testgo(t)
5122                         defer tg.cleanup()
5123                         tg.runFail("test", "-parallel", n, "testdata/standalone_parallel_sub_test.go")
5124                         tg.grepBoth("-parallel can only be given", "go test -parallel with N<1 did not error")
5125                 })
5126         }
5127 }
5128
5129 func TestWrongGOOSErrorBeforeLoadError(t *testing.T) {
5130         skipIfGccgo(t, "gccgo assumes cross-compilation is always possible")
5131         tg := testgo(t)
5132         defer tg.cleanup()
5133         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5134         tg.setenv("GOOS", "windwos")
5135         tg.runFail("build", "exclude")
5136         tg.grepStderr("unsupported GOOS/GOARCH pair", "GOOS=windwos go build exclude did not report 'unsupported GOOS/GOARCH pair'")
5137 }
5138
5139 func TestUpxCompression(t *testing.T) {
5140         if runtime.GOOS != "linux" ||
5141                 (runtime.GOARCH != "amd64" && runtime.GOARCH != "386") {
5142                 t.Skipf("skipping upx test on %s/%s", runtime.GOOS, runtime.GOARCH)
5143         }
5144
5145         testenv.MustHaveExecPath(t, "upx")
5146         out, err := exec.Command("upx", "--version").CombinedOutput()
5147         if err != nil {
5148                 t.Fatalf("upx --version failed: %v", err)
5149         }
5150
5151         // upx --version prints `upx <version>` in the first line of output:
5152         //   upx 3.94
5153         //   [...]
5154         re := regexp.MustCompile(`([[:digit:]]+)\.([[:digit:]]+)`)
5155         upxVersion := re.FindStringSubmatch(string(out))
5156         if len(upxVersion) != 3 {
5157                 t.Fatalf("bad upx version string: %s", upxVersion)
5158         }
5159
5160         major, err1 := strconv.Atoi(upxVersion[1])
5161         minor, err2 := strconv.Atoi(upxVersion[2])
5162         if err1 != nil || err2 != nil {
5163                 t.Fatalf("bad upx version string: %s", upxVersion[0])
5164         }
5165
5166         // Anything below 3.94 is known not to work with go binaries
5167         if (major < 3) || (major == 3 && minor < 94) {
5168                 t.Skipf("skipping because upx version %v.%v is too old", major, minor)
5169         }
5170
5171         tg := testgo(t)
5172         defer tg.cleanup()
5173
5174         tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello upx") }`)
5175         src := tg.path("main.go")
5176         obj := tg.path("main")
5177         tg.run("build", "-o", obj, src)
5178
5179         out, err = exec.Command("upx", obj).CombinedOutput()
5180         if err != nil {
5181                 t.Logf("executing upx\n%s\n", out)
5182                 t.Fatalf("upx failed with %v", err)
5183         }
5184
5185         out, err = exec.Command(obj).CombinedOutput()
5186         if err != nil {
5187                 t.Logf("%s", out)
5188                 t.Fatalf("running compressed go binary failed with error %s", err)
5189         }
5190         if string(out) != "hello upx" {
5191                 t.Fatalf("bad output from compressed go binary:\ngot %q; want %q", out, "hello upx")
5192         }
5193 }
5194
5195 // Test that Go binaries can be run under QEMU in user-emulation mode
5196 // (See issue #13024).
5197 func TestQEMUUserMode(t *testing.T) {
5198         if testing.Short() && testenv.Builder() == "" {
5199                 t.Skipf("skipping in -short mode on non-builder")
5200         }
5201
5202         testArchs := []struct {
5203                 g, qemu string
5204         }{
5205                 {"arm", "arm"},
5206                 {"arm64", "aarch64"},
5207         }
5208
5209         tg := testgo(t)
5210         defer tg.cleanup()
5211         tg.tempFile("main.go", `package main; import "fmt"; func main() { fmt.Print("hello qemu-user") }`)
5212         tg.parallel()
5213         src, obj := tg.path("main.go"), tg.path("main")
5214
5215         for _, arch := range testArchs {
5216                 arch := arch
5217                 t.Run(arch.g, func(t *testing.T) {
5218                         qemu := "qemu-" + arch.qemu
5219                         testenv.MustHaveExecPath(t, qemu)
5220
5221                         out, err := exec.Command(qemu, "--version").CombinedOutput()
5222                         if err != nil {
5223                                 t.Fatalf("%s --version failed: %v", qemu, err)
5224                         }
5225
5226                         tg.setenv("GOARCH", arch.g)
5227                         tg.run("build", "-o", obj, src)
5228
5229                         out, err = exec.Command(qemu, obj).CombinedOutput()
5230                         if err != nil {
5231                                 t.Logf("%s output:\n%s\n", qemu, out)
5232                                 t.Fatalf("%s failed with %v", qemu, err)
5233                         }
5234                         if want := "hello qemu-user"; string(out) != want {
5235                                 t.Errorf("bad output from %s:\ngot %s; want %s", qemu, out, want)
5236                         }
5237                 })
5238         }
5239 }
5240
5241 func TestCacheListStale(t *testing.T) {
5242         tooSlow(t)
5243         if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5244                 t.Skip("GODEBUG gocacheverify")
5245         }
5246         tg := testgo(t)
5247         defer tg.cleanup()
5248         tg.parallel()
5249         tg.makeTempdir()
5250         tg.setenv("GOCACHE", tg.path("cache"))
5251         tg.tempFile("gopath/src/p/p.go", "package p; import _ \"q\"; func F(){}\n")
5252         tg.tempFile("gopath/src/q/q.go", "package q; func F(){}\n")
5253         tg.tempFile("gopath/src/m/m.go", "package main; import _ \"q\"; func main(){}\n")
5254
5255         tg.setenv("GOPATH", tg.path("gopath"))
5256         tg.run("install", "p", "m")
5257         tg.run("list", "-f={{.ImportPath}} {{.Stale}}", "m", "q", "p")
5258         tg.grepStdout("^m false", "m should not be stale")
5259         tg.grepStdout("^q true", "q should be stale")
5260         tg.grepStdout("^p false", "p should not be stale")
5261 }
5262
5263 func TestCacheCoverage(t *testing.T) {
5264         tooSlow(t)
5265
5266         if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5267                 t.Skip("GODEBUG gocacheverify")
5268         }
5269
5270         tg := testgo(t)
5271         defer tg.cleanup()
5272         tg.parallel()
5273         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5274         tg.makeTempdir()
5275
5276         tg.setenv("GOCACHE", tg.path("c1"))
5277         tg.run("test", "-cover", "-short", "strings")
5278         tg.run("test", "-cover", "-short", "math", "strings")
5279 }
5280
5281 func TestCacheVet(t *testing.T) {
5282         skipIfGccgo(t, "gccgo has no standard packages")
5283         tg := testgo(t)
5284         defer tg.cleanup()
5285         tg.parallel()
5286
5287         if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5288                 t.Skip("GODEBUG gocacheverify")
5289         }
5290         if testing.Short() {
5291                 // In short mode, reuse cache.
5292                 // Test failures may be masked if the cache has just the right entries already
5293                 // (not a concern during all.bash, which runs in a clean cache).
5294                 if cfg.Getenv("GOCACHE") == "off" {
5295                         tooSlow(t)
5296                 }
5297         } else {
5298                 tg.makeTempdir()
5299                 tg.setenv("GOCACHE", tg.path("cache"))
5300         }
5301
5302         // Check that second vet reuses cgo-derived inputs.
5303         // The first command could be build instead of vet,
5304         // except that if the cache is empty and there's a net.a
5305         // in GOROOT/pkg, the build will not bother to regenerate
5306         // and cache the cgo outputs, whereas vet always will.
5307         tg.run("vet", "os/user")
5308         tg.run("vet", "-x", "os/user")
5309         tg.grepStderrNot(`^(clang|gcc)`, "should not have run compiler")
5310         tg.grepStderrNot(`[\\/]cgo `, "should not have run cgo")
5311 }
5312
5313 func TestIssue22588(t *testing.T) {
5314         // Don't get confused by stderr coming from tools.
5315         tg := testgo(t)
5316         defer tg.cleanup()
5317         tg.parallel()
5318
5319         if _, err := os.Stat("/usr/bin/time"); err != nil {
5320                 t.Skip(err)
5321         }
5322
5323         tg.run("list", "-f={{.Stale}}", "runtime")
5324         tg.run("list", "-toolexec=/usr/bin/time", "-f={{.Stale}}", "runtime")
5325         tg.grepStdout("false", "incorrectly reported runtime as stale")
5326 }
5327
5328 func TestIssue22531(t *testing.T) {
5329         tooSlow(t)
5330         if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5331                 t.Skip("GODEBUG gocacheverify")
5332         }
5333         tg := testgo(t)
5334         defer tg.cleanup()
5335         tg.parallel()
5336         tg.makeTempdir()
5337         tg.setenv("GOPATH", tg.tempdir)
5338         tg.setenv("GOCACHE", tg.path("cache"))
5339         tg.tempFile("src/m/main.go", "package main /* c1 */; func main() {}\n")
5340         tg.run("install", "-x", "m")
5341         tg.run("list", "-f", "{{.Stale}}", "m")
5342         tg.grepStdout("false", "reported m as stale after install")
5343         tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5344
5345         // The link action ID did not include the full main build ID,
5346         // even though the full main build ID is written into the
5347         // eventual binary. That caused the following install to
5348         // be a no-op, thinking the gofmt binary was up-to-date,
5349         // even though .Stale could see it was not.
5350         tg.tempFile("src/m/main.go", "package main /* c2 */; func main() {}\n")
5351         tg.run("install", "-x", "m")
5352         tg.run("list", "-f", "{{.Stale}}", "m")
5353         tg.grepStdout("false", "reported m as stale after reinstall")
5354         tg.run("tool", "buildid", tg.path("bin/m"+exeSuffix))
5355 }
5356
5357 func TestIssue22596(t *testing.T) {
5358         tooSlow(t)
5359         if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5360                 t.Skip("GODEBUG gocacheverify")
5361         }
5362         tg := testgo(t)
5363         defer tg.cleanup()
5364         tg.parallel()
5365         tg.makeTempdir()
5366         tg.setenv("GOCACHE", tg.path("cache"))
5367         tg.tempFile("gopath1/src/p/p.go", "package p; func F(){}\n")
5368         tg.tempFile("gopath2/src/p/p.go", "package p; func F(){}\n")
5369
5370         tg.setenv("GOPATH", tg.path("gopath1"))
5371         tg.run("list", "-f={{.Target}}", "p")
5372         target1 := strings.TrimSpace(tg.getStdout())
5373         tg.run("install", "p")
5374         tg.wantNotStale("p", "", "p stale after install")
5375
5376         tg.setenv("GOPATH", tg.path("gopath2"))
5377         tg.run("list", "-f={{.Target}}", "p")
5378         target2 := strings.TrimSpace(tg.getStdout())
5379         tg.must(os.MkdirAll(filepath.Dir(target2), 0777))
5380         tg.must(copyFile(target1, target2, 0666))
5381         tg.wantStale("p", "build ID mismatch", "p not stale after copy from gopath1")
5382         tg.run("install", "p")
5383         tg.wantNotStale("p", "", "p stale after install2")
5384 }
5385
5386 func TestTestCache(t *testing.T) {
5387         tooSlow(t)
5388
5389         if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5390                 t.Skip("GODEBUG gocacheverify")
5391         }
5392         tg := testgo(t)
5393         defer tg.cleanup()
5394         tg.parallel()
5395         tg.makeTempdir()
5396         tg.setenv("GOPATH", tg.tempdir)
5397         tg.setenv("GOCACHE", tg.path("cache"))
5398
5399         if runtime.Compiler != "gccgo" {
5400                 // timeout here should not affect result being cached
5401                 // or being retrieved later.
5402                 tg.run("test", "-x", "-timeout=10s", "errors")
5403                 tg.grepStderr(`[\\/]compile|gccgo`, "did not run compiler")
5404                 tg.grepStderr(`[\\/]link|gccgo`, "did not run linker")
5405                 tg.grepStderr(`errors\.test`, "did not run test")
5406
5407                 tg.run("test", "-x", "errors")
5408                 tg.grepStdout(`ok  \terrors\t\(cached\)`, "did not report cached result")
5409                 tg.grepStderrNot(`[\\/]compile|gccgo`, "incorrectly ran compiler")
5410                 tg.grepStderrNot(`[\\/]link|gccgo`, "incorrectly ran linker")
5411                 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5412                 tg.grepStderrNot("DO NOT USE", "poisoned action status leaked")
5413
5414                 // Even very low timeouts do not disqualify cached entries.
5415                 tg.run("test", "-timeout=1ns", "-x", "errors")
5416                 tg.grepStderrNot(`errors\.test`, "incorrectly ran test")
5417
5418                 tg.run("clean", "-testcache")
5419                 tg.run("test", "-x", "errors")
5420                 tg.grepStderr(`errors\.test`, "did not run test")
5421         }
5422
5423         // The -p=1 in the commands below just makes the -x output easier to read.
5424
5425         t.Log("\n\nINITIAL\n\n")
5426
5427         tg.tempFile("src/p1/p1.go", "package p1\nvar X =  1\n")
5428         tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\nvar X = 1\n")
5429         tg.tempFile("src/t/t1/t1_test.go", "package t\nimport \"testing\"\nfunc Test1(*testing.T) {}\n")
5430         tg.tempFile("src/t/t2/t2_test.go", "package t\nimport _ \"p1\"\nimport \"testing\"\nfunc Test2(*testing.T) {}\n")
5431         tg.tempFile("src/t/t3/t3_test.go", "package t\nimport \"p1\"\nimport \"testing\"\nfunc Test3(t *testing.T) {t.Log(p1.X)}\n")
5432         tg.tempFile("src/t/t4/t4_test.go", "package t\nimport \"p2\"\nimport \"testing\"\nfunc Test4(t *testing.T) {t.Log(p2.X)}")
5433         tg.run("test", "-x", "-v", "-short", "t/...")
5434
5435         t.Log("\n\nREPEAT\n\n")
5436
5437         tg.run("test", "-x", "-v", "-short", "t/...")
5438         tg.grepStdout(`ok  \tt/t1\t\(cached\)`, "did not cache t1")
5439         tg.grepStdout(`ok  \tt/t2\t\(cached\)`, "did not cache t2")
5440         tg.grepStdout(`ok  \tt/t3\t\(cached\)`, "did not cache t3")
5441         tg.grepStdout(`ok  \tt/t4\t\(cached\)`, "did not cache t4")
5442         tg.grepStderrNot(`[\\/](compile|gccgo) `, "incorrectly ran compiler")
5443         tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5444         tg.grepStderrNot(`p[0-9]\.test`, "incorrectly ran test")
5445
5446         t.Log("\n\nCOMMENT\n\n")
5447
5448         // Changing the program text without affecting the compiled package
5449         // should result in the package being rebuilt but nothing more.
5450         tg.tempFile("src/p1/p1.go", "package p1\nvar X = 01\n")
5451         tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5452         tg.grepStdout(`ok  \tt/t1\t\(cached\)`, "did not cache t1")
5453         tg.grepStdout(`ok  \tt/t2\t\(cached\)`, "did not cache t2")
5454         tg.grepStdout(`ok  \tt/t3\t\(cached\)`, "did not cache t3")
5455         tg.grepStdout(`ok  \tt/t4\t\(cached\)`, "did not cache t4")
5456         tg.grepStderrNot(`([\\/](compile|gccgo) ).*t[0-9]_test\.go`, "incorrectly ran compiler")
5457         tg.grepStderrNot(`[\\/](link|gccgo) `, "incorrectly ran linker")
5458         tg.grepStderrNot(`t[0-9]\.test.*test\.short`, "incorrectly ran test")
5459
5460         t.Log("\n\nCHANGE\n\n")
5461
5462         // Changing the actual package should have limited effects.
5463         tg.tempFile("src/p1/p1.go", "package p1\nvar X = 02\n")
5464         tg.run("test", "-p=1", "-x", "-v", "-short", "t/...")
5465
5466         // p2 should have been rebuilt.
5467         tg.grepStderr(`([\\/]compile|gccgo).*p2.go`, "did not recompile p2")
5468
5469         // t1 does not import anything, should not have been rebuilt.
5470         tg.grepStderrNot(`([\\/]compile|gccgo).*t1_test.go`, "incorrectly recompiled t1")
5471         tg.grepStderrNot(`([\\/]link|gccgo).*t1_test`, "incorrectly relinked t1_test")
5472         tg.grepStdout(`ok  \tt/t1\t\(cached\)`, "did not cache t/t1")
5473
5474         // t2 imports p1 and must be rebuilt and relinked,
5475         // but the change should not have any effect on the test binary,
5476         // so the test should not have been rerun.
5477         tg.grepStderr(`([\\/]compile|gccgo).*t2_test.go`, "did not recompile t2")
5478         tg.grepStderr(`([\\/]link|gccgo).*t2\.test`, "did not relink t2_test")
5479         // This check does not currently work with gccgo, as garbage
5480         // collection of unused variables is not turned on by default.
5481         if runtime.Compiler != "gccgo" {
5482                 tg.grepStdout(`ok  \tt/t2\t\(cached\)`, "did not cache t/t2")
5483         }
5484
5485         // t3 imports p1, and changing X changes t3's test binary.
5486         tg.grepStderr(`([\\/]compile|gccgo).*t3_test.go`, "did not recompile t3")
5487         tg.grepStderr(`([\\/]link|gccgo).*t3\.test`, "did not relink t3_test")
5488         tg.grepStderr(`t3\.test.*-test.short`, "did not rerun t3_test")
5489         tg.grepStdoutNot(`ok  \tt/t3\t\(cached\)`, "reported cached t3_test result")
5490
5491         // t4 imports p2, but p2 did not change, so t4 should be relinked, not recompiled,
5492         // and not rerun.
5493         tg.grepStderrNot(`([\\/]compile|gccgo).*t4_test.go`, "incorrectly recompiled t4")
5494         tg.grepStderr(`([\\/]link|gccgo).*t4\.test`, "did not relink t4_test")
5495         // This check does not currently work with gccgo, as garbage
5496         // collection of unused variables is not turned on by default.
5497         if runtime.Compiler != "gccgo" {
5498                 tg.grepStdout(`ok  \tt/t4\t\(cached\)`, "did not cache t/t4")
5499         }
5500 }
5501
5502 func TestTestCacheInputs(t *testing.T) {
5503         tooSlow(t)
5504
5505         if strings.Contains(os.Getenv("GODEBUG"), "gocacheverify") {
5506                 t.Skip("GODEBUG gocacheverify")
5507         }
5508         tg := testgo(t)
5509         defer tg.cleanup()
5510         tg.parallel()
5511         tg.makeTempdir()
5512         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5513         tg.setenv("GOCACHE", tg.path("cache"))
5514
5515         defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5516         defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"))
5517         tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("x"), 0644))
5518         old := time.Now().Add(-1 * time.Minute)
5519         tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5520         info, err := os.Stat(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"))
5521         if err != nil {
5522                 t.Fatal(err)
5523         }
5524         t.Logf("file.txt: old=%v, info.ModTime=%v", old, info.ModTime()) // help debug when Chtimes lies about succeeding
5525         tg.setenv("TESTKEY", "x")
5526
5527         tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), []byte("#!/bin/sh\nexit 0\n"), 0755))
5528         tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old, old))
5529
5530         tg.run("test", "testcache")
5531         tg.run("test", "testcache")
5532         tg.grepStdout(`\(cached\)`, "did not cache")
5533
5534         tg.setenv("TESTKEY", "y")
5535         tg.run("test", "testcache")
5536         tg.grepStdoutNot(`\(cached\)`, "did not notice env var change")
5537         tg.run("test", "testcache")
5538         tg.grepStdout(`\(cached\)`, "did not cache")
5539
5540         tg.run("test", "testcache", "-run=FileSize")
5541         tg.run("test", "testcache", "-run=FileSize")
5542         tg.grepStdout(`\(cached\)`, "did not cache")
5543         tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxx"), 0644))
5544         tg.run("test", "testcache", "-run=FileSize")
5545         tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5546         tg.run("test", "testcache", "-run=FileSize")
5547         tg.grepStdout(`\(cached\)`, "did not cache")
5548
5549         tg.run("test", "testcache", "-run=Chdir")
5550         tg.run("test", "testcache", "-run=Chdir")
5551         tg.grepStdout(`\(cached\)`, "did not cache")
5552         tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("xxxxx"), 0644))
5553         tg.run("test", "testcache", "-run=Chdir")
5554         tg.grepStdoutNot(`\(cached\)`, "did not notice file size change")
5555         tg.run("test", "testcache", "-run=Chdir")
5556         tg.grepStdout(`\(cached\)`, "did not cache")
5557
5558         tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old, old))
5559         tg.run("test", "testcache", "-run=FileContent")
5560         tg.run("test", "testcache", "-run=FileContent")
5561         tg.grepStdout(`\(cached\)`, "did not cache")
5562         tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), []byte("yyy"), 0644))
5563         old2 := old.Add(10 * time.Second)
5564         tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt"), old2, old2))
5565         tg.run("test", "testcache", "-run=FileContent")
5566         tg.grepStdoutNot(`\(cached\)`, "did not notice file content change")
5567         tg.run("test", "testcache", "-run=FileContent")
5568         tg.grepStdout(`\(cached\)`, "did not cache")
5569
5570         tg.run("test", "testcache", "-run=DirList")
5571         tg.run("test", "testcache", "-run=DirList")
5572         tg.grepStdout(`\(cached\)`, "did not cache")
5573         tg.must(os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/file.txt")))
5574         tg.run("test", "testcache", "-run=DirList")
5575         tg.grepStdoutNot(`\(cached\)`, "did not notice directory change")
5576         tg.run("test", "testcache", "-run=DirList")
5577         tg.grepStdout(`\(cached\)`, "did not cache")
5578
5579         tg.tempFile("file.txt", "")
5580         tg.must(ioutil.WriteFile(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"), []byte(`package testcache
5581
5582                 import (
5583                         "os"
5584                         "testing"
5585                 )
5586
5587                 func TestExternalFile(t *testing.T) {
5588                         os.Open(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5589                         _, err := os.Stat(`+fmt.Sprintf("%q", tg.path("file.txt"))+`)
5590                         if err != nil {
5591                                 t.Fatal(err)
5592                         }
5593                 }
5594         `), 0666))
5595         defer os.Remove(filepath.Join(tg.pwd(), "testdata/src/testcache/testcachetmp_test.go"))
5596         tg.run("test", "testcache", "-run=ExternalFile")
5597         tg.run("test", "testcache", "-run=ExternalFile")
5598         tg.grepStdout(`\(cached\)`, "did not cache")
5599         tg.must(os.Remove(filepath.Join(tg.tempdir, "file.txt")))
5600         tg.run("test", "testcache", "-run=ExternalFile")
5601         tg.grepStdout(`\(cached\)`, "did not cache")
5602
5603         switch runtime.GOOS {
5604         case "nacl", "plan9", "windows":
5605                 // no shell scripts
5606         default:
5607                 tg.run("test", "testcache", "-run=Exec")
5608                 tg.run("test", "testcache", "-run=Exec")
5609                 tg.grepStdout(`\(cached\)`, "did not cache")
5610                 tg.must(os.Chtimes(filepath.Join(tg.pwd(), "testdata/src/testcache/script.sh"), old2, old2))
5611                 tg.run("test", "testcache", "-run=Exec")
5612                 tg.grepStdoutNot(`\(cached\)`, "did not notice script change")
5613                 tg.run("test", "testcache", "-run=Exec")
5614                 tg.grepStdout(`\(cached\)`, "did not cache")
5615         }
5616 }
5617
5618 func TestTestVet(t *testing.T) {
5619         tooSlow(t)
5620         tg := testgo(t)
5621         defer tg.cleanup()
5622         tg.parallel()
5623
5624         tg.tempFile("p1_test.go", `
5625                 package p
5626                 import "testing"
5627                 func Test(t *testing.T) {
5628                         t.Logf("%d") // oops
5629                 }
5630         `)
5631
5632         tg.runFail("test", tg.path("p1_test.go"))
5633         tg.grepStderr(`Logf format %d`, "did not diagnose bad Logf")
5634         tg.run("test", "-vet=off", tg.path("p1_test.go"))
5635         tg.grepStdout(`^ok`, "did not print test summary")
5636
5637         tg.tempFile("p1.go", `
5638                 package p
5639                 import "fmt"
5640                 func F() {
5641                         fmt.Printf("%d") // oops
5642                 }
5643         `)
5644         tg.runFail("test", tg.path("p1.go"))
5645         tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5646         tg.run("test", "-x", "-vet=shift", tg.path("p1.go"))
5647         tg.grepStderr(`[\\/]vet.*-shift`, "did not run vet with -shift")
5648         tg.grepStdout(`\[no test files\]`, "did not print test summary")
5649         tg.run("test", "-vet=off", tg.path("p1.go"))
5650         tg.grepStdout(`\[no test files\]`, "did not print test summary")
5651
5652         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5653         tg.run("test", "vetcycle") // must not fail; #22890
5654
5655         tg.runFail("test", "vetfail/...")
5656         tg.grepStderr(`Printf format %d`, "did not diagnose bad Printf")
5657         tg.grepStdout(`ok\s+vetfail/p2`, "did not run vetfail/p2")
5658
5659         // Use -a so that we need to recompute the vet-specific export data for
5660         // vetfail/p1.
5661         tg.run("test", "-a", "vetfail/p2")
5662         tg.grepStderrNot(`invalid.*constraint`, "did diagnose bad build constraint in vetxonly mode")
5663 }
5664
5665 func TestTestSkipVetAfterFailedBuild(t *testing.T) {
5666         tg := testgo(t)
5667         defer tg.cleanup()
5668         tg.parallel()
5669
5670         tg.tempFile("x_test.go", `package x
5671                 func f() {
5672                         return 1
5673                 }
5674         `)
5675
5676         tg.runFail("test", tg.path("x_test.go"))
5677         tg.grepStderrNot(`vet`, "vet should be skipped after the failed build")
5678 }
5679
5680 func TestTestVetRebuild(t *testing.T) {
5681         tooSlow(t)
5682         tg := testgo(t)
5683         defer tg.cleanup()
5684         tg.parallel()
5685
5686         // golang.org/issue/23701.
5687         // b_test imports b with augmented method from export_test.go.
5688         // b_test also imports a, which imports b.
5689         // Must not accidentally see un-augmented b propagate through a to b_test.
5690         tg.tempFile("src/a/a.go", `package a
5691                 import "b"
5692                 type Type struct{}
5693                 func (*Type) M() b.T {return 0}
5694         `)
5695         tg.tempFile("src/b/b.go", `package b
5696                 type T int
5697                 type I interface {M() T}
5698         `)
5699         tg.tempFile("src/b/export_test.go", `package b
5700                 func (*T) Method() *T { return nil }
5701         `)
5702         tg.tempFile("src/b/b_test.go", `package b_test
5703                 import (
5704                         "testing"
5705                         "a"
5706                         . "b"
5707                 )
5708                 func TestBroken(t *testing.T) {
5709                         x := new(T)
5710                         x.Method()
5711                         _ = new(a.Type)
5712                 }
5713         `)
5714
5715         tg.setenv("GOPATH", tg.path("."))
5716         tg.run("test", "b")
5717         tg.run("vet", "b")
5718 }
5719
5720 func TestInstallDeps(t *testing.T) {
5721         tooSlow(t)
5722         tg := testgo(t)
5723         defer tg.cleanup()
5724         tg.parallel()
5725         tg.makeTempdir()
5726         tg.setenv("GOPATH", tg.tempdir)
5727
5728         tg.tempFile("src/p1/p1.go", "package p1\nvar X =  1\n")
5729         tg.tempFile("src/p2/p2.go", "package p2\nimport _ \"p1\"\n")
5730         tg.tempFile("src/main1/main.go", "package main\nimport _ \"p2\"\nfunc main() {}\n")
5731
5732         tg.run("list", "-f={{.Target}}", "p1")
5733         p1 := strings.TrimSpace(tg.getStdout())
5734         tg.run("list", "-f={{.Target}}", "p2")
5735         p2 := strings.TrimSpace(tg.getStdout())
5736         tg.run("list", "-f={{.Target}}", "main1")
5737         main1 := strings.TrimSpace(tg.getStdout())
5738
5739         tg.run("install", "main1")
5740
5741         tg.mustExist(main1)
5742         tg.mustNotExist(p2)
5743         tg.mustNotExist(p1)
5744
5745         tg.run("install", "p2")
5746         tg.mustExist(p2)
5747         tg.mustNotExist(p1)
5748
5749         // don't let install -i overwrite runtime
5750         tg.wantNotStale("runtime", "", "must be non-stale before install -i")
5751
5752         tg.run("install", "-i", "main1")
5753         tg.mustExist(p1)
5754         tg.must(os.Remove(p1))
5755
5756         tg.run("install", "-i", "p2")
5757         tg.mustExist(p1)
5758 }
5759
5760 func TestFmtLoadErrors(t *testing.T) {
5761         tg := testgo(t)
5762         defer tg.cleanup()
5763         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5764         tg.runFail("fmt", "does-not-exist")
5765         tg.run("fmt", "-n", "exclude")
5766 }
5767
5768 func TestGoTestMinusN(t *testing.T) {
5769         // Intent here is to verify that 'go test -n' works without crashing.
5770         // This reuses flag_test.go, but really any test would do.
5771         tg := testgo(t)
5772         defer tg.cleanup()
5773         tg.run("test", "testdata/flag_test.go", "-n", "-args", "-v=7")
5774 }
5775
5776 func TestGoTestJSON(t *testing.T) {
5777         skipIfGccgo(t, "gccgo does not have standard packages")
5778         tooSlow(t)
5779
5780         tg := testgo(t)
5781         defer tg.cleanup()
5782         tg.parallel()
5783         tg.makeTempdir()
5784         tg.setenv("GOCACHE", tg.tempdir)
5785         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
5786
5787         // It would be nice to test that the output is interlaced
5788         // but it seems to be impossible to do that in a short test
5789         // that isn't also flaky. Just check that we get JSON output.
5790         tg.run("test", "-json", "-short", "-v", "errors", "empty/pkg", "skipper")
5791         tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5792         tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5793
5794         tg.grepStdout(`"Action":"output","Package":"empty/pkg","Output":".*no test files`, "did not see no test files print")
5795         tg.grepStdout(`"Action":"skip","Package":"empty/pkg"`, "did not see skip")
5796
5797         tg.grepStdout(`"Action":"output","Package":"skipper","Test":"Test","Output":"--- SKIP:`, "did not see SKIP output")
5798         tg.grepStdout(`"Action":"skip","Package":"skipper","Test":"Test"`, "did not see skip result for Test")
5799
5800         tg.run("test", "-json", "-short", "-v", "errors")
5801         tg.grepStdout(`"Action":"output","Package":"errors","Output":".*\(cached\)`, "did not see no cached output")
5802
5803         tg.run("test", "-json", "-bench=NONE", "-short", "-v", "errors")
5804         tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5805         tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5806
5807         tg.run("test", "-o", tg.path("errors.test.exe"), "-c", "errors")
5808         tg.run("tool", "test2json", "-p", "errors", tg.path("errors.test.exe"), "-test.v", "-test.short")
5809         tg.grepStdout(`"Package":"errors"`, "did not see JSON output")
5810         tg.grepStdout(`"Action":"run"`, "did not see JSON output")
5811         tg.grepStdout(`\{"Action":"pass","Package":"errors"\}`, "did not see final pass")
5812 }
5813
5814 func TestFailFast(t *testing.T) {
5815         tooSlow(t)
5816         tg := testgo(t)
5817         defer tg.cleanup()
5818
5819         tests := []struct {
5820                 run      string
5821                 failfast bool
5822                 nfail    int
5823         }{
5824                 {"TestFailingA", true, 1},
5825                 {"TestFailing[AB]", true, 1},
5826                 {"TestFailing[AB]", false, 2},
5827                 // mix with non-failing tests:
5828                 {"TestA|TestFailing[AB]", true, 1},
5829                 {"TestA|TestFailing[AB]", false, 2},
5830                 // mix with parallel tests:
5831                 {"TestFailingB|TestParallelFailingA", true, 2},
5832                 {"TestFailingB|TestParallelFailingA", false, 2},
5833                 {"TestFailingB|TestParallelFailing[AB]", true, 3},
5834                 {"TestFailingB|TestParallelFailing[AB]", false, 3},
5835                 // mix with parallel sub-tests
5836                 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", true, 3},
5837                 {"TestFailingB|TestParallelFailing[AB]|TestParallelFailingSubtestsA", false, 5},
5838                 {"TestParallelFailingSubtestsA", true, 1},
5839                 // only parallels:
5840                 {"TestParallelFailing[AB]", false, 2},
5841                 // non-parallel subtests:
5842                 {"TestFailingSubtestsA", true, 1},
5843                 {"TestFailingSubtestsA", false, 2},
5844                 // fatal test
5845                 {"TestFatal[CD]", true, 1},
5846                 {"TestFatal[CD]", false, 2},
5847         }
5848
5849         for _, tt := range tests {
5850                 t.Run(tt.run, func(t *testing.T) {
5851                         tg.runFail("test", "./testdata/src/failfast_test.go", "-run="+tt.run, "-failfast="+strconv.FormatBool(tt.failfast))
5852
5853                         nfail := strings.Count(tg.getStdout(), "FAIL - ")
5854
5855                         if nfail != tt.nfail {
5856                                 t.Errorf("go test -run=%s -failfast=%t printed %d FAILs, want %d", tt.run, tt.failfast, nfail, tt.nfail)
5857                         }
5858                 })
5859         }
5860 }
5861
5862 // Issue 22986.
5863 func TestImportPath(t *testing.T) {
5864         tooSlow(t)
5865         tg := testgo(t)
5866         defer tg.cleanup()
5867         tg.parallel()
5868
5869         tg.tempFile("src/a/a.go", `
5870 package main
5871
5872 import (
5873         "log"
5874         p "a/p-1.0"
5875 )
5876
5877 func main() {
5878         if !p.V {
5879                 log.Fatal("false")
5880         }
5881 }`)
5882
5883         tg.tempFile("src/a/a_test.go", `
5884 package main_test
5885
5886 import (
5887         p "a/p-1.0"
5888         "testing"
5889 )
5890
5891 func TestV(t *testing.T) {
5892         if !p.V {
5893                 t.Fatal("false")
5894         }
5895 }`)
5896
5897         tg.tempFile("src/a/p-1.0/p.go", `
5898 package p
5899
5900 var V = true
5901
5902 func init() {}
5903 `)
5904
5905         tg.setenv("GOPATH", tg.path("."))
5906         tg.run("build", "-o", tg.path("a.exe"), "a")
5907         tg.run("test", "a")
5908 }
5909
5910 func TestBadCommandLines(t *testing.T) {
5911         tg := testgo(t)
5912         defer tg.cleanup()
5913
5914         tg.tempFile("src/x/x.go", "package x\n")
5915         tg.setenv("GOPATH", tg.path("."))
5916
5917         tg.run("build", "x")
5918
5919         tg.tempFile("src/x/@y.go", "package x\n")
5920         tg.runFail("build", "x")
5921         tg.grepStderr("invalid input file name \"@y.go\"", "did not reject @y.go")
5922         tg.must(os.Remove(tg.path("src/x/@y.go")))
5923
5924         tg.tempFile("src/x/-y.go", "package x\n")
5925         tg.runFail("build", "x")
5926         tg.grepStderr("invalid input file name \"-y.go\"", "did not reject -y.go")
5927         tg.must(os.Remove(tg.path("src/x/-y.go")))
5928
5929         if runtime.Compiler == "gccgo" {
5930                 tg.runFail("build", "-gccgoflags=all=@x", "x")
5931         } else {
5932                 tg.runFail("build", "-gcflags=all=@x", "x")
5933         }
5934         tg.grepStderr("invalid command-line argument @x in command", "did not reject @x during exec")
5935
5936         tg.tempFile("src/@x/x.go", "package x\n")
5937         tg.setenv("GOPATH", tg.path("."))
5938         tg.runFail("build", "@x")
5939         tg.grepStderr("invalid input directory name \"@x\"|cannot use path@version syntax", "did not reject @x directory")
5940
5941         tg.tempFile("src/@x/y/y.go", "package y\n")
5942         tg.setenv("GOPATH", tg.path("."))
5943         tg.runFail("build", "@x/y")
5944         tg.grepStderr("invalid import path \"@x/y\"|cannot use path@version syntax", "did not reject @x/y import path")
5945
5946         tg.tempFile("src/-x/x.go", "package x\n")
5947         tg.setenv("GOPATH", tg.path("."))
5948         tg.runFail("build", "--", "-x")
5949         tg.grepStderr("invalid input directory name \"-x\"", "did not reject -x directory")
5950
5951         tg.tempFile("src/-x/y/y.go", "package y\n")
5952         tg.setenv("GOPATH", tg.path("."))
5953         tg.runFail("build", "--", "-x/y")
5954         tg.grepStderr("invalid import path \"-x/y\"", "did not reject -x/y import path")
5955 }
5956
5957 func TestBadCgoDirectives(t *testing.T) {
5958         if !canCgo {
5959                 t.Skip("no cgo")
5960         }
5961         tooSlow(t)
5962         tg := testgo(t)
5963         defer tg.cleanup()
5964
5965         tg.tempFile("src/x/x.go", "package x\n")
5966         tg.setenv("GOPATH", tg.path("."))
5967
5968         if runtime.Compiler == "gc" {
5969                 tg.tempFile("src/x/x.go", `package x
5970
5971                         //go:cgo_ldflag "-fplugin=foo.so"
5972
5973                         import "C"
5974                 `)
5975                 tg.runFail("build", "x")
5976                 tg.grepStderr("//go:cgo_ldflag .* only allowed in cgo-generated code", "did not reject //go:cgo_ldflag directive")
5977         }
5978
5979         tg.must(os.Remove(tg.path("src/x/x.go")))
5980         tg.runFail("build", "x")
5981         tg.grepStderr("no Go files", "did not report missing source code")
5982         tg.tempFile("src/x/_cgo_yy.go", `package x
5983
5984                 //go:cgo_ldflag "-fplugin=foo.so"
5985
5986                 import "C"
5987         `)
5988         tg.runFail("build", "x")
5989         tg.grepStderr("no Go files", "did not report missing source code") // _* files are ignored...
5990
5991         if runtime.Compiler == "gc" {
5992                 tg.runFail("build", tg.path("src/x/_cgo_yy.go")) // ... but if forced, the comment is rejected
5993                 // Actually, today there is a separate issue that _ files named
5994                 // on the command line are ignored. Once that is fixed,
5995                 // we want to see the cgo_ldflag error.
5996                 tg.grepStderr("//go:cgo_ldflag only allowed in cgo-generated code|no Go files", "did not reject //go:cgo_ldflag directive")
5997         }
5998
5999         tg.must(os.Remove(tg.path("src/x/_cgo_yy.go")))
6000
6001         tg.tempFile("src/x/x.go", "package x\n")
6002         tg.tempFile("src/x/y.go", `package x
6003                 // #cgo CFLAGS: -fplugin=foo.so
6004                 import "C"
6005         `)
6006         tg.runFail("build", "x")
6007         tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
6008
6009         tg.tempFile("src/x/y.go", `package x
6010                 // #cgo CFLAGS: -Ibar -fplugin=foo.so
6011                 import "C"
6012         `)
6013         tg.runFail("build", "x")
6014         tg.grepStderr("invalid flag in #cgo CFLAGS: -fplugin=foo.so", "did not reject -fplugin")
6015
6016         tg.tempFile("src/x/y.go", `package x
6017                 // #cgo pkg-config: -foo
6018                 import "C"
6019         `)
6020         tg.runFail("build", "x")
6021         tg.grepStderr("invalid pkg-config package name: -foo", "did not reject pkg-config: -foo")
6022
6023         tg.tempFile("src/x/y.go", `package x
6024                 // #cgo pkg-config: @foo
6025                 import "C"
6026         `)
6027         tg.runFail("build", "x")
6028         tg.grepStderr("invalid pkg-config package name: @foo", "did not reject pkg-config: -foo")
6029
6030         tg.tempFile("src/x/y.go", `package x
6031                 // #cgo CFLAGS: @foo
6032                 import "C"
6033         `)
6034         tg.runFail("build", "x")
6035         tg.grepStderr("invalid flag in #cgo CFLAGS: @foo", "did not reject @foo flag")
6036
6037         tg.tempFile("src/x/y.go", `package x
6038                 // #cgo CFLAGS: -D
6039                 import "C"
6040         `)
6041         tg.runFail("build", "x")
6042         tg.grepStderr("invalid flag in #cgo CFLAGS: -D without argument", "did not reject trailing -I flag")
6043
6044         // Note that -I @foo is allowed because we rewrite it into -I /path/to/src/@foo
6045         // before the check is applied. There's no such rewrite for -D.
6046
6047         tg.tempFile("src/x/y.go", `package x
6048                 // #cgo CFLAGS: -D @foo
6049                 import "C"
6050         `)
6051         tg.runFail("build", "x")
6052         tg.grepStderr("invalid flag in #cgo CFLAGS: -D @foo", "did not reject -D @foo flag")
6053
6054         tg.tempFile("src/x/y.go", `package x
6055                 // #cgo CFLAGS: -D@foo
6056                 import "C"
6057         `)
6058         tg.runFail("build", "x")
6059         tg.grepStderr("invalid flag in #cgo CFLAGS: -D@foo", "did not reject -D@foo flag")
6060
6061         tg.setenv("CGO_CFLAGS", "-D@foo")
6062         tg.tempFile("src/x/y.go", `package x
6063                 import "C"
6064         `)
6065         tg.run("build", "-n", "x")
6066         tg.grepStderr("-D@foo", "did not find -D@foo in commands")
6067 }
6068
6069 func TestTwoPkgConfigs(t *testing.T) {
6070         if !canCgo {
6071                 t.Skip("no cgo")
6072         }
6073         if runtime.GOOS == "windows" || runtime.GOOS == "plan9" {
6074                 t.Skipf("no shell scripts on %s", runtime.GOOS)
6075         }
6076         tooSlow(t)
6077         tg := testgo(t)
6078         defer tg.cleanup()
6079         tg.parallel()
6080         tg.tempFile("src/x/a.go", `package x
6081                 // #cgo pkg-config: --static a
6082                 import "C"
6083         `)
6084         tg.tempFile("src/x/b.go", `package x
6085                 // #cgo pkg-config: --static a
6086                 import "C"
6087         `)
6088         tg.tempFile("pkg-config.sh", `#!/bin/sh
6089 echo $* >>`+tg.path("pkg-config.out"))
6090         tg.must(os.Chmod(tg.path("pkg-config.sh"), 0755))
6091         tg.setenv("GOPATH", tg.path("."))
6092         tg.setenv("PKG_CONFIG", tg.path("pkg-config.sh"))
6093         tg.run("build", "x")
6094         out, err := ioutil.ReadFile(tg.path("pkg-config.out"))
6095         tg.must(err)
6096         out = bytes.TrimSpace(out)
6097         want := "--cflags --static --static -- a a\n--libs --static --static -- a a"
6098         if !bytes.Equal(out, []byte(want)) {
6099                 t.Errorf("got %q want %q", out, want)
6100         }
6101 }
6102
6103 func TestCgoCache(t *testing.T) {
6104         if !canCgo {
6105                 t.Skip("no cgo")
6106         }
6107         tooSlow(t)
6108
6109         tg := testgo(t)
6110         defer tg.cleanup()
6111         tg.parallel()
6112         tg.tempFile("src/x/a.go", `package main
6113                 // #ifndef VAL
6114                 // #define VAL 0
6115                 // #endif
6116                 // int val = VAL;
6117                 import "C"
6118                 import "fmt"
6119                 func main() { fmt.Println(C.val) }
6120         `)
6121         tg.setenv("GOPATH", tg.path("."))
6122         exe := tg.path("x.exe")
6123         tg.run("build", "-o", exe, "x")
6124         tg.setenv("CGO_LDFLAGS", "-lnosuchlibraryexists")
6125         tg.runFail("build", "-o", exe, "x")
6126         tg.grepStderr(`nosuchlibraryexists`, "did not run linker with changed CGO_LDFLAGS")
6127 }
6128
6129 // Issue 23982
6130 func TestFilepathUnderCwdFormat(t *testing.T) {
6131         tg := testgo(t)
6132         defer tg.cleanup()
6133         tg.run("test", "-x", "-cover", "log")
6134         tg.grepStderrNot(`\.log\.cover\.go`, "-x output should contain correctly formatted filepath under cwd")
6135 }
6136
6137 // Issue 24396.
6138 func TestDontReportRemoveOfEmptyDir(t *testing.T) {
6139         tg := testgo(t)
6140         defer tg.cleanup()
6141         tg.parallel()
6142         tg.tempFile("src/a/a.go", `package a`)
6143         tg.setenv("GOPATH", tg.path("."))
6144         tg.run("install", "-x", "a")
6145         tg.run("install", "-x", "a")
6146         // The second install should have printed only a WORK= line,
6147         // nothing else.
6148         if bytes.Count(tg.stdout.Bytes(), []byte{'\n'})+bytes.Count(tg.stderr.Bytes(), []byte{'\n'}) > 1 {
6149                 t.Error("unnecessary output when installing installed package")
6150         }
6151 }
6152
6153 // Issue 24704.
6154 func TestLinkerTmpDirIsDeleted(t *testing.T) {
6155         skipIfGccgo(t, "gccgo does not use cmd/link")
6156         if !canCgo {
6157                 t.Skip("skipping because cgo not enabled")
6158         }
6159         tooSlow(t)
6160
6161         tg := testgo(t)
6162         defer tg.cleanup()
6163         tg.parallel()
6164         tg.tempFile("a.go", `package main; import "C"; func main() {}`)
6165         tg.run("build", "-ldflags", "-v", "-o", os.DevNull, tg.path("a.go"))
6166         // Find line that has "host link:" in linker output.
6167         stderr := tg.getStderr()
6168         var hostLinkLine string
6169         for _, line := range strings.Split(stderr, "\n") {
6170                 if !strings.Contains(line, "host link:") {
6171                         continue
6172                 }
6173                 hostLinkLine = line
6174                 break
6175         }
6176         if hostLinkLine == "" {
6177                 t.Fatal(`fail to find with "host link:" string in linker output`)
6178         }
6179         // Find parameter, like "/tmp/go-link-408556474/go.o" inside of
6180         // "host link:" line, and extract temp directory /tmp/go-link-408556474
6181         // out of it.
6182         tmpdir := hostLinkLine
6183         i := strings.Index(tmpdir, `go.o"`)
6184         if i == -1 {
6185                 t.Fatalf(`fail to find "go.o" in "host link:" line %q`, hostLinkLine)
6186         }
6187         tmpdir = tmpdir[:i-1]
6188         i = strings.LastIndex(tmpdir, `"`)
6189         if i == -1 {
6190                 t.Fatalf(`fail to find " in "host link:" line %q`, hostLinkLine)
6191         }
6192         tmpdir = tmpdir[i+1:]
6193         // Verify that temp directory has been removed.
6194         _, err := os.Stat(tmpdir)
6195         if err == nil {
6196                 t.Fatalf("temp directory %q has not been removed", tmpdir)
6197         }
6198         if !os.IsNotExist(err) {
6199                 t.Fatalf("Stat(%q) returns unexpected error: %v", tmpdir, err)
6200         }
6201 }
6202
6203 func testCDAndGOPATHAreDifferent(tg *testgoData, cd, gopath string) {
6204         skipIfGccgo(tg.t, "gccgo does not support -ldflags -X")
6205         tg.setenv("GOPATH", gopath)
6206
6207         tg.tempDir("dir")
6208         exe := tg.path("dir/a.exe")
6209
6210         tg.cd(cd)
6211
6212         tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked")
6213         out, err := exec.Command(exe).CombinedOutput()
6214         if err != nil {
6215                 tg.t.Fatal(err)
6216         }
6217         if string(out) != "linkXworked\n" {
6218                 tg.t.Errorf(`incorrect output with GOPATH=%q and CD=%q: expected "linkXworked\n", but have %q`, gopath, cd, string(out))
6219         }
6220 }
6221
6222 func TestCDAndGOPATHAreDifferent(t *testing.T) {
6223         tg := testgo(t)
6224         defer tg.cleanup()
6225
6226         gopath := filepath.Join(tg.pwd(), "testdata")
6227         cd := filepath.Join(gopath, "src/my.pkg/main")
6228
6229         testCDAndGOPATHAreDifferent(tg, cd, gopath)
6230         if runtime.GOOS == "windows" {
6231                 testCDAndGOPATHAreDifferent(tg, cd, strings.ReplaceAll(gopath, `\`, `/`))
6232                 testCDAndGOPATHAreDifferent(tg, cd, strings.ToUpper(gopath))
6233                 testCDAndGOPATHAreDifferent(tg, cd, strings.ToLower(gopath))
6234         }
6235 }
6236
6237 // Issue 26242.
6238 func TestGoTestWithoutTests(t *testing.T) {
6239         tg := testgo(t)
6240         defer tg.cleanup()
6241         tg.parallel()
6242         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
6243         tg.run("test", "testnorun")
6244         tg.grepStdout(`testnorun\t\[no test files\]`, "do not want test to run")
6245 }
6246
6247 // Issue 25579.
6248 func TestGoBuildDashODevNull(t *testing.T) {
6249         tooSlow(t)
6250         tg := testgo(t)
6251         defer tg.cleanup()
6252         tg.parallel()
6253         tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
6254         tg.run("build", "-o", os.DevNull, filepath.Join(tg.pwd(), "testdata", "src", "hello", "hello.go"))
6255         tg.mustNotExist("hello")
6256         tg.mustNotExist("hello.exe")
6257 }
6258
6259 // Issue 25093.
6260 func TestCoverpkgTestOnly(t *testing.T) {
6261         skipIfGccgo(t, "gccgo has no cover tool")
6262         tooSlow(t)
6263         tg := testgo(t)
6264         defer tg.cleanup()
6265         tg.parallel()
6266         tg.tempFile("src/a/a.go", `package a
6267                 func F(i int) int {
6268                         return i*i
6269                 }`)
6270         tg.tempFile("src/atest/a_test.go", `
6271                 package a_test
6272                 import ( "a"; "testing" )
6273                 func TestF(t *testing.T) { a.F(2) }
6274         `)
6275         tg.setenv("GOPATH", tg.path("."))
6276         tg.run("test", "-coverpkg=a", "atest")
6277         tg.grepStderrNot("no packages being tested depend on matches", "bad match message")
6278         tg.grepStdout("coverage: 100", "no coverage")
6279 }