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