...
Run Format

Source file src/cmd/go/go_test.go

Documentation: cmd/go

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

View as plain text