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