...
Run Format

Source file src/cmd/go/go_test.go

Documentation: cmd/go

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

View as plain text