github.com/zxy12/go_duplicate_112_new@v0.0.0-20200807091221-747231827200/src/cmd/go/go_test.go (about)

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