github.com/c0deoo1/golang1.5@v0.0.0-20220525150107-c87c805d4593/src/cmd/go/go_test.go (about)

     1  // Copyright 2015 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main_test
     6  
     7  import (
     8  	"bytes"
     9  	"flag"
    10  	"fmt"
    11  	"go/build"
    12  	"go/format"
    13  	"internal/testenv"
    14  	"io"
    15  	"io/ioutil"
    16  	"os"
    17  	"os/exec"
    18  	"path/filepath"
    19  	"regexp"
    20  	"runtime"
    21  	"strconv"
    22  	"strings"
    23  	"testing"
    24  	"time"
    25  )
    26  
    27  var (
    28  	canRun  = true  // whether we can run go or ./testgo
    29  	canRace = false // whether we can run the race detector
    30  	canCgo  = false // whether we can use cgo
    31  
    32  	exeSuffix string // ".exe" on Windows
    33  
    34  	builder             = testenv.Builder()
    35  	skipExternalBuilder = false // skip external tests on this builder
    36  )
    37  
    38  func init() {
    39  	switch runtime.GOOS {
    40  	case "android", "nacl":
    41  		canRun = false
    42  	case "darwin":
    43  		switch runtime.GOARCH {
    44  		case "arm", "arm64":
    45  			canRun = false
    46  		}
    47  	}
    48  
    49  	if strings.HasPrefix(builder+"-", "freebsd-arm-") {
    50  		skipExternalBuilder = true
    51  		canRun = false
    52  	}
    53  
    54  	switch runtime.GOOS {
    55  	case "windows":
    56  		exeSuffix = ".exe"
    57  	}
    58  }
    59  
    60  // The TestMain function creates a go command for testing purposes and
    61  // deletes it after the tests have been run.
    62  func TestMain(m *testing.M) {
    63  	flag.Parse()
    64  
    65  	if canRun {
    66  		out, err := exec.Command("go", "build", "-tags", "testgo", "-o", "testgo"+exeSuffix).CombinedOutput()
    67  		if err != nil {
    68  			fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out)
    69  			os.Exit(2)
    70  		}
    71  
    72  		if out, err := exec.Command("./testgo"+exeSuffix, "env", "CGO_ENABLED").Output(); err != nil {
    73  			fmt.Fprintf(os.Stderr, "running testgo failed: %v\n", err)
    74  			canRun = false
    75  		} else {
    76  			canCgo, err = strconv.ParseBool(strings.TrimSpace(string(out)))
    77  			if err != nil {
    78  				fmt.Fprintf(os.Stderr, "can't parse go env CGO_ENABLED output: %v\n", strings.TrimSpace(string(out)))
    79  			}
    80  		}
    81  
    82  		switch runtime.GOOS {
    83  		case "linux", "darwin", "freebsd", "windows":
    84  			canRace = canCgo && runtime.GOARCH == "amd64"
    85  		}
    86  
    87  		measureTick("./testgo" + exeSuffix)
    88  	}
    89  
    90  	// Don't let these environment variables confuse the test.
    91  	os.Unsetenv("GOBIN")
    92  	os.Unsetenv("GOPATH")
    93  
    94  	r := m.Run()
    95  
    96  	if canRun {
    97  		os.Remove("testgo" + exeSuffix)
    98  	}
    99  
   100  	os.Exit(r)
   101  }
   102  
   103  // The length of an mtime tick on this system.  This is an estimate of
   104  // how long we need to sleep to ensure that the mtime of two files is
   105  // different.
   106  var mtimeTick time.Duration
   107  
   108  // measureTick sets mtimeTick by looking at the rounding of the mtime
   109  // of a file.
   110  func measureTick(path string) {
   111  	st, err := os.Stat(path)
   112  	if err != nil {
   113  		// Default to one second, the most conservative value.
   114  		mtimeTick = time.Second
   115  		return
   116  	}
   117  	mtime := st.ModTime()
   118  	t := time.Microsecond
   119  	for mtime.Round(t).Equal(mtime) && t < time.Second {
   120  		t *= 10
   121  	}
   122  	mtimeTick = t
   123  }
   124  
   125  // Manage a single run of the testgo binary.
   126  type testgoData struct {
   127  	t              *testing.T
   128  	temps          []string
   129  	wd             string
   130  	env            []string
   131  	tempdir        string
   132  	ran            bool
   133  	inParallel     bool
   134  	stdout, stderr bytes.Buffer
   135  }
   136  
   137  // testgo sets up for a test that runs testgo.
   138  func testgo(t *testing.T) *testgoData {
   139  	testenv.MustHaveGoBuild(t)
   140  
   141  	if skipExternalBuilder {
   142  		t.Skip("skipping external tests on %s builder", builder)
   143  	}
   144  
   145  	return &testgoData{t: t}
   146  }
   147  
   148  // must gives a fatal error if err is not nil.
   149  func (tg *testgoData) must(err error) {
   150  	if err != nil {
   151  		tg.t.Fatal(err)
   152  	}
   153  }
   154  
   155  // check gives a test non-fatal error if err is not nil.
   156  func (tg *testgoData) check(err error) {
   157  	if err != nil {
   158  		tg.t.Error(err)
   159  	}
   160  }
   161  
   162  // parallel runs the test in parallel by calling t.Parallel.
   163  func (tg *testgoData) parallel() {
   164  	if tg.ran {
   165  		tg.t.Fatal("internal testsuite error: call to parallel after run")
   166  	}
   167  	if tg.wd != "" {
   168  		tg.t.Fatal("internal testsuite error: call to parallel after cd")
   169  	}
   170  	for _, e := range tg.env {
   171  		if strings.HasPrefix(e, "GOROOT=") || strings.HasPrefix(e, "GOPATH=") || strings.HasPrefix(e, "GOBIN=") {
   172  			val := e[strings.Index(e, "=")+1:]
   173  			if strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata") {
   174  				tg.t.Fatalf("internal testsuite error: call to parallel with testdata in environment (%s)", e)
   175  			}
   176  		}
   177  	}
   178  	tg.inParallel = true
   179  	tg.t.Parallel()
   180  }
   181  
   182  // pwd returns the current directory.
   183  func (tg *testgoData) pwd() string {
   184  	wd, err := os.Getwd()
   185  	if err != nil {
   186  		tg.t.Fatalf("could not get working directory: %v", err)
   187  	}
   188  	return wd
   189  }
   190  
   191  // cd changes the current directory to the named directory.  Note that
   192  // using this means that the test must not be run in parallel with any
   193  // other tests.
   194  func (tg *testgoData) cd(dir string) {
   195  	if tg.inParallel {
   196  		tg.t.Fatal("internal testsuite error: changing directory when running in parallel")
   197  	}
   198  	if tg.wd == "" {
   199  		tg.wd = tg.pwd()
   200  	}
   201  	abs, err := filepath.Abs(dir)
   202  	tg.must(os.Chdir(dir))
   203  	if err == nil {
   204  		tg.setenv("PWD", abs)
   205  	}
   206  }
   207  
   208  // sleep sleeps for one tick, where a tick is a conservative estimate
   209  // of how long it takes for a file modification to get a different
   210  // mtime.
   211  func (tg *testgoData) sleep() {
   212  	time.Sleep(mtimeTick)
   213  }
   214  
   215  // setenv sets an environment variable to use when running the test go
   216  // command.
   217  func (tg *testgoData) setenv(name, val string) {
   218  	if tg.inParallel && (name == "GOROOT" || name == "GOPATH" || name == "GOBIN") && (strings.HasPrefix(val, "testdata") || strings.HasPrefix(val, "./testdata")) {
   219  		tg.t.Fatalf("internal testsuite error: call to setenv with testdata (%s=%s) after parallel", name, val)
   220  	}
   221  	tg.unsetenv(name)
   222  	tg.env = append(tg.env, name+"="+val)
   223  }
   224  
   225  // unsetenv removes an environment variable.
   226  func (tg *testgoData) unsetenv(name string) {
   227  	if tg.env == nil {
   228  		tg.env = append([]string(nil), os.Environ()...)
   229  	}
   230  	for i, v := range tg.env {
   231  		if strings.HasPrefix(v, name+"=") {
   232  			tg.env = append(tg.env[:i], tg.env[i+1:]...)
   233  			break
   234  		}
   235  	}
   236  }
   237  
   238  // doRun runs the test go command, recording stdout and stderr and
   239  // returning exit status.
   240  func (tg *testgoData) doRun(args []string) error {
   241  	if !canRun {
   242  		panic("testgoData.doRun called but canRun false")
   243  	}
   244  	if tg.inParallel {
   245  		for _, arg := range args {
   246  			if strings.HasPrefix(arg, "testdata") || strings.HasPrefix(arg, "./testdata") {
   247  				tg.t.Fatal("internal testsuite error: parallel run using testdata")
   248  			}
   249  		}
   250  	}
   251  	tg.t.Logf("running testgo %v", args)
   252  	var prog string
   253  	if tg.wd == "" {
   254  		prog = "./testgo" + exeSuffix
   255  	} else {
   256  		prog = filepath.Join(tg.wd, "testgo"+exeSuffix)
   257  	}
   258  	cmd := exec.Command(prog, args...)
   259  	tg.stdout.Reset()
   260  	tg.stderr.Reset()
   261  	cmd.Stdout = &tg.stdout
   262  	cmd.Stderr = &tg.stderr
   263  	cmd.Env = tg.env
   264  	status := cmd.Run()
   265  	if tg.stdout.Len() > 0 {
   266  		tg.t.Log("standard output:")
   267  		tg.t.Log(tg.stdout.String())
   268  	}
   269  	if tg.stderr.Len() > 0 {
   270  		tg.t.Log("standard error:")
   271  		tg.t.Log(tg.stderr.String())
   272  	}
   273  	tg.ran = true
   274  	return status
   275  }
   276  
   277  // run runs the test go command, and expects it to succeed.
   278  func (tg *testgoData) run(args ...string) {
   279  	if status := tg.doRun(args); status != nil {
   280  		tg.t.Logf("go %v failed unexpectedly: %v", args, status)
   281  		tg.t.FailNow()
   282  	}
   283  }
   284  
   285  // runFail runs the test go command, and expects it to fail.
   286  func (tg *testgoData) runFail(args ...string) {
   287  	if status := tg.doRun(args); status == nil {
   288  		tg.t.Fatal("testgo succeeded unexpectedly")
   289  	} else {
   290  		tg.t.Log("testgo failed as expected:", status)
   291  	}
   292  }
   293  
   294  // runGit runs a git command, and expects it to succeed.
   295  func (tg *testgoData) runGit(dir string, args ...string) {
   296  	cmd := exec.Command("git", args...)
   297  	tg.stdout.Reset()
   298  	tg.stderr.Reset()
   299  	cmd.Stdout = &tg.stdout
   300  	cmd.Stderr = &tg.stderr
   301  	cmd.Dir = dir
   302  	cmd.Env = tg.env
   303  	status := cmd.Run()
   304  	if tg.stdout.Len() > 0 {
   305  		tg.t.Log("git standard output:")
   306  		tg.t.Log(tg.stdout.String())
   307  	}
   308  	if tg.stderr.Len() > 0 {
   309  		tg.t.Log("git standard error:")
   310  		tg.t.Log(tg.stderr.String())
   311  	}
   312  	if status != nil {
   313  		tg.t.Logf("git %v failed unexpectedly: %v", args, status)
   314  		tg.t.FailNow()
   315  	}
   316  }
   317  
   318  // getStdout returns standard output of the testgo run as a string.
   319  func (tg *testgoData) getStdout() string {
   320  	if !tg.ran {
   321  		tg.t.Fatal("internal testsuite error: stdout called before run")
   322  	}
   323  	return tg.stdout.String()
   324  }
   325  
   326  // getStderr returns standard error of the testgo run as a string.
   327  func (tg *testgoData) getStderr() string {
   328  	if !tg.ran {
   329  		tg.t.Fatal("internal testsuite error: stdout called before run")
   330  	}
   331  	return tg.stderr.String()
   332  }
   333  
   334  // doGrepMatch looks for a regular expression in a buffer, and returns
   335  // whether it is found.  The regular expression is matched against
   336  // each line separately, as with the grep command.
   337  func (tg *testgoData) doGrepMatch(match string, b *bytes.Buffer) bool {
   338  	if !tg.ran {
   339  		tg.t.Fatal("internal testsuite error: grep called before run")
   340  	}
   341  	re := regexp.MustCompile(match)
   342  	for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
   343  		if re.Match(ln) {
   344  			return true
   345  		}
   346  	}
   347  	return false
   348  }
   349  
   350  // doGrep looks for a regular expression in a buffer and fails if it
   351  // is not found.  The name argument is the name of the output we are
   352  // searching, "output" or "error".  The msg argument is logged on
   353  // failure.
   354  func (tg *testgoData) doGrep(match string, b *bytes.Buffer, name, msg string) {
   355  	if !tg.doGrepMatch(match, b) {
   356  		tg.t.Log(msg)
   357  		tg.t.Logf("pattern %v not found in standard %s", match, name)
   358  		tg.t.FailNow()
   359  	}
   360  }
   361  
   362  // grepStdout looks for a regular expression in the test run's
   363  // standard output and fails, logging msg, if it is not found.
   364  func (tg *testgoData) grepStdout(match, msg string) {
   365  	tg.doGrep(match, &tg.stdout, "output", msg)
   366  }
   367  
   368  // grepStderr looks for a regular expression in the test run's
   369  // standard error and fails, logging msg, if it is not found.
   370  func (tg *testgoData) grepStderr(match, msg string) {
   371  	tg.doGrep(match, &tg.stderr, "error", msg)
   372  }
   373  
   374  // grepBoth looks for a regular expression in the test run's standard
   375  // output or stand error and fails, logging msg, if it is not found.
   376  func (tg *testgoData) grepBoth(match, msg string) {
   377  	if !tg.doGrepMatch(match, &tg.stdout) && !tg.doGrepMatch(match, &tg.stderr) {
   378  		tg.t.Log(msg)
   379  		tg.t.Logf("pattern %v not found in standard output or standard error", match)
   380  		tg.t.FailNow()
   381  	}
   382  }
   383  
   384  // doGrepNot looks for a regular expression in a buffer and fails if
   385  // it is found.  The name and msg arguments are as for doGrep.
   386  func (tg *testgoData) doGrepNot(match string, b *bytes.Buffer, name, msg string) {
   387  	if tg.doGrepMatch(match, b) {
   388  		tg.t.Log(msg)
   389  		tg.t.Logf("pattern %v found unexpectedly in standard %s", match, name)
   390  		tg.t.FailNow()
   391  	}
   392  }
   393  
   394  // grepStdoutNot looks for a regular expression in the test run's
   395  // standard output and fails, logging msg, if it is found.
   396  func (tg *testgoData) grepStdoutNot(match, msg string) {
   397  	tg.doGrepNot(match, &tg.stdout, "output", msg)
   398  }
   399  
   400  // grepStderrNot looks for a regular expression in the test run's
   401  // standard error and fails, logging msg, if it is found.
   402  func (tg *testgoData) grepStderrNot(match, msg string) {
   403  	tg.doGrepNot(match, &tg.stderr, "error", msg)
   404  }
   405  
   406  // grepBothNot looks for a regular expression in the test run's
   407  // standard output or stand error and fails, logging msg, if it is
   408  // found.
   409  func (tg *testgoData) grepBothNot(match, msg string) {
   410  	if tg.doGrepMatch(match, &tg.stdout) || tg.doGrepMatch(match, &tg.stderr) {
   411  		tg.t.Log(msg)
   412  		tg.t.Fatalf("pattern %v found unexpectedly in standard output or standard error", match)
   413  	}
   414  }
   415  
   416  // doGrepCount counts the number of times a regexp is seen in a buffer.
   417  func (tg *testgoData) doGrepCount(match string, b *bytes.Buffer) int {
   418  	if !tg.ran {
   419  		tg.t.Fatal("internal testsuite error: doGrepCount called before run")
   420  	}
   421  	re := regexp.MustCompile(match)
   422  	c := 0
   423  	for _, ln := range bytes.Split(b.Bytes(), []byte{'\n'}) {
   424  		if re.Match(ln) {
   425  			c++
   426  		}
   427  	}
   428  	return c
   429  }
   430  
   431  // grepCountStdout returns the number of times a regexp is seen in
   432  // standard output.
   433  func (tg *testgoData) grepCountStdout(match string) int {
   434  	return tg.doGrepCount(match, &tg.stdout)
   435  }
   436  
   437  // grepCountStderr returns the number of times a regexp is seen in
   438  // standard error.
   439  func (tg *testgoData) grepCountStderr(match string) int {
   440  	return tg.doGrepCount(match, &tg.stderr)
   441  }
   442  
   443  // grepCountBoth returns the number of times a regexp is seen in both
   444  // standard output and standard error.
   445  func (tg *testgoData) grepCountBoth(match string) int {
   446  	return tg.doGrepCount(match, &tg.stdout) + tg.doGrepCount(match, &tg.stderr)
   447  }
   448  
   449  // creatingTemp records that the test plans to create a temporary file
   450  // or directory.  If the file or directory exists already, it will be
   451  // removed.  When the test completes, the file or directory will be
   452  // removed if it exists.
   453  func (tg *testgoData) creatingTemp(path string) {
   454  	if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) {
   455  		tg.t.Fatal("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path)
   456  	}
   457  	// If we have changed the working directory, make sure we have
   458  	// an absolute path, because we are going to change directory
   459  	// back before we remove the temporary.
   460  	if tg.wd != "" && !filepath.IsAbs(path) {
   461  		path = filepath.Join(tg.pwd(), path)
   462  	}
   463  	tg.must(os.RemoveAll(path))
   464  	tg.temps = append(tg.temps, path)
   465  }
   466  
   467  // makeTempdir makes a temporary directory for a run of testgo.  If
   468  // the temporary directory was already created, this does nothing.
   469  func (tg *testgoData) makeTempdir() {
   470  	if tg.tempdir == "" {
   471  		var err error
   472  		tg.tempdir, err = ioutil.TempDir("", "gotest")
   473  		tg.must(err)
   474  	}
   475  }
   476  
   477  // tempFile adds a temporary file for a run of testgo.
   478  func (tg *testgoData) tempFile(path, contents string) {
   479  	tg.makeTempdir()
   480  	tg.must(os.MkdirAll(filepath.Join(tg.tempdir, filepath.Dir(path)), 0755))
   481  	bytes := []byte(contents)
   482  	if strings.HasSuffix(path, ".go") {
   483  		formatted, err := format.Source(bytes)
   484  		if err == nil {
   485  			bytes = formatted
   486  		}
   487  	}
   488  	tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644))
   489  }
   490  
   491  // tempDir adds a temporary directory for a run of testgo.
   492  func (tg *testgoData) tempDir(path string) {
   493  	tg.makeTempdir()
   494  	if err := os.MkdirAll(filepath.Join(tg.tempdir, path), 0755); err != nil && !os.IsExist(err) {
   495  		tg.t.Fatal(err)
   496  	}
   497  }
   498  
   499  // path returns the absolute pathname to file with the temporary
   500  // directory.
   501  func (tg *testgoData) path(name string) string {
   502  	if tg.tempdir == "" {
   503  		tg.t.Fatalf("internal testsuite error: path(%q) with no tempdir", name)
   504  	}
   505  	if name == "." {
   506  		return tg.tempdir
   507  	}
   508  	return filepath.Join(tg.tempdir, name)
   509  }
   510  
   511  // mustNotExist fails if path exists.
   512  func (tg *testgoData) mustNotExist(path string) {
   513  	if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) {
   514  		tg.t.Fatalf("%s exists but should not (%v)", path, err)
   515  	}
   516  }
   517  
   518  // wantExecutable fails with msg if path is not executable.
   519  func (tg *testgoData) wantExecutable(path, msg string) {
   520  	if st, err := os.Stat(path); err != nil {
   521  		if !os.IsNotExist(err) {
   522  			tg.t.Log(err)
   523  		}
   524  		tg.t.Fatal(msg)
   525  	} else {
   526  		if runtime.GOOS != "windows" && st.Mode()&0111 == 0 {
   527  			tg.t.Fatalf("binary %s exists but is not executable", path)
   528  		}
   529  	}
   530  }
   531  
   532  // wantArchive fails if path is not an archive.
   533  func (tg *testgoData) wantArchive(path string) {
   534  	f, err := os.Open(path)
   535  	if err != nil {
   536  		tg.t.Fatal(err)
   537  	}
   538  	buf := make([]byte, 100)
   539  	io.ReadFull(f, buf)
   540  	f.Close()
   541  	if !bytes.HasPrefix(buf, []byte("!<arch>\n")) {
   542  		tg.t.Fatalf("file %s exists but is not an archive", path)
   543  	}
   544  }
   545  
   546  // isStale returns whether pkg is stale.
   547  func (tg *testgoData) isStale(pkg string) bool {
   548  	tg.run("list", "-f", "{{.Stale}}", pkg)
   549  	switch v := strings.TrimSpace(tg.getStdout()); v {
   550  	case "true":
   551  		return true
   552  	case "false":
   553  		return false
   554  	default:
   555  		tg.t.Fatalf("unexpected output checking staleness of package %v: %v", pkg, v)
   556  		panic("unreachable")
   557  	}
   558  }
   559  
   560  // wantStale fails with msg if pkg is not stale.
   561  func (tg *testgoData) wantStale(pkg, msg string) {
   562  	if !tg.isStale(pkg) {
   563  		tg.t.Fatal(msg)
   564  	}
   565  }
   566  
   567  // wantNotStale fails with msg if pkg is stale.
   568  func (tg *testgoData) wantNotStale(pkg, msg string) {
   569  	if tg.isStale(pkg) {
   570  		tg.t.Fatal(msg)
   571  	}
   572  }
   573  
   574  // cleanup cleans up a test that runs testgo.
   575  func (tg *testgoData) cleanup() {
   576  	if tg.wd != "" {
   577  		if err := os.Chdir(tg.wd); err != nil {
   578  			// We are unlikely to be able to continue.
   579  			fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err)
   580  			os.Exit(2)
   581  		}
   582  	}
   583  	for _, path := range tg.temps {
   584  		tg.check(os.RemoveAll(path))
   585  	}
   586  	if tg.tempdir != "" {
   587  		tg.check(os.RemoveAll(tg.tempdir))
   588  	}
   589  }
   590  
   591  // resetReadOnlyFlagAll resets windows read-only flag
   592  // set on path and any children it contains.
   593  // The flag is set by git and has to be removed.
   594  // os.Remove refuses to remove files with read-only flag set.
   595  func (tg *testgoData) resetReadOnlyFlagAll(path string) {
   596  	fi, err := os.Stat(path)
   597  	if err != nil {
   598  		tg.t.Fatalf("resetReadOnlyFlagAll(%q) failed: %v", path, err)
   599  	}
   600  	if !fi.IsDir() {
   601  		err := os.Chmod(path, 0666)
   602  		if err != nil {
   603  			tg.t.Fatalf("resetReadOnlyFlagAll(%q) failed: %v", path, err)
   604  		}
   605  	}
   606  	fd, err := os.Open(path)
   607  	if err != nil {
   608  		tg.t.Fatalf("resetReadOnlyFlagAll(%q) failed: %v", path, err)
   609  	}
   610  	defer fd.Close()
   611  	names, _ := fd.Readdirnames(-1)
   612  	for _, name := range names {
   613  		tg.resetReadOnlyFlagAll(path + string(filepath.Separator) + name)
   614  	}
   615  }
   616  
   617  // failSSH puts an ssh executable in the PATH that always fails.
   618  // This is to stub out uses of ssh by go get.
   619  func (tg *testgoData) failSSH() {
   620  	wd, err := os.Getwd()
   621  	if err != nil {
   622  		tg.t.Fatal(err)
   623  	}
   624  	fail := filepath.Join(wd, "testdata/failssh")
   625  	tg.setenv("PATH", fmt.Sprintf("%v%c%v", fail, filepath.ListSeparator, os.Getenv("PATH")))
   626  }
   627  
   628  func TestFileLineInErrorMessages(t *testing.T) {
   629  	tg := testgo(t)
   630  	defer tg.cleanup()
   631  	tg.parallel()
   632  	tg.tempFile("err.go", `package main; import "bar"`)
   633  	path := tg.path("err.go")
   634  	tg.runFail("run", path)
   635  	shortPath := path
   636  	if rel, err := filepath.Rel(tg.pwd(), path); err == nil && len(rel) < len(path) {
   637  		shortPath = rel
   638  	}
   639  	tg.grepStderr("^"+regexp.QuoteMeta(shortPath)+":", "missing file:line in error message")
   640  }
   641  
   642  func TestProgramNameInCrashMessages(t *testing.T) {
   643  	tg := testgo(t)
   644  	defer tg.cleanup()
   645  	tg.parallel()
   646  	tg.tempFile("triv.go", `package main; func main() {}`)
   647  	tg.runFail("build", "-ldflags", "-crash_for_testing", tg.path("triv.go"))
   648  	tg.grepStderr(`[/\\]tool[/\\].*[/\\]link`, "missing linker name in error message")
   649  }
   650  
   651  func TestBrokenTestsWithoutTestFunctionsAllFail(t *testing.T) {
   652  	tg := testgo(t)
   653  	defer tg.cleanup()
   654  	tg.runFail("test", "./testdata/src/badtest/...")
   655  	tg.grepBothNot("^ok", "test passed unexpectedly")
   656  	tg.grepBoth("FAIL.*badtest/badexec", "test did not run everything")
   657  	tg.grepBoth("FAIL.*badtest/badsyntax", "test did not run everything")
   658  	tg.grepBoth("FAIL.*badtest/badvar", "test did not run everything")
   659  }
   660  
   661  func TestGoBuildDashAInDevBranch(t *testing.T) {
   662  	if testing.Short() {
   663  		t.Skip("don't rebuild the standard library in short mode")
   664  	}
   665  
   666  	tg := testgo(t)
   667  	defer tg.cleanup()
   668  	tg.run("install", "math") // should be up to date already but just in case
   669  	tg.setenv("TESTGO_IS_GO_RELEASE", "0")
   670  	tg.run("build", "-v", "-a", "math")
   671  	tg.grepStderr("runtime", "testgo build -a math in dev branch DID NOT build runtime, but should have")
   672  }
   673  
   674  func TestGoBuilDashAInReleaseBranch(t *testing.T) {
   675  	if testing.Short() {
   676  		t.Skip("don't rebuild the standard library in short mode")
   677  	}
   678  
   679  	tg := testgo(t)
   680  	defer tg.cleanup()
   681  	tg.run("install", "math") // should be up to date already but just in case
   682  	tg.setenv("TESTGO_IS_GO_RELEASE", "1")
   683  	tg.run("build", "-v", "-a", "math")
   684  	tg.grepStderr("runtime", "testgo build -a math in dev branch did not build runtime, but should have")
   685  }
   686  
   687  func TestGoInstallCleansUpAfterGoBuild(t *testing.T) {
   688  	tg := testgo(t)
   689  	defer tg.cleanup()
   690  	tg.tempFile("src/mycmd/main.go", `package main; func main(){}`)
   691  	tg.setenv("GOPATH", tg.path("."))
   692  	tg.cd(tg.path("src/mycmd"))
   693  
   694  	doesNotExist := func(file, msg string) {
   695  		if _, err := os.Stat(file); err == nil {
   696  			t.Fatal(msg)
   697  		} else if !os.IsNotExist(err) {
   698  			t.Fatal(msg, "error:", err)
   699  		}
   700  	}
   701  
   702  	tg.run("build")
   703  	tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary")
   704  	tg.run("install")
   705  	doesNotExist("mycmd"+exeSuffix, "testgo install did not remove command binary")
   706  	tg.run("build")
   707  	tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (second time)")
   708  	// Running install with arguments does not remove the target,
   709  	// even in the same directory.
   710  	tg.run("install", "mycmd")
   711  	tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary when run in mycmd")
   712  	tg.run("build")
   713  	tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (third time)")
   714  	// And especially not outside the directory.
   715  	tg.cd(tg.path("."))
   716  	if data, err := ioutil.ReadFile("src/mycmd/mycmd" + exeSuffix); err != nil {
   717  		t.Fatal("could not read file:", err)
   718  	} else {
   719  		if err := ioutil.WriteFile("mycmd"+exeSuffix, data, 0555); err != nil {
   720  			t.Fatal("could not write file:", err)
   721  		}
   722  	}
   723  	tg.run("install", "mycmd")
   724  	tg.wantExecutable("src/mycmd/mycmd"+exeSuffix, "testgo install mycmd removed command binary from its source dir when run outside mycmd")
   725  	tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary from current dir when run outside mycmd")
   726  }
   727  
   728  func TestGoInstallRebuildsStalePackagesInOtherGOPATH(t *testing.T) {
   729  	tg := testgo(t)
   730  	defer tg.cleanup()
   731  	tg.parallel()
   732  	tg.tempFile("d1/src/p1/p1.go", `package p1
   733  		import "p2"
   734  		func F() { p2.F() }`)
   735  	tg.tempFile("d2/src/p2/p2.go", `package p2
   736  		func F() {}`)
   737  	sep := string(filepath.ListSeparator)
   738  	tg.setenv("GOPATH", tg.path("d1")+sep+tg.path("d2"))
   739  	tg.run("install", "p1")
   740  	tg.wantNotStale("p1", "./testgo list mypkg claims p1 is stale, incorrectly")
   741  	tg.wantNotStale("p2", "./testgo list mypkg claims p2 is stale, incorrectly")
   742  	tg.sleep()
   743  	if f, err := os.OpenFile(tg.path("d2/src/p2/p2.go"), os.O_WRONLY|os.O_APPEND, 0); err != nil {
   744  		t.Fatal(err)
   745  	} else if _, err = f.WriteString(`func G() {}`); err != nil {
   746  		t.Fatal(err)
   747  	} else {
   748  		tg.must(f.Close())
   749  	}
   750  	tg.wantStale("p2", "./testgo list mypkg claims p2 is NOT stale, incorrectly")
   751  	tg.wantStale("p1", "./testgo list mypkg claims p1 is NOT stale, incorrectly")
   752  
   753  	tg.run("install", "p1")
   754  	tg.wantNotStale("p2", "./testgo list mypkg claims p2 is stale after reinstall, incorrectly")
   755  	tg.wantNotStale("p1", "./testgo list mypkg claims p1 is stale after reinstall, incorrectly")
   756  }
   757  
   758  func TestGoInstallDetectsRemovedFiles(t *testing.T) {
   759  	tg := testgo(t)
   760  	defer tg.cleanup()
   761  	tg.parallel()
   762  	tg.tempFile("src/mypkg/x.go", `package mypkg`)
   763  	tg.tempFile("src/mypkg/y.go", `package mypkg`)
   764  	tg.tempFile("src/mypkg/z.go", `// +build missingtag
   765  
   766  		package mypkg`)
   767  	tg.setenv("GOPATH", tg.path("."))
   768  	tg.run("install", "mypkg")
   769  	tg.wantNotStale("mypkg", "./testgo list mypkg claims mypkg is stale, incorrectly")
   770  	// z.go was not part of the build; removing it is okay.
   771  	tg.must(os.Remove(tg.path("src/mypkg/z.go")))
   772  	tg.wantNotStale("mypkg", "./testgo list mypkg claims mypkg is stale after removing z.go; should not be stale")
   773  	// y.go was part of the package; removing it should be detected.
   774  	tg.must(os.Remove(tg.path("src/mypkg/y.go")))
   775  	tg.wantStale("mypkg", "./testgo list mypkg claims mypkg is NOT stale after removing y.go; should be stale")
   776  }
   777  
   778  func TestGoInstallErrorOnCrossCompileToBin(t *testing.T) {
   779  	if testing.Short() {
   780  		t.Skip("don't install into GOROOT in short mode")
   781  	}
   782  
   783  	tg := testgo(t)
   784  	defer tg.cleanup()
   785  	tg.tempFile("src/mycmd/x.go", `package main
   786  		func main() {}`)
   787  	tg.setenv("GOPATH", tg.path("."))
   788  	tg.cd(tg.path("src/mycmd"))
   789  
   790  	tg.run("build", "mycmd")
   791  
   792  	goarch := "386"
   793  	if runtime.GOARCH == "386" {
   794  		goarch = "amd64"
   795  	}
   796  	tg.setenv("GOOS", "linux")
   797  	tg.setenv("GOARCH", goarch)
   798  	tg.run("install", "mycmd")
   799  	tg.setenv("GOBIN", tg.path("."))
   800  	tg.runFail("install", "mycmd")
   801  	tg.run("install", "cmd/pack")
   802  }
   803  
   804  func TestGoInstallDetectsRemovedFilesInPackageMain(t *testing.T) {
   805  	tg := testgo(t)
   806  	defer tg.cleanup()
   807  	tg.parallel()
   808  	tg.tempFile("src/mycmd/x.go", `package main
   809  		func main() {}`)
   810  	tg.tempFile("src/mycmd/y.go", `package main`)
   811  	tg.tempFile("src/mycmd/z.go", `// +build missingtag
   812  
   813  		package main`)
   814  	tg.setenv("GOPATH", tg.path("."))
   815  	tg.run("install", "mycmd")
   816  	tg.wantNotStale("mycmd", "./testgo list mypkg claims mycmd is stale, incorrectly")
   817  	// z.go was not part of the build; removing it is okay.
   818  	tg.must(os.Remove(tg.path("src/mycmd/z.go")))
   819  	tg.wantNotStale("mycmd", "./testgo list mycmd claims mycmd is stale after removing z.go; should not be stale")
   820  	// y.go was part of the package; removing it should be detected.
   821  	tg.must(os.Remove(tg.path("src/mycmd/y.go")))
   822  	tg.wantStale("mycmd", "./testgo list mycmd claims mycmd is NOT stale after removing y.go; should be stale")
   823  }
   824  
   825  func testLocalRun(tg *testgoData, exepath, local, match string) {
   826  	out, err := exec.Command(exepath).Output()
   827  	if err != nil {
   828  		tg.t.Fatalf("error running %v: %v", exepath, err)
   829  	}
   830  	if !regexp.MustCompile(match).Match(out) {
   831  		tg.t.Log(string(out))
   832  		tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local)
   833  	}
   834  }
   835  
   836  func testLocalEasy(tg *testgoData, local string) {
   837  	exepath := "./easy" + exeSuffix
   838  	tg.creatingTemp(exepath)
   839  	tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go"))
   840  	testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
   841  }
   842  
   843  func testLocalEasySub(tg *testgoData, local string) {
   844  	exepath := "./easysub" + exeSuffix
   845  	tg.creatingTemp(exepath)
   846  	tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go"))
   847  	testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`)
   848  }
   849  
   850  func testLocalHard(tg *testgoData, local string) {
   851  	exepath := "./hard" + exeSuffix
   852  	tg.creatingTemp(exepath)
   853  	tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go"))
   854  	testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`)
   855  }
   856  
   857  func testLocalInstall(tg *testgoData, local string) {
   858  	tg.runFail("install", filepath.Join("testdata", local, "easy.go"))
   859  }
   860  
   861  func TestLocalImportsEasy(t *testing.T) {
   862  	tg := testgo(t)
   863  	defer tg.cleanup()
   864  	testLocalEasy(tg, "local")
   865  }
   866  
   867  func TestLocalImportsEasySub(t *testing.T) {
   868  	tg := testgo(t)
   869  	defer tg.cleanup()
   870  	testLocalEasySub(tg, "local")
   871  }
   872  
   873  func TestLocalImportsHard(t *testing.T) {
   874  	tg := testgo(t)
   875  	defer tg.cleanup()
   876  	testLocalHard(tg, "local")
   877  }
   878  
   879  func TestLocalImportsGoInstallShouldFail(t *testing.T) {
   880  	tg := testgo(t)
   881  	defer tg.cleanup()
   882  	testLocalInstall(tg, "local")
   883  }
   884  
   885  const badDirName = `#$%:, &()*;<=>?\^{}`
   886  
   887  func copyBad(tg *testgoData) {
   888  	if runtime.GOOS == "windows" {
   889  		tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName)
   890  	}
   891  
   892  	tg.must(filepath.Walk("testdata/local",
   893  		func(path string, info os.FileInfo, err error) error {
   894  			if err != nil {
   895  				return err
   896  			}
   897  			if info.IsDir() {
   898  				return nil
   899  			}
   900  			var data []byte
   901  			data, err = ioutil.ReadFile(path)
   902  			if err != nil {
   903  				return err
   904  			}
   905  			newpath := strings.Replace(path, "local", badDirName, 1)
   906  			tg.tempFile(newpath, string(data))
   907  			return nil
   908  		}))
   909  	tg.cd(tg.path("."))
   910  }
   911  
   912  func TestBadImportsEasy(t *testing.T) {
   913  	tg := testgo(t)
   914  	defer tg.cleanup()
   915  	copyBad(tg)
   916  	testLocalEasy(tg, badDirName)
   917  }
   918  
   919  func TestBadImportsEasySub(t *testing.T) {
   920  	tg := testgo(t)
   921  	defer tg.cleanup()
   922  	copyBad(tg)
   923  	testLocalEasySub(tg, badDirName)
   924  }
   925  
   926  func TestBadImportsHard(t *testing.T) {
   927  	tg := testgo(t)
   928  	defer tg.cleanup()
   929  	copyBad(tg)
   930  	testLocalHard(tg, badDirName)
   931  }
   932  
   933  func TestBadImportsGoInstallShouldFail(t *testing.T) {
   934  	tg := testgo(t)
   935  	defer tg.cleanup()
   936  	copyBad(tg)
   937  	testLocalInstall(tg, badDirName)
   938  }
   939  
   940  func TestInternalPackagesInGOROOTAreRespected(t *testing.T) {
   941  	tg := testgo(t)
   942  	defer tg.cleanup()
   943  	tg.runFail("build", "-v", "./testdata/testinternal")
   944  	tg.grepBoth("use of internal package not allowed", "wrong error message for testdata/testinternal")
   945  }
   946  
   947  func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) {
   948  	tg := testgo(t)
   949  	defer tg.cleanup()
   950  	tg.runFail("build", "-v", "./testdata/testinternal2")
   951  	tg.grepBoth("use of internal package not allowed", "wrote error message for testdata/testinternal2")
   952  }
   953  
   954  func testMove(t *testing.T, vcs, url, base, config string) {
   955  	testenv.MustHaveExternalNetwork(t)
   956  
   957  	tg := testgo(t)
   958  	defer tg.cleanup()
   959  	tg.parallel()
   960  	tg.tempDir("src")
   961  	tg.setenv("GOPATH", tg.path("."))
   962  	tg.run("get", "-d", url)
   963  	tg.run("get", "-d", "-u", url)
   964  	switch vcs {
   965  	case "svn":
   966  		// SVN doesn't believe in text files so we can't just edit the config.
   967  		// Check out a different repo into the wrong place.
   968  		tg.must(os.RemoveAll(tg.path("src/code.google.com/p/rsc-svn")))
   969  		tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk")
   970  		tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn")))
   971  	default:
   972  		path := tg.path(filepath.Join("src", config))
   973  		data, err := ioutil.ReadFile(path)
   974  		tg.must(err)
   975  		data = bytes.Replace(data, []byte(base), []byte(base+"XXX"), -1)
   976  		tg.must(ioutil.WriteFile(path, data, 0644))
   977  	}
   978  	if vcs == "git" {
   979  		// git will ask for a username and password when we
   980  		// run go get -d -f -u.  An empty username and
   981  		// password will work.  Prevent asking by setting
   982  		// GIT_ASKPASS.
   983  		tg.creatingTemp("sink" + exeSuffix)
   984  		tg.tempFile("src/sink/sink.go", `package main; func main() {}`)
   985  		tg.run("build", "-o", "sink"+exeSuffix, "sink")
   986  		tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix))
   987  	}
   988  	tg.runFail("get", "-d", "-u", url)
   989  	tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason")
   990  	tg.runFail("get", "-d", "-f", "-u", url)
   991  	tg.grepStderr("validating server certificate|not found", "go get -d -f -u "+url+" failed for wrong reason")
   992  }
   993  
   994  func TestInternalPackageErrorsAreHandled(t *testing.T) {
   995  	tg := testgo(t)
   996  	defer tg.cleanup()
   997  	tg.run("list", "./testdata/testinternal3")
   998  }
   999  
  1000  func TestInternalCache(t *testing.T) {
  1001  	tg := testgo(t)
  1002  	defer tg.cleanup()
  1003  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4"))
  1004  	tg.runFail("build", "p")
  1005  	tg.grepStderr("internal", "did not fail to build p")
  1006  }
  1007  
  1008  func TestMoveGit(t *testing.T) {
  1009  	testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config")
  1010  }
  1011  
  1012  // TODO(rsc): Set up a test case on bitbucket for hg.
  1013  // func TestMoveHG(t *testing.T) {
  1014  // 	testMove(t, "hg", "rsc.io/x86/x86asm", "x86", "rsc.io/x86/.hg/hgrc")
  1015  // }
  1016  
  1017  // TODO(rsc): Set up a test case on SourceForge (?) for svn.
  1018  // func testMoveSVN(t *testing.T) {
  1019  //	testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-")
  1020  // }
  1021  
  1022  func TestImportCommandMatch(t *testing.T) {
  1023  	tg := testgo(t)
  1024  	defer tg.cleanup()
  1025  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
  1026  	tg.run("build", "./testdata/importcom/works.go")
  1027  }
  1028  
  1029  func TestImportCommentMismatch(t *testing.T) {
  1030  	tg := testgo(t)
  1031  	defer tg.cleanup()
  1032  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
  1033  	tg.runFail("build", "./testdata/importcom/wrongplace.go")
  1034  	tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import")
  1035  }
  1036  
  1037  func TestImportCommentSyntaxError(t *testing.T) {
  1038  	tg := testgo(t)
  1039  	defer tg.cleanup()
  1040  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
  1041  	tg.runFail("build", "./testdata/importcom/bad.go")
  1042  	tg.grepStderr("cannot parse import comment", "go build did not mention syntax error")
  1043  }
  1044  
  1045  func TestImportCommentConflict(t *testing.T) {
  1046  	tg := testgo(t)
  1047  	defer tg.cleanup()
  1048  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom"))
  1049  	tg.runFail("build", "./testdata/importcom/conflict.go")
  1050  	tg.grepStderr("found import comments", "go build did not mention comment conflict")
  1051  }
  1052  
  1053  // cmd/go: custom import path checking should not apply to github.com/xxx/yyy.
  1054  func TestIssue10952(t *testing.T) {
  1055  	testenv.MustHaveExternalNetwork(t)
  1056  
  1057  	if _, err := exec.LookPath("git"); err != nil {
  1058  		t.Skip("skipping because git binary not found")
  1059  	}
  1060  
  1061  	tg := testgo(t)
  1062  	defer tg.cleanup()
  1063  	tg.parallel()
  1064  	tg.tempDir("src")
  1065  	tg.setenv("GOPATH", tg.path("."))
  1066  	const importPath = "github.com/zombiezen/go-get-issue-10952"
  1067  	tg.run("get", "-d", "-u", importPath)
  1068  	repoDir := tg.path("src/" + importPath)
  1069  	defer tg.resetReadOnlyFlagAll(repoDir)
  1070  	tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git")
  1071  	tg.run("get", "-d", "-u", importPath)
  1072  }
  1073  
  1074  func TestDisallowedCSourceFiles(t *testing.T) {
  1075  	tg := testgo(t)
  1076  	defer tg.cleanup()
  1077  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  1078  	tg.runFail("build", "badc")
  1079  	tg.grepStderr("C source files not allowed", "go test did not say C source files not allowed")
  1080  }
  1081  
  1082  func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) {
  1083  	tg := testgo(t)
  1084  	defer tg.cleanup()
  1085  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  1086  	tg.runFail("test", "syntaxerror")
  1087  	tg.grepStderr("FAIL", "go test did not say FAIL")
  1088  }
  1089  
  1090  func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) {
  1091  	tg := testgo(t)
  1092  	defer tg.cleanup()
  1093  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  1094  	tg.runFail("list", "...")
  1095  	tg.grepBoth("badpkg", "go list ... failure does not mention badpkg")
  1096  	tg.run("list", "m...")
  1097  }
  1098  
  1099  func TestRelativeImportsGoTest(t *testing.T) {
  1100  	tg := testgo(t)
  1101  	defer tg.cleanup()
  1102  	tg.run("test", "./testdata/testimport")
  1103  }
  1104  
  1105  func TestRelativeImportsGoTestDashI(t *testing.T) {
  1106  	tg := testgo(t)
  1107  	defer tg.cleanup()
  1108  	tg.run("test", "-i", "./testdata/testimport")
  1109  }
  1110  
  1111  func TestRelativeImportsInCommandLinePackage(t *testing.T) {
  1112  	tg := testgo(t)
  1113  	defer tg.cleanup()
  1114  	files, err := filepath.Glob("./testdata/testimport/*.go")
  1115  	tg.must(err)
  1116  	tg.run(append([]string{"test"}, files...)...)
  1117  }
  1118  
  1119  func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) {
  1120  	tg := testgo(t)
  1121  	defer tg.cleanup()
  1122  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1"))
  1123  	tg.runFail("get", "-u", "foo")
  1124  
  1125  	// TODO(iant): We should not have to use strconv.Quote here.
  1126  	// The code in vcs.go should be changed so that it is not required.
  1127  	quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo"))
  1128  	quoted = quoted[1 : len(quoted)-1]
  1129  
  1130  	tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo")
  1131  }
  1132  
  1133  func TestInstallFailsWithNoBuildableFiles(t *testing.T) {
  1134  	tg := testgo(t)
  1135  	defer tg.cleanup()
  1136  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  1137  	tg.setenv("CGO_ENABLED", "0")
  1138  	tg.runFail("install", "cgotest")
  1139  	tg.grepStderr("no buildable Go source files", "go install cgotest did not report 'no buildable Go Source files'")
  1140  }
  1141  
  1142  // Test that without $GOBIN set, binaries get installed
  1143  // into the GOPATH bin directory.
  1144  func TestInstallIntoGOPATH(t *testing.T) {
  1145  	tg := testgo(t)
  1146  	defer tg.cleanup()
  1147  	tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix)
  1148  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  1149  	tg.run("install", "go-cmd-test")
  1150  	tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test")
  1151  }
  1152  
  1153  func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) {
  1154  	tg := testgo(t)
  1155  	defer tg.cleanup()
  1156  	gobin := filepath.Join(tg.pwd(), "testdata", "bin")
  1157  	tg.creatingTemp(gobin)
  1158  	tg.setenv("GOBIN", gobin)
  1159  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  1160  	tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now()))
  1161  	tg.sleep()
  1162  	tg.run("test", "main_test")
  1163  	tg.run("install", "main_test")
  1164  	tg.wantNotStale("main_test", "after go install, main listed as stale")
  1165  	tg.run("test", "main_test")
  1166  }
  1167  
  1168  // With $GOBIN set, binaries get installed to $GOBIN.
  1169  func TestInstallIntoGOBIN(t *testing.T) {
  1170  	tg := testgo(t)
  1171  	defer tg.cleanup()
  1172  	gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
  1173  	tg.creatingTemp(gobin)
  1174  	tg.setenv("GOBIN", gobin)
  1175  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  1176  	tg.run("install", "go-cmd-test")
  1177  	tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test")
  1178  }
  1179  
  1180  // Issue 11065
  1181  func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) {
  1182  	tg := testgo(t)
  1183  	defer tg.cleanup()
  1184  	pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test")
  1185  	tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix))
  1186  	tg.setenv("GOBIN", pkg)
  1187  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  1188  	tg.cd(pkg)
  1189  	tg.run("install")
  1190  	tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory")
  1191  }
  1192  
  1193  // Without $GOBIN set, installing a program outside $GOPATH should fail
  1194  // (there is nowhere to install it).
  1195  func TestInstallWithoutDestinationFails(t *testing.T) {
  1196  	tg := testgo(t)
  1197  	defer tg.cleanup()
  1198  	tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go")
  1199  	tg.grepStderr("no install location for .go files listed on command line", "wrong error")
  1200  }
  1201  
  1202  // With $GOBIN set, should install there.
  1203  func TestInstallToGOBINCommandLinePackage(t *testing.T) {
  1204  	tg := testgo(t)
  1205  	defer tg.cleanup()
  1206  	gobin := filepath.Join(tg.pwd(), "testdata", "bin1")
  1207  	tg.creatingTemp(gobin)
  1208  	tg.setenv("GOBIN", gobin)
  1209  	tg.run("install", "testdata/src/go-cmd-test/helloworld.go")
  1210  	tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld")
  1211  }
  1212  
  1213  func TestGodocInstalls(t *testing.T) {
  1214  	testenv.MustHaveExternalNetwork(t)
  1215  
  1216  	// godoc installs into GOBIN
  1217  	tg := testgo(t)
  1218  	defer tg.cleanup()
  1219  	tg.parallel()
  1220  	tg.tempDir("gobin")
  1221  	tg.setenv("GOPATH", tg.path("."))
  1222  	tg.setenv("GOBIN", tg.path("gobin"))
  1223  	tg.run("get", "golang.org/x/tools/cmd/godoc")
  1224  	tg.wantExecutable(tg.path("gobin/godoc"), "did not install godoc to $GOBIN")
  1225  	tg.unsetenv("GOBIN")
  1226  
  1227  	// godoc installs into GOROOT
  1228  	goroot := runtime.GOROOT()
  1229  	tg.setenv("GOROOT", goroot)
  1230  	tg.check(os.RemoveAll(filepath.Join(goroot, "bin", "godoc")))
  1231  	tg.run("install", "golang.org/x/tools/cmd/godoc")
  1232  	tg.wantExecutable(filepath.Join(goroot, "bin", "godoc"), "did not install godoc to $GOROOT/bin")
  1233  }
  1234  
  1235  func TestGoGetNonPkg(t *testing.T) {
  1236  	testenv.MustHaveExternalNetwork(t)
  1237  
  1238  	tg := testgo(t)
  1239  	defer tg.cleanup()
  1240  	tg.tempDir("gobin")
  1241  	tg.setenv("GOPATH", tg.path("."))
  1242  	tg.setenv("GOBIN", tg.path("gobin"))
  1243  	tg.runFail("get", "-d", "golang.org/x/tools")
  1244  	tg.grepStderr("golang.org/x/tools: no buildable Go source files", "missing error")
  1245  	tg.runFail("get", "-d", "-u", "golang.org/x/tools")
  1246  	tg.grepStderr("golang.org/x/tools: no buildable Go source files", "missing error")
  1247  	tg.runFail("get", "-d", "golang.org/x/tools")
  1248  	tg.grepStderr("golang.org/x/tools: no buildable Go source files", "missing error")
  1249  }
  1250  
  1251  func TestInstalls(t *testing.T) {
  1252  	if testing.Short() {
  1253  		t.Skip("don't install into GOROOT in short mode")
  1254  	}
  1255  
  1256  	tg := testgo(t)
  1257  	defer tg.cleanup()
  1258  	tg.parallel()
  1259  	tg.tempDir("gobin")
  1260  	tg.setenv("GOPATH", tg.path("."))
  1261  	goroot := runtime.GOROOT()
  1262  	tg.setenv("GOROOT", goroot)
  1263  
  1264  	// cmd/fix installs into tool
  1265  	tg.run("env", "GOOS")
  1266  	goos := strings.TrimSpace(tg.getStdout())
  1267  	tg.setenv("GOOS", goos)
  1268  	tg.run("env", "GOARCH")
  1269  	goarch := strings.TrimSpace(tg.getStdout())
  1270  	tg.setenv("GOARCH", goarch)
  1271  	fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix
  1272  	tg.must(os.RemoveAll(fixbin))
  1273  	tg.run("install", "cmd/fix")
  1274  	tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool")
  1275  	tg.must(os.Remove(fixbin))
  1276  	tg.setenv("GOBIN", tg.path("gobin"))
  1277  	tg.run("install", "cmd/fix")
  1278  	tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set")
  1279  	tg.unsetenv("GOBIN")
  1280  
  1281  	// gopath program installs into GOBIN
  1282  	tg.tempFile("src/progname/p.go", `package main; func main() {}`)
  1283  	tg.setenv("GOBIN", tg.path("gobin"))
  1284  	tg.run("install", "progname")
  1285  	tg.unsetenv("GOBIN")
  1286  	tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname")
  1287  
  1288  	// gopath program installs into GOPATH/bin
  1289  	tg.run("install", "progname")
  1290  	tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname")
  1291  }
  1292  
  1293  func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) {
  1294  	tg := testgo(t)
  1295  	defer tg.cleanup()
  1296  	tg.setenv("GOPATH", ".")
  1297  	tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
  1298  	tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
  1299  }
  1300  
  1301  func TestRejectRelativePathsInGOPATH(t *testing.T) {
  1302  	tg := testgo(t)
  1303  	defer tg.cleanup()
  1304  	sep := string(filepath.ListSeparator)
  1305  	tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".")
  1306  	tg.runFail("build", "go-cmd-test")
  1307  	tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
  1308  }
  1309  
  1310  func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) {
  1311  	tg := testgo(t)
  1312  	defer tg.cleanup()
  1313  	tg.setenv("GOPATH", "testdata")
  1314  	tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go")
  1315  	tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries")
  1316  }
  1317  
  1318  // Issue 4104.
  1319  func TestGoTestWithPackageListedMultipleTimes(t *testing.T) {
  1320  	tg := testgo(t)
  1321  	defer tg.cleanup()
  1322  	tg.parallel()
  1323  	tg.run("test", "errors", "errors", "errors", "errors", "errors")
  1324  	if strings.Index(strings.TrimSpace(tg.getStdout()), "\n") != -1 {
  1325  		t.Error("go test errors errors errors errors errors tested the same package multiple times")
  1326  	}
  1327  }
  1328  
  1329  func TestGoListHasAConsistentOrder(t *testing.T) {
  1330  	tg := testgo(t)
  1331  	defer tg.cleanup()
  1332  	tg.run("list", "std")
  1333  	first := tg.getStdout()
  1334  	tg.run("list", "std")
  1335  	if first != tg.getStdout() {
  1336  		t.Error("go list std ordering is inconsistent")
  1337  	}
  1338  }
  1339  
  1340  func TestGoListStdDoesNotIncludeCommands(t *testing.T) {
  1341  	tg := testgo(t)
  1342  	defer tg.cleanup()
  1343  	tg.run("list", "std")
  1344  	tg.grepStdoutNot("cmd/", "go list std shows commands")
  1345  }
  1346  
  1347  func TestGoListCmdOnlyShowsCommands(t *testing.T) {
  1348  	tg := testgo(t)
  1349  	defer tg.cleanup()
  1350  	tg.run("list", "cmd")
  1351  	out := strings.TrimSpace(tg.getStdout())
  1352  	for _, line := range strings.Split(out, "\n") {
  1353  		if strings.Index(line, "cmd/") == -1 {
  1354  			t.Error("go list cmd shows non-commands")
  1355  			break
  1356  		}
  1357  	}
  1358  }
  1359  
  1360  // Issue 4096. Validate the output of unsuccessful go install foo/quxx.
  1361  func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) {
  1362  	tg := testgo(t)
  1363  	defer tg.cleanup()
  1364  	tg.runFail("install", "foo/quxx")
  1365  	if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 {
  1366  		t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`)
  1367  	}
  1368  }
  1369  
  1370  func TestGOROOTSearchFailureReporting(t *testing.T) {
  1371  	tg := testgo(t)
  1372  	defer tg.cleanup()
  1373  	tg.runFail("install", "foo/quxx")
  1374  	if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 {
  1375  		t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`)
  1376  	}
  1377  }
  1378  
  1379  func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) {
  1380  	tg := testgo(t)
  1381  	defer tg.cleanup()
  1382  	sep := string(filepath.ListSeparator)
  1383  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
  1384  	tg.runFail("install", "foo/quxx")
  1385  	if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 {
  1386  		t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`)
  1387  	}
  1388  }
  1389  
  1390  // Test (from $GOPATH) annotation is reported for the first GOPATH entry,
  1391  func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) {
  1392  	tg := testgo(t)
  1393  	defer tg.cleanup()
  1394  	sep := string(filepath.ListSeparator)
  1395  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
  1396  	tg.runFail("install", "foo/quxx")
  1397  	if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 {
  1398  		t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`)
  1399  	}
  1400  }
  1401  
  1402  // but not on the second.
  1403  func TestMentionGOPATHNotOnSecondEntry(t *testing.T) {
  1404  	tg := testgo(t)
  1405  	defer tg.cleanup()
  1406  	sep := string(filepath.ListSeparator)
  1407  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b"))
  1408  	tg.runFail("install", "foo/quxx")
  1409  	if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 {
  1410  		t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`)
  1411  	}
  1412  }
  1413  
  1414  // Test missing GOPATH is reported.
  1415  func TestMissingGOPATHIsReported(t *testing.T) {
  1416  	tg := testgo(t)
  1417  	defer tg.cleanup()
  1418  	tg.setenv("GOPATH", "")
  1419  	tg.runFail("install", "foo/quxx")
  1420  	if tg.grepCountBoth(`\(\$GOPATH not set\)$`) != 1 {
  1421  		t.Error(`go install foo/quxx expected error: ($GOPATH not set)`)
  1422  	}
  1423  }
  1424  
  1425  // Issue 4186.  go get cannot be used to download packages to $GOROOT.
  1426  // Test that without GOPATH set, go get should fail.
  1427  func TestWithoutGOPATHGoGetFails(t *testing.T) {
  1428  	testenv.MustHaveExternalNetwork(t)
  1429  
  1430  	tg := testgo(t)
  1431  	defer tg.cleanup()
  1432  	tg.parallel()
  1433  	tg.tempDir("src")
  1434  	tg.setenv("GOPATH", "")
  1435  	tg.setenv("GOROOT", tg.path("."))
  1436  	tg.runFail("get", "-d", "golang.org/x/codereview/cmd/hgpatch")
  1437  }
  1438  
  1439  // Test that with GOPATH=$GOROOT, go get should fail.
  1440  func TestWithGOPATHEqualsGOROOTGoGetFails(t *testing.T) {
  1441  	testenv.MustHaveExternalNetwork(t)
  1442  
  1443  	tg := testgo(t)
  1444  	defer tg.cleanup()
  1445  	tg.parallel()
  1446  	tg.tempDir("src")
  1447  	tg.setenv("GOPATH", tg.path("."))
  1448  	tg.setenv("GOROOT", tg.path("."))
  1449  	tg.runFail("get", "-d", "golang.org/x/codereview/cmd/hgpatch")
  1450  }
  1451  
  1452  func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) {
  1453  	tg := testgo(t)
  1454  	defer tg.cleanup()
  1455  	tg.parallel()
  1456  	tg.tempFile("main.go", `package main
  1457  		var extern string
  1458  		func main() {
  1459  			println(extern)
  1460  		}`)
  1461  	tg.run("run", "-ldflags", `-X main.extern "hello world"`, tg.path("main.go"))
  1462  	tg.grepStderr("^hello world", `ldflags -X main.extern 'hello world' failed`)
  1463  }
  1464  
  1465  func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) {
  1466  	tg := testgo(t)
  1467  	defer tg.cleanup()
  1468  	tg.makeTempdir()
  1469  	tg.cd(tg.path("."))
  1470  	tg.run("test", "-cpuprofile", "errors.prof", "errors")
  1471  	tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test")
  1472  }
  1473  
  1474  func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) {
  1475  	tg := testgo(t)
  1476  	defer tg.cleanup()
  1477  	tg.makeTempdir()
  1478  	tg.cd(tg.path("."))
  1479  	tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors")
  1480  	tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test")
  1481  }
  1482  
  1483  func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) {
  1484  	tg := testgo(t)
  1485  	defer tg.cleanup()
  1486  	tg.parallel()
  1487  	tg.makeTempdir()
  1488  	tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
  1489  	tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test")
  1490  }
  1491  
  1492  func TestGoTestDashOWritesBinary(t *testing.T) {
  1493  	tg := testgo(t)
  1494  	defer tg.cleanup()
  1495  	tg.parallel()
  1496  	tg.makeTempdir()
  1497  	tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors")
  1498  	tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test")
  1499  }
  1500  
  1501  // Issue 4568.
  1502  func TestSymlinksDoNotConfuseGoList(t *testing.T) {
  1503  	switch runtime.GOOS {
  1504  	case "plan9", "windows":
  1505  		t.Skipf("skipping symlink test on %s", runtime.GOOS)
  1506  	}
  1507  
  1508  	tg := testgo(t)
  1509  	defer tg.cleanup()
  1510  	tg.tempDir("src")
  1511  	tg.must(os.Symlink(tg.path("."), tg.path("src/dir1")))
  1512  	tg.tempFile("src/dir1/p.go", "package p")
  1513  	tg.setenv("GOPATH", tg.path("."))
  1514  	tg.cd(tg.path("src"))
  1515  	tg.run("list", "-f", "{{.Root}}", "dir1")
  1516  	if strings.TrimSpace(tg.getStdout()) != tg.path(".") {
  1517  		t.Error("confused by symlinks")
  1518  	}
  1519  }
  1520  
  1521  // Issue 4515.
  1522  func TestInstallWithTags(t *testing.T) {
  1523  	tg := testgo(t)
  1524  	defer tg.cleanup()
  1525  	tg.parallel()
  1526  	tg.tempDir("bin")
  1527  	tg.tempFile("src/example/a/main.go", `package main
  1528  		func main() {}`)
  1529  	tg.tempFile("src/example/b/main.go", `// +build mytag
  1530  
  1531  		package main
  1532  		func main() {}`)
  1533  	tg.setenv("GOPATH", tg.path("."))
  1534  	tg.run("install", "-tags", "mytag", "example/a", "example/b")
  1535  	tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries")
  1536  	tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries")
  1537  	tg.must(os.Remove(tg.path("bin/a" + exeSuffix)))
  1538  	tg.must(os.Remove(tg.path("bin/b" + exeSuffix)))
  1539  	tg.run("install", "-tags", "mytag", "example/...")
  1540  	tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries")
  1541  	tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries")
  1542  	tg.run("list", "-tags", "mytag", "example/b...")
  1543  	if strings.TrimSpace(tg.getStdout()) != "example/b" {
  1544  		t.Error("go list example/b did not find example/b")
  1545  	}
  1546  }
  1547  
  1548  // Issue 4773
  1549  func TestCaseCollisions(t *testing.T) {
  1550  	tg := testgo(t)
  1551  	defer tg.cleanup()
  1552  	tg.parallel()
  1553  	tg.tempDir("src/example/a/pkg")
  1554  	tg.tempDir("src/example/a/Pkg")
  1555  	tg.tempDir("src/example/b")
  1556  	tg.setenv("GOPATH", tg.path("."))
  1557  	tg.tempFile("src/example/a/a.go", `package p
  1558  		import (
  1559  			_ "example/a/pkg"
  1560  			_ "example/a/Pkg"
  1561  		)`)
  1562  	tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`)
  1563  	tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`)
  1564  	tg.runFail("list", "example/a")
  1565  	tg.grepStderr("case-insensitive import collision", "go list example/a did not report import collision")
  1566  	tg.tempFile("src/example/b/file.go", `package b`)
  1567  	tg.tempFile("src/example/b/FILE.go", `package b`)
  1568  	f, err := os.Open(tg.path("src/example/b"))
  1569  	tg.must(err)
  1570  	names, err := f.Readdirnames(0)
  1571  	tg.must(err)
  1572  	tg.check(f.Close())
  1573  	args := []string{"list"}
  1574  	if len(names) == 2 {
  1575  		// case-sensitive file system, let directory read find both files
  1576  		args = append(args, "example/b")
  1577  	} else {
  1578  		// case-insensitive file system, list files explicitly on command line
  1579  		args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go"))
  1580  	}
  1581  	tg.runFail(args...)
  1582  	tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision")
  1583  }
  1584  
  1585  // Issue 8181.
  1586  func TestGoGetDashTIssue8181(t *testing.T) {
  1587  	if testing.Short() {
  1588  		t.Skip("skipping test that uses network in short mode")
  1589  	}
  1590  
  1591  	tg := testgo(t)
  1592  	defer tg.cleanup()
  1593  	tg.parallel()
  1594  	tg.makeTempdir()
  1595  	tg.setenv("GOPATH", tg.path("."))
  1596  	tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b")
  1597  	tg.run("list", "...")
  1598  	tg.grepStdout("x/build/cmd/cl", "missing expected x/build/cmd/cl")
  1599  }
  1600  
  1601  func TestIssue11307(t *testing.T) {
  1602  	// go get -u was not working except in checkout directory
  1603  	if testing.Short() {
  1604  		t.Skip("skipping test that uses network in short mode")
  1605  	}
  1606  
  1607  	tg := testgo(t)
  1608  	defer tg.cleanup()
  1609  	tg.parallel()
  1610  	tg.makeTempdir()
  1611  	tg.setenv("GOPATH", tg.path("."))
  1612  	tg.run("get", "github.com/rsc/go-get-issue-11307")
  1613  	tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing
  1614  }
  1615  
  1616  func TestShadowingLogic(t *testing.T) {
  1617  	tg := testgo(t)
  1618  	defer tg.cleanup()
  1619  	pwd := tg.pwd()
  1620  	sep := string(filepath.ListSeparator)
  1621  	tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2"))
  1622  
  1623  	// The math in root1 is not "math" because the standard math is.
  1624  	tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math")
  1625  	pwdForwardSlash := strings.Replace(pwd, string(os.PathSeparator), "/", -1)
  1626  	if !strings.HasPrefix(pwdForwardSlash, "/") {
  1627  		pwdForwardSlash = "/" + pwdForwardSlash
  1628  	}
  1629  	// The output will have makeImportValid applies, but we only
  1630  	// bother to deal with characters we might reasonably see.
  1631  	pwdForwardSlash = strings.Replace(pwdForwardSlash, ":", "_", -1)
  1632  	want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")"
  1633  	if strings.TrimSpace(tg.getStdout()) != want {
  1634  		t.Error("shadowed math is not shadowed; looking for", want)
  1635  	}
  1636  
  1637  	// The foo in root1 is "foo".
  1638  	tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo")
  1639  	if strings.TrimSpace(tg.getStdout()) != "(foo) ()" {
  1640  		t.Error("unshadowed foo is shadowed")
  1641  	}
  1642  
  1643  	// The foo in root2 is not "foo" because the foo in root1 got there first.
  1644  	tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo")
  1645  	want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")"
  1646  	if strings.TrimSpace(tg.getStdout()) != want {
  1647  		t.Error("shadowed foo is not shadowed; looking for", want)
  1648  	}
  1649  
  1650  	// The error for go install should mention the conflicting directory.
  1651  	tg.runFail("install", "./testdata/shadow/root2/src/foo")
  1652  	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")
  1653  	if strings.TrimSpace(tg.getStderr()) != want {
  1654  		t.Error("wrong shadowed install error; looking for", want)
  1655  	}
  1656  }
  1657  
  1658  // Only succeeds if source order is preserved.
  1659  func TestSourceFileNameOrderPreserved(t *testing.T) {
  1660  	tg := testgo(t)
  1661  	defer tg.cleanup()
  1662  	tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go")
  1663  }
  1664  
  1665  // Check that coverage analysis works at all.
  1666  // Don't worry about the exact numbers but require not 0.0%.
  1667  func checkCoverage(tg *testgoData, data string) {
  1668  	if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) {
  1669  		tg.t.Error("some coverage results are 0.0%")
  1670  	}
  1671  	tg.t.Log(data)
  1672  }
  1673  
  1674  func TestCoverageRuns(t *testing.T) {
  1675  	if testing.Short() {
  1676  		t.Skip("don't build libraries for coverage in short mode")
  1677  	}
  1678  	tg := testgo(t)
  1679  	defer tg.cleanup()
  1680  	tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp")
  1681  	data := tg.getStdout() + tg.getStderr()
  1682  	tg.run("test", "-short", "-cover", "strings", "math", "regexp")
  1683  	data += tg.getStdout() + tg.getStderr()
  1684  	checkCoverage(tg, data)
  1685  }
  1686  
  1687  // Check that coverage analysis uses set mode.
  1688  func TestCoverageUsesSetMode(t *testing.T) {
  1689  	if testing.Short() {
  1690  		t.Skip("don't build libraries for coverage in short mode")
  1691  	}
  1692  	tg := testgo(t)
  1693  	defer tg.cleanup()
  1694  	tg.creatingTemp("testdata/cover.out")
  1695  	tg.run("test", "-short", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
  1696  	data := tg.getStdout() + tg.getStderr()
  1697  	if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
  1698  		t.Error(err)
  1699  	} else {
  1700  		if !bytes.Contains(out, []byte("mode: set")) {
  1701  			t.Error("missing mode: set")
  1702  		}
  1703  	}
  1704  	checkCoverage(tg, data)
  1705  }
  1706  
  1707  func TestCoverageUsesAtomicModeForRace(t *testing.T) {
  1708  	if testing.Short() {
  1709  		t.Skip("don't build libraries for coverage in short mode")
  1710  	}
  1711  	if !canRace {
  1712  		t.Skip("skipping because race detector not supported")
  1713  	}
  1714  
  1715  	tg := testgo(t)
  1716  	defer tg.cleanup()
  1717  	tg.creatingTemp("testdata/cover.out")
  1718  	tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out")
  1719  	data := tg.getStdout() + tg.getStderr()
  1720  	if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
  1721  		t.Error(err)
  1722  	} else {
  1723  		if !bytes.Contains(out, []byte("mode: atomic")) {
  1724  			t.Error("missing mode: atomic")
  1725  		}
  1726  	}
  1727  	checkCoverage(tg, data)
  1728  }
  1729  
  1730  func TestCoverageUsesActualSettingToOverrideEvenForRace(t *testing.T) {
  1731  	if testing.Short() {
  1732  		t.Skip("don't build libraries for coverage in short mode")
  1733  	}
  1734  	if !canRace {
  1735  		t.Skip("skipping because race detector not supported")
  1736  	}
  1737  
  1738  	tg := testgo(t)
  1739  	defer tg.cleanup()
  1740  	tg.creatingTemp("testdata/cover.out")
  1741  	tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-covermode=count", "-coverprofile=testdata/cover.out")
  1742  	data := tg.getStdout() + tg.getStderr()
  1743  	if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil {
  1744  		t.Error(err)
  1745  	} else {
  1746  		if !bytes.Contains(out, []byte("mode: count")) {
  1747  			t.Error("missing mode: count")
  1748  		}
  1749  	}
  1750  	checkCoverage(tg, data)
  1751  }
  1752  
  1753  func TestCoverageWithCgo(t *testing.T) {
  1754  	if !canCgo {
  1755  		t.Skip("skipping because cgo not enabled")
  1756  	}
  1757  
  1758  	tg := testgo(t)
  1759  	defer tg.cleanup()
  1760  	tg.run("test", "-short", "-cover", "./testdata/cgocover")
  1761  	data := tg.getStdout() + tg.getStderr()
  1762  	checkCoverage(tg, data)
  1763  }
  1764  
  1765  func TestCgoDependsOnSyscall(t *testing.T) {
  1766  	if testing.Short() {
  1767  		t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode")
  1768  	}
  1769  	if !canCgo {
  1770  		t.Skip("skipping because cgo not enabled")
  1771  	}
  1772  	if !canRace {
  1773  		t.Skip("skipping because race detector not supported")
  1774  	}
  1775  
  1776  	tg := testgo(t)
  1777  	defer tg.cleanup()
  1778  	files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race"))
  1779  	tg.must(err)
  1780  	for _, file := range files {
  1781  		tg.check(os.RemoveAll(file))
  1782  	}
  1783  	tg.tempFile("src/foo/foo.go", `
  1784  		package foo
  1785  		//#include <stdio.h>
  1786  		import "C"`)
  1787  	tg.setenv("GOPATH", tg.path("."))
  1788  	tg.run("build", "-race", "foo")
  1789  }
  1790  
  1791  func TestCgoShowsFullPathNames(t *testing.T) {
  1792  	if !canCgo {
  1793  		t.Skip("skipping because cgo not enabled")
  1794  	}
  1795  
  1796  	tg := testgo(t)
  1797  	defer tg.cleanup()
  1798  	tg.parallel()
  1799  	tg.tempFile("src/x/y/dirname/foo.go", `
  1800  		package foo
  1801  		import "C"
  1802  		func f() {`)
  1803  	tg.setenv("GOPATH", tg.path("."))
  1804  	tg.runFail("build", "x/y/dirname")
  1805  	tg.grepBoth("x/y/dirname", "error did not use full path")
  1806  }
  1807  
  1808  func TestCgoHandlesWlORIGIN(t *testing.T) {
  1809  	if !canCgo {
  1810  		t.Skip("skipping because cgo not enabled")
  1811  	}
  1812  
  1813  	tg := testgo(t)
  1814  	defer tg.cleanup()
  1815  	tg.parallel()
  1816  	tg.tempFile("src/origin/origin.go", `package origin
  1817  		// #cgo !darwin LDFLAGS: -Wl,-rpath -Wl,$ORIGIN
  1818  		// void f(void) {}
  1819  		import "C"
  1820  		func f() { C.f() }`)
  1821  	tg.setenv("GOPATH", tg.path("."))
  1822  	tg.run("build", "origin")
  1823  }
  1824  
  1825  // "go test -c -test.bench=XXX errors" should not hang
  1826  func TestIssue6480(t *testing.T) {
  1827  	tg := testgo(t)
  1828  	defer tg.cleanup()
  1829  	tg.makeTempdir()
  1830  	tg.cd(tg.path("."))
  1831  	tg.run("test", "-c", "-test.bench=XXX", "errors")
  1832  }
  1833  
  1834  // cmd/cgo: undefined reference when linking a C-library using gccgo
  1835  func TestIssue7573(t *testing.T) {
  1836  	if _, err := exec.LookPath("gccgo"); err != nil {
  1837  		t.Skip("skipping because no gccgo compiler found")
  1838  	}
  1839  
  1840  	tg := testgo(t)
  1841  	defer tg.cleanup()
  1842  	tg.parallel()
  1843  	tg.tempFile("src/cgoref/cgoref.go", `
  1844  package main
  1845  // #cgo LDFLAGS: -L alibpath -lalib
  1846  // void f(void) {}
  1847  import "C"
  1848  
  1849  func main() { C.f() }`)
  1850  	tg.setenv("GOPATH", tg.path("."))
  1851  	tg.run("build", "-n", "-compiler", "gccgo", "cgoref")
  1852  	tg.grepStderr(`gccgo.*\-L alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`)
  1853  }
  1854  
  1855  func TestListTemplateCanUseContextFunction(t *testing.T) {
  1856  	tg := testgo(t)
  1857  	defer tg.cleanup()
  1858  	tg.run("list", "-f", "GOARCH: {{context.GOARCH}}")
  1859  }
  1860  
  1861  // cmd/go: "go test" should fail if package does not build
  1862  func TestIssue7108(t *testing.T) {
  1863  	tg := testgo(t)
  1864  	defer tg.cleanup()
  1865  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  1866  	tg.runFail("test", "notest")
  1867  }
  1868  
  1869  // cmd/go: go test -a foo does not rebuild regexp.
  1870  func TestIssue6844(t *testing.T) {
  1871  	if testing.Short() {
  1872  		t.Skip("don't rebuild the standard libary in short mode")
  1873  	}
  1874  
  1875  	tg := testgo(t)
  1876  	defer tg.cleanup()
  1877  	tg.creatingTemp("deps.test" + exeSuffix)
  1878  	tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go")
  1879  	tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp")
  1880  }
  1881  
  1882  func TestBuildDashIInstallsDependencies(t *testing.T) {
  1883  	tg := testgo(t)
  1884  	defer tg.cleanup()
  1885  	tg.parallel()
  1886  	tg.tempFile("src/x/y/foo/foo.go", `package foo
  1887  		func F() {}`)
  1888  	tg.tempFile("src/x/y/bar/bar.go", `package bar
  1889  		import "x/y/foo"
  1890  		func F() { foo.F() }`)
  1891  	tg.setenv("GOPATH", tg.path("."))
  1892  
  1893  	checkbar := func(desc string) {
  1894  		tg.sleep()
  1895  		tg.must(os.Chtimes(tg.path("src/x/y/foo/foo.go"), time.Now(), time.Now()))
  1896  		tg.sleep()
  1897  		tg.run("build", "-v", "-i", "x/y/bar")
  1898  		tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo")
  1899  		tg.run("build", "-v", "-i", "x/y/bar")
  1900  		tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo")
  1901  	}
  1902  	checkbar("pkg")
  1903  	tg.creatingTemp("bar" + exeSuffix)
  1904  	tg.tempFile("src/x/y/bar/bar.go", `package main
  1905  		import "x/y/foo"
  1906  		func main() { foo.F() }`)
  1907  	checkbar("cmd")
  1908  }
  1909  
  1910  func TestGoBuildInTestOnlyDirectoryFailsWithAGoodError(t *testing.T) {
  1911  	tg := testgo(t)
  1912  	defer tg.cleanup()
  1913  	tg.runFail("build", "./testdata/testonly")
  1914  	tg.grepStderr("no buildable Go", "go build ./testdata/testonly produced unexpected error")
  1915  }
  1916  
  1917  func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) {
  1918  	tg := testgo(t)
  1919  	defer tg.cleanup()
  1920  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  1921  	tg.runFail("test", "-c", "testcycle/p3")
  1922  	tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error")
  1923  
  1924  	tg.runFail("test", "-c", "testcycle/q1")
  1925  	tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error")
  1926  }
  1927  
  1928  func TestGoTestFooTestWorks(t *testing.T) {
  1929  	tg := testgo(t)
  1930  	defer tg.cleanup()
  1931  	tg.run("test", "testdata/standalone_test.go")
  1932  }
  1933  
  1934  func TestGoTestXtestonlyWorks(t *testing.T) {
  1935  	tg := testgo(t)
  1936  	defer tg.cleanup()
  1937  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  1938  	tg.run("clean", "-i", "xtestonly")
  1939  	tg.run("test", "xtestonly")
  1940  }
  1941  
  1942  func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) {
  1943  	tg := testgo(t)
  1944  	defer tg.cleanup()
  1945  	tg.run("test", "-v", "./testdata/norunexample")
  1946  	tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built")
  1947  }
  1948  
  1949  func TestGoGenerateHandlesSimpleCommand(t *testing.T) {
  1950  	if runtime.GOOS == "windows" {
  1951  		t.Skip("skipping because windows has no echo command")
  1952  	}
  1953  
  1954  	tg := testgo(t)
  1955  	defer tg.cleanup()
  1956  	tg.run("generate", "./testdata/generate/test1.go")
  1957  	tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output")
  1958  }
  1959  
  1960  func TestGoGenerateHandlesCommandAlias(t *testing.T) {
  1961  	if runtime.GOOS == "windows" {
  1962  		t.Skip("skipping because windows has no echo command")
  1963  	}
  1964  
  1965  	tg := testgo(t)
  1966  	defer tg.cleanup()
  1967  	tg.run("generate", "./testdata/generate/test2.go")
  1968  	tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output")
  1969  }
  1970  
  1971  func TestGoGenerateVariableSubstitution(t *testing.T) {
  1972  	if runtime.GOOS == "windows" {
  1973  		t.Skip("skipping because windows has no echo command")
  1974  	}
  1975  
  1976  	tg := testgo(t)
  1977  	defer tg.cleanup()
  1978  	tg.run("generate", "./testdata/generate/test3.go")
  1979  	tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output")
  1980  }
  1981  
  1982  func TestGoGenerateRunFlag(t *testing.T) {
  1983  	if runtime.GOOS == "windows" {
  1984  		t.Skip("skipping because windows has no echo command")
  1985  	}
  1986  
  1987  	tg := testgo(t)
  1988  	defer tg.cleanup()
  1989  	tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go")
  1990  	tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes")
  1991  	tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no")
  1992  }
  1993  
  1994  func TestGoGetCustomDomainWildcard(t *testing.T) {
  1995  	testenv.MustHaveExternalNetwork(t)
  1996  
  1997  	tg := testgo(t)
  1998  	defer tg.cleanup()
  1999  	tg.makeTempdir()
  2000  	tg.setenv("GOPATH", tg.path("."))
  2001  	tg.run("get", "-u", "rsc.io/pdf/...")
  2002  	tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd")
  2003  }
  2004  
  2005  func TestGoGetInternalWildcard(t *testing.T) {
  2006  	testenv.MustHaveExternalNetwork(t)
  2007  
  2008  	tg := testgo(t)
  2009  	defer tg.cleanup()
  2010  	tg.makeTempdir()
  2011  	tg.setenv("GOPATH", tg.path("."))
  2012  	// used to fail with errors about internal packages
  2013  	tg.run("get", "github.com/rsc/go-get-issue-11960/...")
  2014  }
  2015  
  2016  func TestGoVetWithExternalTests(t *testing.T) {
  2017  	testenv.MustHaveExternalNetwork(t)
  2018  
  2019  	tg := testgo(t)
  2020  	defer tg.cleanup()
  2021  	tg.makeTempdir()
  2022  	tg.setenv("GOPATH", tg.path("."))
  2023  	tg.run("get", "golang.org/x/tools/cmd/vet")
  2024  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  2025  	tg.runFail("vet", "vetpkg")
  2026  	tg.grepBoth("missing argument for Printf", "go vet vetpkg did not find missing argument for Printf")
  2027  }
  2028  
  2029  func TestGoVetWithTags(t *testing.T) {
  2030  	testenv.MustHaveExternalNetwork(t)
  2031  
  2032  	tg := testgo(t)
  2033  	defer tg.cleanup()
  2034  	tg.makeTempdir()
  2035  	tg.setenv("GOPATH", tg.path("."))
  2036  	tg.run("get", "golang.org/x/tools/cmd/vet")
  2037  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  2038  	tg.runFail("vet", "-tags", "tagtest", "vetpkg")
  2039  	tg.grepBoth(`c\.go.*wrong number of args for format`, "go get vetpkg did not run scan tagged file")
  2040  }
  2041  
  2042  // Issue 9767.
  2043  func TestGoGetRscIoToolstash(t *testing.T) {
  2044  	testenv.MustHaveExternalNetwork(t)
  2045  
  2046  	tg := testgo(t)
  2047  	defer tg.cleanup()
  2048  	tg.tempDir("src/rsc.io")
  2049  	tg.setenv("GOPATH", tg.path("."))
  2050  	tg.cd(tg.path("src/rsc.io"))
  2051  	tg.run("get", "./toolstash")
  2052  }
  2053  
  2054  // Test that you can not import a main package.
  2055  func TestIssue4210(t *testing.T) {
  2056  	tg := testgo(t)
  2057  	defer tg.cleanup()
  2058  	tg.tempFile("src/x/main.go", `package main
  2059  		var X int
  2060  		func main() {}`)
  2061  	tg.tempFile("src/y/main.go", `package main
  2062  		import "fmt"
  2063  		import xmain "x"
  2064  		func main() {
  2065  			fmt.Println(xmain.X)
  2066  		}`)
  2067  	tg.setenv("GOPATH", tg.path("."))
  2068  	tg.runFail("build", "y")
  2069  	tg.grepBoth("is a program", `did not find expected error message ("is a program")`)
  2070  }
  2071  
  2072  func TestGoGetInsecure(t *testing.T) {
  2073  	testenv.MustHaveExternalNetwork(t)
  2074  
  2075  	tg := testgo(t)
  2076  	defer tg.cleanup()
  2077  	tg.makeTempdir()
  2078  	tg.setenv("GOPATH", tg.path("."))
  2079  	tg.failSSH()
  2080  
  2081  	const repo = "wh3rd.net/git.git"
  2082  
  2083  	// Try go get -d of HTTP-only repo (should fail).
  2084  	tg.runFail("get", "-d", repo)
  2085  
  2086  	// Try again with -insecure (should succeed).
  2087  	tg.run("get", "-d", "-insecure", repo)
  2088  
  2089  	// Try updating without -insecure (should fail).
  2090  	tg.runFail("get", "-d", "-u", "-f", repo)
  2091  }
  2092  
  2093  func TestGoGetUpdateInsecure(t *testing.T) {
  2094  	testenv.MustHaveExternalNetwork(t)
  2095  
  2096  	tg := testgo(t)
  2097  	defer tg.cleanup()
  2098  	tg.makeTempdir()
  2099  	tg.setenv("GOPATH", tg.path("."))
  2100  
  2101  	const repo = "github.com/golang/example"
  2102  
  2103  	// Clone the repo via HTTP manually.
  2104  	cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo))
  2105  	if out, err := cmd.CombinedOutput(); err != nil {
  2106  		t.Fatalf("cloning %v repo: %v\n%s", repo, err, out)
  2107  	}
  2108  
  2109  	// Update without -insecure should fail.
  2110  	// Update with -insecure should succeed.
  2111  	// We need -f to ignore import comments.
  2112  	const pkg = repo + "/hello"
  2113  	tg.runFail("get", "-d", "-u", "-f", pkg)
  2114  	tg.run("get", "-d", "-u", "-f", "-insecure", pkg)
  2115  }
  2116  
  2117  func TestGoGetInsecureCustomDomain(t *testing.T) {
  2118  	testenv.MustHaveExternalNetwork(t)
  2119  
  2120  	tg := testgo(t)
  2121  	defer tg.cleanup()
  2122  	tg.makeTempdir()
  2123  	tg.setenv("GOPATH", tg.path("."))
  2124  
  2125  	const repo = "wh3rd.net/repo"
  2126  	tg.runFail("get", "-d", repo)
  2127  	tg.run("get", "-d", "-insecure", repo)
  2128  }
  2129  
  2130  func TestIssue10193(t *testing.T) {
  2131  	testenv.MustHaveExternalNetwork(t)
  2132  
  2133  	tg := testgo(t)
  2134  	defer tg.cleanup()
  2135  	tg.parallel()
  2136  	tg.tempDir("src")
  2137  	tg.setenv("GOPATH", tg.path("."))
  2138  	tg.runFail("get", "code.google.com/p/rsc/pdf")
  2139  	tg.grepStderr("is shutting down", "missed warning about code.google.com")
  2140  }
  2141  
  2142  func TestGoRunDirs(t *testing.T) {
  2143  	tg := testgo(t)
  2144  	defer tg.cleanup()
  2145  	tg.cd("testdata/rundir")
  2146  	tg.runFail("run", "x.go", "sub/sub.go")
  2147  	tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output")
  2148  	tg.runFail("run", "sub/sub.go", "x.go")
  2149  	tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output")
  2150  }
  2151  
  2152  func TestGoInstallPkgdir(t *testing.T) {
  2153  	tg := testgo(t)
  2154  	defer tg.cleanup()
  2155  	tg.makeTempdir()
  2156  	pkg := tg.path(".")
  2157  	tg.run("install", "-pkgdir", pkg, "errors")
  2158  	_, err := os.Stat(filepath.Join(pkg, "errors.a"))
  2159  	tg.must(err)
  2160  	_, err = os.Stat(filepath.Join(pkg, "runtime.a"))
  2161  	tg.must(err)
  2162  }
  2163  
  2164  func TestGoTestRaceInstallCgo(t *testing.T) {
  2165  	switch sys := runtime.GOOS + "/" + runtime.GOARCH; sys {
  2166  	case "darwin/amd64", "freebsd/amd64", "linux/amd64", "windows/amd64":
  2167  		// ok
  2168  	default:
  2169  		t.Skip("no race detector on %s", sys)
  2170  	}
  2171  
  2172  	if !build.Default.CgoEnabled {
  2173  		t.Skip("no race detector without cgo")
  2174  	}
  2175  
  2176  	// golang.org/issue/10500.
  2177  	// This used to install a race-enabled cgo.
  2178  	tg := testgo(t)
  2179  	defer tg.cleanup()
  2180  	tg.run("tool", "-n", "cgo")
  2181  	cgo := strings.TrimSpace(tg.stdout.String())
  2182  	old, err := os.Stat(cgo)
  2183  	tg.must(err)
  2184  	tg.run("test", "-race", "-i", "runtime/race")
  2185  	new, err := os.Stat(cgo)
  2186  	tg.must(err)
  2187  	if new.ModTime() != old.ModTime() {
  2188  		t.Fatalf("go test -i runtime/race reinstalled cmd/cgo")
  2189  	}
  2190  }
  2191  
  2192  func TestGoTestImportErrorStack(t *testing.T) {
  2193  	const out = `package testdep/p1 (test)
  2194  	imports testdep/p2
  2195  	imports testdep/p3: no buildable Go source files`
  2196  
  2197  	tg := testgo(t)
  2198  	defer tg.cleanup()
  2199  	tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata"))
  2200  	tg.runFail("test", "testdep/p1")
  2201  	if !strings.Contains(tg.stderr.String(), out) {
  2202  		t.Fatal("did not give full import stack:\n\n%s", tg.stderr.String())
  2203  	}
  2204  }
  2205  
  2206  func TestGoGetUpdate(t *testing.T) {
  2207  	// golang.org/issue/9224.
  2208  	// The recursive updating was trying to walk to
  2209  	// former dependencies, not current ones.
  2210  
  2211  	testenv.MustHaveExternalNetwork(t)
  2212  
  2213  	tg := testgo(t)
  2214  	defer tg.cleanup()
  2215  	tg.makeTempdir()
  2216  	tg.setenv("GOPATH", tg.path("."))
  2217  
  2218  	rewind := func() {
  2219  		tg.run("get", "github.com/rsc/go-get-issue-9224-cmd")
  2220  		cmd := exec.Command("git", "reset", "--hard", "HEAD~")
  2221  		cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib")
  2222  		out, err := cmd.CombinedOutput()
  2223  		if err != nil {
  2224  			t.Fatalf("git: %v\n%s", err, out)
  2225  		}
  2226  	}
  2227  
  2228  	rewind()
  2229  	tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd")
  2230  
  2231  	// Again with -d -u.
  2232  	rewind()
  2233  	tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd")
  2234  }
  2235  
  2236  func TestGoGetDomainRoot(t *testing.T) {
  2237  	// golang.org/issue/9357.
  2238  	// go get foo.io (not foo.io/subdir) was not working consistently.
  2239  
  2240  	testenv.MustHaveExternalNetwork(t)
  2241  
  2242  	tg := testgo(t)
  2243  	defer tg.cleanup()
  2244  	tg.makeTempdir()
  2245  	tg.setenv("GOPATH", tg.path("."))
  2246  
  2247  	// go-get-issue-9357.appspot.com is running
  2248  	// the code at github.com/rsc/go-get-issue-9357,
  2249  	// a trivial Go on App Engine app that serves a
  2250  	// <meta> tag for the domain root.
  2251  	tg.run("get", "-d", "go-get-issue-9357.appspot.com")
  2252  	tg.run("get", "go-get-issue-9357.appspot.com")
  2253  	tg.run("get", "-u", "go-get-issue-9357.appspot.com")
  2254  
  2255  	tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
  2256  	tg.run("get", "go-get-issue-9357.appspot.com")
  2257  
  2258  	tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com")))
  2259  	tg.run("get", "-u", "go-get-issue-9357.appspot.com")
  2260  }
  2261  
  2262  func TestGoInstallShadowedGOPATH(t *testing.T) {
  2263  	// golang.org/issue/3652.
  2264  	// go get foo.io (not foo.io/subdir) was not working consistently.
  2265  
  2266  	testenv.MustHaveExternalNetwork(t)
  2267  
  2268  	tg := testgo(t)
  2269  	defer tg.cleanup()
  2270  	tg.makeTempdir()
  2271  	tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2"))
  2272  
  2273  	tg.tempDir("gopath1/src/test")
  2274  	tg.tempDir("gopath2/src/test")
  2275  	tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n")
  2276  
  2277  	tg.cd(tg.path("gopath2/src/test"))
  2278  	tg.runFail("install")
  2279  	tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error")
  2280  }
  2281  
  2282  func TestIssue11709(t *testing.T) {
  2283  	tg := testgo(t)
  2284  	defer tg.cleanup()
  2285  	tg.tempFile("run.go", `
  2286  		package main
  2287  		import "os"
  2288  		func main() {
  2289  			if os.Getenv("TERM") != "" {
  2290  				os.Exit(1)
  2291  			}
  2292  		}`)
  2293  	tg.unsetenv("TERM")
  2294  	tg.run("run", tg.path("run.go"))
  2295  }
  2296  
  2297  func TestGoBuildOutput(t *testing.T) {
  2298  	tg := testgo(t)
  2299  	defer tg.cleanup()
  2300  
  2301  	tg.makeTempdir()
  2302  	tg.cd(tg.path("."))
  2303  
  2304  	nonExeSuffix := ".exe"
  2305  	if exeSuffix == ".exe" {
  2306  		nonExeSuffix = ""
  2307  	}
  2308  
  2309  	tg.tempFile("x.go", "package main\nfunc main(){}\n")
  2310  	tg.run("build", "x.go")
  2311  	tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix)
  2312  	tg.must(os.Remove(tg.path("x" + exeSuffix)))
  2313  	tg.mustNotExist("x" + nonExeSuffix)
  2314  
  2315  	tg.run("build", "-o", "myprog", "x.go")
  2316  	tg.mustNotExist("x")
  2317  	tg.mustNotExist("x.exe")
  2318  	tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog")
  2319  	tg.mustNotExist("myprog.exe")
  2320  
  2321  	tg.tempFile("p.go", "package p\n")
  2322  	tg.run("build", "p.go")
  2323  	tg.mustNotExist("p")
  2324  	tg.mustNotExist("p.a")
  2325  	tg.mustNotExist("p.o")
  2326  	tg.mustNotExist("p.exe")
  2327  
  2328  	tg.run("build", "-o", "p.a", "p.go")
  2329  	tg.wantArchive("p.a")
  2330  
  2331  	tg.run("build", "cmd/gofmt")
  2332  	tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix)
  2333  	tg.must(os.Remove(tg.path("gofmt" + exeSuffix)))
  2334  	tg.mustNotExist("gofmt" + nonExeSuffix)
  2335  
  2336  	tg.run("build", "-o", "mygofmt", "cmd/gofmt")
  2337  	tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt")
  2338  	tg.mustNotExist("mygofmt.exe")
  2339  	tg.mustNotExist("gofmt")
  2340  	tg.mustNotExist("gofmt.exe")
  2341  
  2342  	tg.run("build", "sync/atomic")
  2343  	tg.mustNotExist("atomic")
  2344  	tg.mustNotExist("atomic.exe")
  2345  
  2346  	tg.run("build", "-o", "myatomic.a", "sync/atomic")
  2347  	tg.wantArchive("myatomic.a")
  2348  	tg.mustNotExist("atomic")
  2349  	tg.mustNotExist("atomic.a")
  2350  	tg.mustNotExist("atomic.exe")
  2351  
  2352  	tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic")
  2353  	tg.grepStderr("multiple packages", "did not reject -o with multiple packages")
  2354  }