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