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