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