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