github.com/FenixAra/go@v0.0.0-20170127160404-96ea0918e670/src/cmd/go/go_test.go (about)

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