github.com/dannin/go@v0.0.0-20161031215817-d35dfd405eaa/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/race" 14 "internal/testenv" 15 "io" 16 "io/ioutil" 17 "os" 18 "os/exec" 19 "path/filepath" 20 "regexp" 21 "runtime" 22 "strconv" 23 "strings" 24 "testing" 25 "time" 26 ) 27 28 var ( 29 canRun = true // whether we can run go or ./testgo 30 canRace = false // whether we can run the race detector 31 canCgo = false // whether we can use cgo 32 33 exeSuffix string // ".exe" on Windows 34 35 skipExternal = false // skip external tests 36 ) 37 38 func init() { 39 switch runtime.GOOS { 40 case "android", "nacl": 41 canRun = false 42 case "darwin": 43 switch runtime.GOARCH { 44 case "arm", "arm64": 45 canRun = false 46 } 47 case "linux": 48 switch runtime.GOARCH { 49 case "arm": 50 // many linux/arm machines are too slow to run 51 // the full set of external tests. 52 skipExternal = true 53 } 54 case "freebsd": 55 switch runtime.GOARCH { 56 case "arm": 57 // many freebsd/arm machines are too slow to run 58 // the full set of external tests. 59 skipExternal = true 60 canRun = false 61 } 62 case "windows": 63 exeSuffix = ".exe" 64 } 65 } 66 67 // The TestMain function creates a go command for testing purposes and 68 // deletes it after the tests have been run. 69 func TestMain(m *testing.M) { 70 flag.Parse() 71 72 if canRun { 73 args := []string{"build", "-tags", "testgo", "-o", "testgo" + exeSuffix} 74 if race.Enabled { 75 args = append(args, "-race") 76 } 77 out, err := exec.Command("go", args...).CombinedOutput() 78 if err != nil { 79 fmt.Fprintf(os.Stderr, "building testgo failed: %v\n%s", err, out) 80 os.Exit(2) 81 } 82 83 if out, err := exec.Command("./testgo"+exeSuffix, "env", "CGO_ENABLED").Output(); err != nil { 84 fmt.Fprintf(os.Stderr, "running testgo failed: %v\n", err) 85 canRun = false 86 } else { 87 canCgo, err = strconv.ParseBool(strings.TrimSpace(string(out))) 88 if err != nil { 89 fmt.Fprintf(os.Stderr, "can't parse go env CGO_ENABLED output: %v\n", strings.TrimSpace(string(out))) 90 } 91 } 92 93 switch runtime.GOOS { 94 case "linux", "darwin", "freebsd", "windows": 95 canRace = canCgo && runtime.GOARCH == "amd64" 96 } 97 } 98 99 // Don't let these environment variables confuse the test. 100 os.Unsetenv("GOBIN") 101 os.Unsetenv("GOPATH") 102 if home, ccacheDir := os.Getenv("HOME"), os.Getenv("CCACHE_DIR"); home != "" && ccacheDir == "" { 103 // On some systems the default C compiler is ccache. 104 // Setting HOME to a non-existent directory will break 105 // those systems. Set CCACHE_DIR to cope. Issue 17668. 106 os.Setenv("CCACHE_DIR", filepath.Join(home, ".ccache")) 107 } 108 os.Setenv("HOME", "/test-go-home-does-not-exist") 109 110 r := m.Run() 111 112 if canRun { 113 os.Remove("testgo" + exeSuffix) 114 } 115 116 os.Exit(r) 117 } 118 119 // The length of an mtime tick on this system. This is an estimate of 120 // how long we need to sleep to ensure that the mtime of two files is 121 // different. 122 // We used to try to be clever but that didn't always work (see golang.org/issue/12205). 123 var mtimeTick time.Duration = 1 * time.Second 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 skipExternal { 142 t.Skip("skipping external tests on %s/%s", runtime.GOOS, runtime.GOARCH) 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 // grepCountBoth returns the number of times a regexp is seen in both 432 // standard output and standard error. 433 func (tg *testgoData) grepCountBoth(match string) int { 434 return tg.doGrepCount(match, &tg.stdout) + tg.doGrepCount(match, &tg.stderr) 435 } 436 437 // creatingTemp records that the test plans to create a temporary file 438 // or directory. If the file or directory exists already, it will be 439 // removed. When the test completes, the file or directory will be 440 // removed if it exists. 441 func (tg *testgoData) creatingTemp(path string) { 442 if filepath.IsAbs(path) && !strings.HasPrefix(path, tg.tempdir) { 443 tg.t.Fatalf("internal testsuite error: creatingTemp(%q) with absolute path not in temporary directory", path) 444 } 445 // If we have changed the working directory, make sure we have 446 // an absolute path, because we are going to change directory 447 // back before we remove the temporary. 448 if tg.wd != "" && !filepath.IsAbs(path) { 449 path = filepath.Join(tg.pwd(), path) 450 } 451 tg.must(os.RemoveAll(path)) 452 tg.temps = append(tg.temps, path) 453 } 454 455 // makeTempdir makes a temporary directory for a run of testgo. If 456 // the temporary directory was already created, this does nothing. 457 func (tg *testgoData) makeTempdir() { 458 if tg.tempdir == "" { 459 var err error 460 tg.tempdir, err = ioutil.TempDir("", "gotest") 461 tg.must(err) 462 } 463 } 464 465 // tempFile adds a temporary file for a run of testgo. 466 func (tg *testgoData) tempFile(path, contents string) { 467 tg.makeTempdir() 468 tg.must(os.MkdirAll(filepath.Join(tg.tempdir, filepath.Dir(path)), 0755)) 469 bytes := []byte(contents) 470 if strings.HasSuffix(path, ".go") { 471 formatted, err := format.Source(bytes) 472 if err == nil { 473 bytes = formatted 474 } 475 } 476 tg.must(ioutil.WriteFile(filepath.Join(tg.tempdir, path), bytes, 0644)) 477 } 478 479 // tempDir adds a temporary directory for a run of testgo. 480 func (tg *testgoData) tempDir(path string) { 481 tg.makeTempdir() 482 if err := os.MkdirAll(filepath.Join(tg.tempdir, path), 0755); err != nil && !os.IsExist(err) { 483 tg.t.Fatal(err) 484 } 485 } 486 487 // path returns the absolute pathname to file with the temporary 488 // directory. 489 func (tg *testgoData) path(name string) string { 490 if tg.tempdir == "" { 491 tg.t.Fatalf("internal testsuite error: path(%q) with no tempdir", name) 492 } 493 if name == "." { 494 return tg.tempdir 495 } 496 return filepath.Join(tg.tempdir, name) 497 } 498 499 // mustExist fails if path does not exist. 500 func (tg *testgoData) mustExist(path string) { 501 if _, err := os.Stat(path); err != nil { 502 if os.IsNotExist(err) { 503 tg.t.Fatalf("%s does not exist but should", path) 504 } 505 tg.t.Fatalf("%s stat failed: %v", path, err) 506 } 507 } 508 509 // mustNotExist fails if path exists. 510 func (tg *testgoData) mustNotExist(path string) { 511 if _, err := os.Stat(path); err == nil || !os.IsNotExist(err) { 512 tg.t.Fatalf("%s exists but should not (%v)", path, err) 513 } 514 } 515 516 // wantExecutable fails with msg if path is not executable. 517 func (tg *testgoData) wantExecutable(path, msg string) { 518 if st, err := os.Stat(path); err != nil { 519 if !os.IsNotExist(err) { 520 tg.t.Log(err) 521 } 522 tg.t.Fatal(msg) 523 } else { 524 if runtime.GOOS != "windows" && st.Mode()&0111 == 0 { 525 tg.t.Fatalf("binary %s exists but is not executable", path) 526 } 527 } 528 } 529 530 // wantArchive fails if path is not an archive. 531 func (tg *testgoData) wantArchive(path string) { 532 f, err := os.Open(path) 533 if err != nil { 534 tg.t.Fatal(err) 535 } 536 buf := make([]byte, 100) 537 io.ReadFull(f, buf) 538 f.Close() 539 if !bytes.HasPrefix(buf, []byte("!<arch>\n")) { 540 tg.t.Fatalf("file %s exists but is not an archive", path) 541 } 542 } 543 544 // isStale reports whether pkg is stale, and why 545 func (tg *testgoData) isStale(pkg string) (bool, string) { 546 tg.run("list", "-f", "{{.Stale}}:{{.StaleReason}}", pkg) 547 v := strings.TrimSpace(tg.getStdout()) 548 f := strings.SplitN(v, ":", 2) 549 if len(f) == 2 { 550 switch f[0] { 551 case "true": 552 return true, f[1] 553 case "false": 554 return false, f[1] 555 } 556 } 557 tg.t.Fatalf("unexpected output checking staleness of package %v: %v", pkg, v) 558 panic("unreachable") 559 } 560 561 // wantStale fails with msg if pkg is not stale. 562 func (tg *testgoData) wantStale(pkg, reason, msg string) { 563 stale, why := tg.isStale(pkg) 564 if !stale { 565 tg.t.Fatal(msg) 566 } 567 if reason == "" && why != "" || !strings.Contains(why, reason) { 568 tg.t.Errorf("wrong reason for Stale=true: %q, want %q", why, reason) 569 } 570 } 571 572 // wantNotStale fails with msg if pkg is stale. 573 func (tg *testgoData) wantNotStale(pkg, reason, msg string) { 574 stale, why := tg.isStale(pkg) 575 if stale { 576 tg.t.Fatal(msg) 577 } 578 if reason == "" && why != "" || !strings.Contains(why, reason) { 579 tg.t.Errorf("wrong reason for Stale=false: %q, want %q", why, reason) 580 } 581 } 582 583 // cleanup cleans up a test that runs testgo. 584 func (tg *testgoData) cleanup() { 585 if tg.wd != "" { 586 if err := os.Chdir(tg.wd); err != nil { 587 // We are unlikely to be able to continue. 588 fmt.Fprintln(os.Stderr, "could not restore working directory, crashing:", err) 589 os.Exit(2) 590 } 591 } 592 for _, path := range tg.temps { 593 tg.check(os.RemoveAll(path)) 594 } 595 if tg.tempdir != "" { 596 tg.check(os.RemoveAll(tg.tempdir)) 597 } 598 } 599 600 // failSSH puts an ssh executable in the PATH that always fails. 601 // This is to stub out uses of ssh by go get. 602 func (tg *testgoData) failSSH() { 603 wd, err := os.Getwd() 604 if err != nil { 605 tg.t.Fatal(err) 606 } 607 fail := filepath.Join(wd, "testdata/failssh") 608 tg.setenv("PATH", fmt.Sprintf("%v%c%v", fail, filepath.ListSeparator, os.Getenv("PATH"))) 609 } 610 611 func TestFileLineInErrorMessages(t *testing.T) { 612 tg := testgo(t) 613 defer tg.cleanup() 614 tg.parallel() 615 tg.tempFile("err.go", `package main; import "bar"`) 616 path := tg.path("err.go") 617 tg.runFail("run", path) 618 shortPath := path 619 if rel, err := filepath.Rel(tg.pwd(), path); err == nil && len(rel) < len(path) { 620 shortPath = rel 621 } 622 tg.grepStderr("^"+regexp.QuoteMeta(shortPath)+":", "missing file:line in error message") 623 } 624 625 func TestProgramNameInCrashMessages(t *testing.T) { 626 tg := testgo(t) 627 defer tg.cleanup() 628 tg.parallel() 629 tg.tempFile("triv.go", `package main; func main() {}`) 630 tg.runFail("build", "-ldflags", "-crash_for_testing", tg.path("triv.go")) 631 tg.grepStderr(`[/\\]tool[/\\].*[/\\]link`, "missing linker name in error message") 632 } 633 634 func TestBrokenTestsWithoutTestFunctionsAllFail(t *testing.T) { 635 tg := testgo(t) 636 defer tg.cleanup() 637 tg.runFail("test", "./testdata/src/badtest/...") 638 tg.grepBothNot("^ok", "test passed unexpectedly") 639 tg.grepBoth("FAIL.*badtest/badexec", "test did not run everything") 640 tg.grepBoth("FAIL.*badtest/badsyntax", "test did not run everything") 641 tg.grepBoth("FAIL.*badtest/badvar", "test did not run everything") 642 } 643 644 func TestGoBuildDashAInDevBranch(t *testing.T) { 645 if testing.Short() { 646 t.Skip("don't rebuild the standard library in short mode") 647 } 648 649 tg := testgo(t) 650 defer tg.cleanup() 651 tg.run("install", "math") // should be up to date already but just in case 652 tg.setenv("TESTGO_IS_GO_RELEASE", "0") 653 tg.run("build", "-v", "-a", "math") 654 tg.grepStderr("runtime", "testgo build -a math in dev branch DID NOT build runtime, but should have") 655 656 // Everything is out of date. Rebuild to leave things in a better state. 657 tg.run("install", "std") 658 } 659 660 func TestGoBuildDashAInReleaseBranch(t *testing.T) { 661 if testing.Short() { 662 t.Skip("don't rebuild the standard library in short mode") 663 } 664 665 tg := testgo(t) 666 defer tg.cleanup() 667 tg.run("install", "math", "net/http") // should be up to date already but just in case 668 tg.setenv("TESTGO_IS_GO_RELEASE", "1") 669 tg.run("install", "-v", "-a", "math") 670 tg.grepStderr("runtime", "testgo build -a math in release branch DID NOT build runtime, but should have") 671 672 // Now runtime.a is updated (newer mtime), so everything would look stale if not for being a release. 673 tg.run("build", "-v", "net/http") 674 tg.grepStderrNot("strconv", "testgo build -v net/http in release branch with newer runtime.a DID build strconv but should not have") 675 tg.grepStderrNot("golang.org/x/net/http2/hpack", "testgo build -v net/http in release branch with newer runtime.a DID build .../golang.org/x/net/http2/hpack but should not have") 676 tg.grepStderrNot("net/http", "testgo build -v net/http in release branch with newer runtime.a DID build net/http but should not have") 677 678 // Everything is out of date. Rebuild to leave things in a better state. 679 tg.run("install", "std") 680 } 681 682 func TestNewReleaseRebuildsStalePackagesInGOPATH(t *testing.T) { 683 if testing.Short() { 684 t.Skip("don't rebuild the standard library in short mode") 685 } 686 687 tg := testgo(t) 688 defer tg.cleanup() 689 690 addNL := func(name string) (restore func()) { 691 data, err := ioutil.ReadFile(name) 692 if err != nil { 693 t.Fatal(err) 694 } 695 old := data 696 data = append(data, '\n') 697 if err := ioutil.WriteFile(name, append(data, '\n'), 0666); err != nil { 698 t.Fatal(err) 699 } 700 tg.sleep() 701 return func() { 702 if err := ioutil.WriteFile(name, old, 0666); err != nil { 703 t.Fatal(err) 704 } 705 } 706 } 707 708 tg.setenv("TESTGO_IS_GO_RELEASE", "1") 709 710 tg.tempFile("d1/src/p1/p1.go", `package p1`) 711 tg.setenv("GOPATH", tg.path("d1")) 712 tg.run("install", "-a", "p1") 713 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly") 714 tg.sleep() 715 716 // Changing mtime and content of runtime/internal/sys/sys.go 717 // should have no effect: we're in a release, which doesn't rebuild 718 // for general mtime or content changes. 719 sys := runtime.GOROOT() + "/src/runtime/internal/sys/sys.go" 720 restore := addNL(sys) 721 defer restore() 722 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after updating runtime/internal/sys/sys.go") 723 restore() 724 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after restoring runtime/internal/sys/sys.go") 725 726 // But changing runtime/internal/sys/zversion.go should have an effect: 727 // that's how we tell when we flip from one release to another. 728 zversion := runtime.GOROOT() + "/src/runtime/internal/sys/zversion.go" 729 restore = addNL(zversion) 730 defer restore() 731 tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing to new release") 732 restore() 733 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly, after changing back to old release") 734 addNL(zversion) 735 tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing again to new release") 736 tg.run("install", "p1") 737 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with new release") 738 739 // Restore to "old" release. 740 restore() 741 tg.wantStale("p1", "build ID mismatch", "./testgo list claims p1 is NOT stale, incorrectly, after changing to old release after new build") 742 tg.run("install", "p1") 743 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after building with old release") 744 745 // Everything is out of date. Rebuild to leave things in a better state. 746 tg.run("install", "std") 747 } 748 749 func TestGoListStandard(t *testing.T) { 750 tg := testgo(t) 751 defer tg.cleanup() 752 tg.cd(runtime.GOROOT() + "/src") 753 tg.run("list", "-f", "{{if not .Standard}}{{.ImportPath}}{{end}}", "./...") 754 stdout := tg.getStdout() 755 for _, line := range strings.Split(stdout, "\n") { 756 if strings.HasPrefix(line, "_/") && strings.HasSuffix(line, "/src") { 757 // $GOROOT/src shows up if there are any .go files there. 758 // We don't care. 759 continue 760 } 761 if line == "" { 762 continue 763 } 764 t.Errorf("package in GOROOT not listed as standard: %v", line) 765 } 766 767 // Similarly, expanding std should include some of our vendored code. 768 tg.run("list", "std", "cmd") 769 tg.grepStdout("golang.org/x/net/http2/hpack", "list std cmd did not mention vendored hpack") 770 tg.grepStdout("golang.org/x/arch/x86/x86asm", "list std cmd did not mention vendored x86asm") 771 } 772 773 func TestGoInstallCleansUpAfterGoBuild(t *testing.T) { 774 tg := testgo(t) 775 defer tg.cleanup() 776 tg.tempFile("src/mycmd/main.go", `package main; func main(){}`) 777 tg.setenv("GOPATH", tg.path(".")) 778 tg.cd(tg.path("src/mycmd")) 779 780 doesNotExist := func(file, msg string) { 781 if _, err := os.Stat(file); err == nil { 782 t.Fatal(msg) 783 } else if !os.IsNotExist(err) { 784 t.Fatal(msg, "error:", err) 785 } 786 } 787 788 tg.run("build") 789 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary") 790 tg.run("install") 791 doesNotExist("mycmd"+exeSuffix, "testgo install did not remove command binary") 792 tg.run("build") 793 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (second time)") 794 // Running install with arguments does not remove the target, 795 // even in the same directory. 796 tg.run("install", "mycmd") 797 tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary when run in mycmd") 798 tg.run("build") 799 tg.wantExecutable("mycmd"+exeSuffix, "testgo build did not write command binary (third time)") 800 // And especially not outside the directory. 801 tg.cd(tg.path(".")) 802 if data, err := ioutil.ReadFile("src/mycmd/mycmd" + exeSuffix); err != nil { 803 t.Fatal("could not read file:", err) 804 } else { 805 if err := ioutil.WriteFile("mycmd"+exeSuffix, data, 0555); err != nil { 806 t.Fatal("could not write file:", err) 807 } 808 } 809 tg.run("install", "mycmd") 810 tg.wantExecutable("src/mycmd/mycmd"+exeSuffix, "testgo install mycmd removed command binary from its source dir when run outside mycmd") 811 tg.wantExecutable("mycmd"+exeSuffix, "testgo install mycmd removed command binary from current dir when run outside mycmd") 812 } 813 814 func TestGoInstallRebuildsStalePackagesInOtherGOPATH(t *testing.T) { 815 tg := testgo(t) 816 defer tg.cleanup() 817 tg.parallel() 818 tg.tempFile("d1/src/p1/p1.go", `package p1 819 import "p2" 820 func F() { p2.F() }`) 821 tg.tempFile("d2/src/p2/p2.go", `package p2 822 func F() {}`) 823 sep := string(filepath.ListSeparator) 824 tg.setenv("GOPATH", tg.path("d1")+sep+tg.path("d2")) 825 tg.run("install", "p1") 826 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale, incorrectly") 827 tg.wantNotStale("p2", "", "./testgo list claims p2 is stale, incorrectly") 828 tg.sleep() 829 if f, err := os.OpenFile(tg.path("d2/src/p2/p2.go"), os.O_WRONLY|os.O_APPEND, 0); err != nil { 830 t.Fatal(err) 831 } else if _, err = f.WriteString(`func G() {}`); err != nil { 832 t.Fatal(err) 833 } else { 834 tg.must(f.Close()) 835 } 836 tg.wantStale("p2", "newer source file", "./testgo list claims p2 is NOT stale, incorrectly") 837 tg.wantStale("p1", "stale dependency", "./testgo list claims p1 is NOT stale, incorrectly") 838 839 tg.run("install", "p1") 840 tg.wantNotStale("p2", "", "./testgo list claims p2 is stale after reinstall, incorrectly") 841 tg.wantNotStale("p1", "", "./testgo list claims p1 is stale after reinstall, incorrectly") 842 } 843 844 func TestGoInstallDetectsRemovedFiles(t *testing.T) { 845 tg := testgo(t) 846 defer tg.cleanup() 847 tg.parallel() 848 tg.tempFile("src/mypkg/x.go", `package mypkg`) 849 tg.tempFile("src/mypkg/y.go", `package mypkg`) 850 tg.tempFile("src/mypkg/z.go", `// +build missingtag 851 852 package mypkg`) 853 tg.setenv("GOPATH", tg.path(".")) 854 tg.run("install", "mypkg") 855 tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale, incorrectly") 856 // z.go was not part of the build; removing it is okay. 857 tg.must(os.Remove(tg.path("src/mypkg/z.go"))) 858 tg.wantNotStale("mypkg", "", "./testgo list mypkg claims mypkg is stale after removing z.go; should not be stale") 859 // y.go was part of the package; removing it should be detected. 860 tg.must(os.Remove(tg.path("src/mypkg/y.go"))) 861 tg.wantStale("mypkg", "build ID mismatch", "./testgo list mypkg claims mypkg is NOT stale after removing y.go; should be stale") 862 } 863 864 func TestWildcardMatchesSyntaxErrorDirs(t *testing.T) { 865 tg := testgo(t) 866 defer tg.cleanup() 867 tg.tempFile("src/mypkg/x.go", `package mypkg`) 868 tg.tempFile("src/mypkg/y.go", `pkg mypackage`) 869 tg.setenv("GOPATH", tg.path(".")) 870 tg.cd(tg.path("src/mypkg")) 871 tg.runFail("list", "./...") 872 tg.runFail("build", "./...") 873 tg.runFail("install", "./...") 874 } 875 876 func TestGoListWithTags(t *testing.T) { 877 tg := testgo(t) 878 defer tg.cleanup() 879 tg.tempFile("src/mypkg/x.go", "// +build thetag\n\npackage mypkg\n") 880 tg.setenv("GOPATH", tg.path(".")) 881 tg.cd(tg.path("./src")) 882 tg.run("list", "-tags=thetag", "./my...") 883 tg.grepStdout("mypkg", "did not find mypkg") 884 } 885 886 func TestGoInstallErrorOnCrossCompileToBin(t *testing.T) { 887 if testing.Short() { 888 t.Skip("don't install into GOROOT in short mode") 889 } 890 891 tg := testgo(t) 892 defer tg.cleanup() 893 tg.tempFile("src/mycmd/x.go", `package main 894 func main() {}`) 895 tg.setenv("GOPATH", tg.path(".")) 896 tg.cd(tg.path("src/mycmd")) 897 898 tg.run("build", "mycmd") 899 900 goarch := "386" 901 if runtime.GOARCH == "386" { 902 goarch = "amd64" 903 } 904 tg.setenv("GOOS", "linux") 905 tg.setenv("GOARCH", goarch) 906 tg.run("install", "mycmd") 907 tg.setenv("GOBIN", tg.path(".")) 908 tg.runFail("install", "mycmd") 909 tg.run("install", "cmd/pack") 910 } 911 912 func TestGoInstallDetectsRemovedFilesInPackageMain(t *testing.T) { 913 tg := testgo(t) 914 defer tg.cleanup() 915 tg.parallel() 916 tg.tempFile("src/mycmd/x.go", `package main 917 func main() {}`) 918 tg.tempFile("src/mycmd/y.go", `package main`) 919 tg.tempFile("src/mycmd/z.go", `// +build missingtag 920 921 package main`) 922 tg.setenv("GOPATH", tg.path(".")) 923 tg.run("install", "mycmd") 924 tg.wantNotStale("mycmd", "", "./testgo list mypkg claims mycmd is stale, incorrectly") 925 // z.go was not part of the build; removing it is okay. 926 tg.must(os.Remove(tg.path("src/mycmd/z.go"))) 927 tg.wantNotStale("mycmd", "", "./testgo list mycmd claims mycmd is stale after removing z.go; should not be stale") 928 // y.go was part of the package; removing it should be detected. 929 tg.must(os.Remove(tg.path("src/mycmd/y.go"))) 930 tg.wantStale("mycmd", "build ID mismatch", "./testgo list mycmd claims mycmd is NOT stale after removing y.go; should be stale") 931 } 932 933 func testLocalRun(tg *testgoData, exepath, local, match string) { 934 out, err := exec.Command(exepath).Output() 935 if err != nil { 936 tg.t.Fatalf("error running %v: %v", exepath, err) 937 } 938 if !regexp.MustCompile(match).Match(out) { 939 tg.t.Log(string(out)) 940 tg.t.Errorf("testdata/%s/easy.go did not generate expected output", local) 941 } 942 } 943 944 func testLocalEasy(tg *testgoData, local string) { 945 exepath := "./easy" + exeSuffix 946 tg.creatingTemp(exepath) 947 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easy.go")) 948 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`) 949 } 950 951 func testLocalEasySub(tg *testgoData, local string) { 952 exepath := "./easysub" + exeSuffix 953 tg.creatingTemp(exepath) 954 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "easysub", "main.go")) 955 testLocalRun(tg, exepath, local, `(?m)^easysub\.Hello`) 956 } 957 958 func testLocalHard(tg *testgoData, local string) { 959 exepath := "./hard" + exeSuffix 960 tg.creatingTemp(exepath) 961 tg.run("build", "-o", exepath, filepath.Join("testdata", local, "hard.go")) 962 testLocalRun(tg, exepath, local, `(?m)^sub\.Hello`) 963 } 964 965 func testLocalInstall(tg *testgoData, local string) { 966 tg.runFail("install", filepath.Join("testdata", local, "easy.go")) 967 } 968 969 func TestLocalImportsEasy(t *testing.T) { 970 tg := testgo(t) 971 defer tg.cleanup() 972 testLocalEasy(tg, "local") 973 } 974 975 func TestLocalImportsEasySub(t *testing.T) { 976 tg := testgo(t) 977 defer tg.cleanup() 978 testLocalEasySub(tg, "local") 979 } 980 981 func TestLocalImportsHard(t *testing.T) { 982 tg := testgo(t) 983 defer tg.cleanup() 984 testLocalHard(tg, "local") 985 } 986 987 func TestLocalImportsGoInstallShouldFail(t *testing.T) { 988 tg := testgo(t) 989 defer tg.cleanup() 990 testLocalInstall(tg, "local") 991 } 992 993 const badDirName = `#$%:, &()*;<=>?\^{}` 994 995 func copyBad(tg *testgoData) { 996 if runtime.GOOS == "windows" { 997 tg.t.Skipf("skipping test because %q is an invalid directory name", badDirName) 998 } 999 1000 tg.must(filepath.Walk("testdata/local", 1001 func(path string, info os.FileInfo, err error) error { 1002 if err != nil { 1003 return err 1004 } 1005 if info.IsDir() { 1006 return nil 1007 } 1008 var data []byte 1009 data, err = ioutil.ReadFile(path) 1010 if err != nil { 1011 return err 1012 } 1013 newpath := strings.Replace(path, "local", badDirName, 1) 1014 tg.tempFile(newpath, string(data)) 1015 return nil 1016 })) 1017 tg.cd(tg.path(".")) 1018 } 1019 1020 func TestBadImportsEasy(t *testing.T) { 1021 tg := testgo(t) 1022 defer tg.cleanup() 1023 copyBad(tg) 1024 testLocalEasy(tg, badDirName) 1025 } 1026 1027 func TestBadImportsEasySub(t *testing.T) { 1028 tg := testgo(t) 1029 defer tg.cleanup() 1030 copyBad(tg) 1031 testLocalEasySub(tg, badDirName) 1032 } 1033 1034 func TestBadImportsHard(t *testing.T) { 1035 tg := testgo(t) 1036 defer tg.cleanup() 1037 copyBad(tg) 1038 testLocalHard(tg, badDirName) 1039 } 1040 1041 func TestBadImportsGoInstallShouldFail(t *testing.T) { 1042 tg := testgo(t) 1043 defer tg.cleanup() 1044 copyBad(tg) 1045 testLocalInstall(tg, badDirName) 1046 } 1047 1048 func TestInternalPackagesInGOROOTAreRespected(t *testing.T) { 1049 tg := testgo(t) 1050 defer tg.cleanup() 1051 tg.runFail("build", "-v", "./testdata/testinternal") 1052 tg.grepBoth("use of internal package not allowed", "wrong error message for testdata/testinternal") 1053 } 1054 1055 func TestInternalPackagesOutsideGOROOTAreRespected(t *testing.T) { 1056 tg := testgo(t) 1057 defer tg.cleanup() 1058 tg.runFail("build", "-v", "./testdata/testinternal2") 1059 tg.grepBoth("use of internal package not allowed", "wrote error message for testdata/testinternal2") 1060 } 1061 1062 func TestRunInternal(t *testing.T) { 1063 tg := testgo(t) 1064 defer tg.cleanup() 1065 dir := filepath.Join(tg.pwd(), "testdata") 1066 tg.setenv("GOPATH", dir) 1067 tg.run("run", filepath.Join(dir, "src/run/good.go")) 1068 tg.runFail("run", filepath.Join(dir, "src/run/bad.go")) 1069 tg.grepStderr("use of internal package not allowed", "unexpected error for run/bad.go") 1070 } 1071 1072 func testMove(t *testing.T, vcs, url, base, config string) { 1073 testenv.MustHaveExternalNetwork(t) 1074 1075 tg := testgo(t) 1076 defer tg.cleanup() 1077 tg.parallel() 1078 tg.tempDir("src") 1079 tg.setenv("GOPATH", tg.path(".")) 1080 tg.run("get", "-d", url) 1081 tg.run("get", "-d", "-u", url) 1082 switch vcs { 1083 case "svn": 1084 // SVN doesn't believe in text files so we can't just edit the config. 1085 // Check out a different repo into the wrong place. 1086 tg.must(os.RemoveAll(tg.path("src/code.google.com/p/rsc-svn"))) 1087 tg.run("get", "-d", "-u", "code.google.com/p/rsc-svn2/trunk") 1088 tg.must(os.Rename(tg.path("src/code.google.com/p/rsc-svn2"), tg.path("src/code.google.com/p/rsc-svn"))) 1089 default: 1090 path := tg.path(filepath.Join("src", config)) 1091 data, err := ioutil.ReadFile(path) 1092 tg.must(err) 1093 data = bytes.Replace(data, []byte(base), []byte(base+"XXX"), -1) 1094 tg.must(ioutil.WriteFile(path, data, 0644)) 1095 } 1096 if vcs == "git" { 1097 // git will ask for a username and password when we 1098 // run go get -d -f -u. An empty username and 1099 // password will work. Prevent asking by setting 1100 // GIT_ASKPASS. 1101 tg.creatingTemp("sink" + exeSuffix) 1102 tg.tempFile("src/sink/sink.go", `package main; func main() {}`) 1103 tg.run("build", "-o", "sink"+exeSuffix, "sink") 1104 tg.setenv("GIT_ASKPASS", filepath.Join(tg.pwd(), "sink"+exeSuffix)) 1105 } 1106 tg.runFail("get", "-d", "-u", url) 1107 tg.grepStderr("is a custom import path for", "go get -d -u "+url+" failed for wrong reason") 1108 tg.runFail("get", "-d", "-f", "-u", url) 1109 tg.grepStderr("validating server certificate|not found", "go get -d -f -u "+url+" failed for wrong reason") 1110 } 1111 1112 func TestInternalPackageErrorsAreHandled(t *testing.T) { 1113 tg := testgo(t) 1114 defer tg.cleanup() 1115 tg.run("list", "./testdata/testinternal3") 1116 } 1117 1118 func TestInternalCache(t *testing.T) { 1119 tg := testgo(t) 1120 defer tg.cleanup() 1121 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/testinternal4")) 1122 tg.runFail("build", "p") 1123 tg.grepStderr("internal", "did not fail to build p") 1124 } 1125 1126 func TestMoveGit(t *testing.T) { 1127 testMove(t, "git", "rsc.io/pdf", "pdf", "rsc.io/pdf/.git/config") 1128 } 1129 1130 // TODO(rsc): Set up a test case on bitbucket for hg. 1131 // func TestMoveHG(t *testing.T) { 1132 // testMove(t, "hg", "rsc.io/x86/x86asm", "x86", "rsc.io/x86/.hg/hgrc") 1133 // } 1134 1135 // TODO(rsc): Set up a test case on SourceForge (?) for svn. 1136 // func testMoveSVN(t *testing.T) { 1137 // testMove(t, "svn", "code.google.com/p/rsc-svn/trunk", "-", "-") 1138 // } 1139 1140 func TestImportCommandMatch(t *testing.T) { 1141 tg := testgo(t) 1142 defer tg.cleanup() 1143 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom")) 1144 tg.run("build", "./testdata/importcom/works.go") 1145 } 1146 1147 func TestImportCommentMismatch(t *testing.T) { 1148 tg := testgo(t) 1149 defer tg.cleanup() 1150 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom")) 1151 tg.runFail("build", "./testdata/importcom/wrongplace.go") 1152 tg.grepStderr(`wrongplace expects import "my/x"`, "go build did not mention incorrect import") 1153 } 1154 1155 func TestImportCommentSyntaxError(t *testing.T) { 1156 tg := testgo(t) 1157 defer tg.cleanup() 1158 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom")) 1159 tg.runFail("build", "./testdata/importcom/bad.go") 1160 tg.grepStderr("cannot parse import comment", "go build did not mention syntax error") 1161 } 1162 1163 func TestImportCommentConflict(t *testing.T) { 1164 tg := testgo(t) 1165 defer tg.cleanup() 1166 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/importcom")) 1167 tg.runFail("build", "./testdata/importcom/conflict.go") 1168 tg.grepStderr("found import comments", "go build did not mention comment conflict") 1169 } 1170 1171 // cmd/go: custom import path checking should not apply to Go packages without import comment. 1172 func TestIssue10952(t *testing.T) { 1173 testenv.MustHaveExternalNetwork(t) 1174 if _, err := exec.LookPath("git"); err != nil { 1175 t.Skip("skipping because git binary not found") 1176 } 1177 1178 tg := testgo(t) 1179 defer tg.cleanup() 1180 tg.parallel() 1181 tg.tempDir("src") 1182 tg.setenv("GOPATH", tg.path(".")) 1183 const importPath = "github.com/zombiezen/go-get-issue-10952" 1184 tg.run("get", "-d", "-u", importPath) 1185 repoDir := tg.path("src/" + importPath) 1186 tg.runGit(repoDir, "remote", "set-url", "origin", "https://"+importPath+".git") 1187 tg.run("get", "-d", "-u", importPath) 1188 } 1189 1190 func TestIssue16471(t *testing.T) { 1191 testenv.MustHaveExternalNetwork(t) 1192 if _, err := exec.LookPath("git"); err != nil { 1193 t.Skip("skipping because git binary not found") 1194 } 1195 1196 tg := testgo(t) 1197 defer tg.cleanup() 1198 tg.parallel() 1199 tg.tempDir("src") 1200 tg.setenv("GOPATH", tg.path(".")) 1201 tg.must(os.MkdirAll(tg.path("src/rsc.io/go-get-issue-10952"), 0755)) 1202 tg.runGit(tg.path("src/rsc.io"), "clone", "https://github.com/zombiezen/go-get-issue-10952") 1203 tg.runFail("get", "-u", "rsc.io/go-get-issue-10952") 1204 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") 1205 } 1206 1207 // Test git clone URL that uses SCP-like syntax and custom import path checking. 1208 func TestIssue11457(t *testing.T) { 1209 testenv.MustHaveExternalNetwork(t) 1210 if _, err := exec.LookPath("git"); err != nil { 1211 t.Skip("skipping because git binary not found") 1212 } 1213 1214 tg := testgo(t) 1215 defer tg.cleanup() 1216 tg.parallel() 1217 tg.tempDir("src") 1218 tg.setenv("GOPATH", tg.path(".")) 1219 const importPath = "github.com/rsc/go-get-issue-11457" 1220 tg.run("get", "-d", "-u", importPath) 1221 repoDir := tg.path("src/" + importPath) 1222 tg.runGit(repoDir, "remote", "set-url", "origin", "git@github.com:rsc/go-get-issue-11457") 1223 1224 // At this time, custom import path checking compares remotes verbatim (rather than 1225 // just the host and path, skipping scheme and user), so we expect go get -u to fail. 1226 // However, the goal of this test is to verify that gitRemoteRepo correctly parsed 1227 // the SCP-like syntax, and we expect it to appear in the error message. 1228 tg.runFail("get", "-d", "-u", importPath) 1229 want := " is checked out from ssh://git@github.com/rsc/go-get-issue-11457" 1230 if !strings.HasSuffix(strings.TrimSpace(tg.getStderr()), want) { 1231 t.Error("expected clone URL to appear in stderr") 1232 } 1233 } 1234 1235 func TestGetGitDefaultBranch(t *testing.T) { 1236 testenv.MustHaveExternalNetwork(t) 1237 if _, err := exec.LookPath("git"); err != nil { 1238 t.Skip("skipping because git binary not found") 1239 } 1240 1241 tg := testgo(t) 1242 defer tg.cleanup() 1243 tg.parallel() 1244 tg.tempDir("src") 1245 tg.setenv("GOPATH", tg.path(".")) 1246 1247 // This repo has two branches, master and another-branch. 1248 // The another-branch is the default that you get from 'git clone'. 1249 // The go get command variants should not override this. 1250 const importPath = "github.com/rsc/go-get-default-branch" 1251 1252 tg.run("get", "-d", importPath) 1253 repoDir := tg.path("src/" + importPath) 1254 tg.runGit(repoDir, "branch", "--contains", "HEAD") 1255 tg.grepStdout(`\* another-branch`, "not on correct default branch") 1256 1257 tg.run("get", "-d", "-u", importPath) 1258 tg.runGit(repoDir, "branch", "--contains", "HEAD") 1259 tg.grepStdout(`\* another-branch`, "not on correct default branch") 1260 } 1261 1262 func TestErrorMessageForSyntaxErrorInTestGoFileSaysFAIL(t *testing.T) { 1263 tg := testgo(t) 1264 defer tg.cleanup() 1265 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1266 tg.runFail("test", "syntaxerror") 1267 tg.grepStderr("FAIL", "go test did not say FAIL") 1268 } 1269 1270 func TestWildcardsDoNotLookInUselessDirectories(t *testing.T) { 1271 tg := testgo(t) 1272 defer tg.cleanup() 1273 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1274 tg.runFail("list", "...") 1275 tg.grepBoth("badpkg", "go list ... failure does not mention badpkg") 1276 tg.run("list", "m...") 1277 } 1278 1279 func TestRelativeImportsGoTest(t *testing.T) { 1280 tg := testgo(t) 1281 defer tg.cleanup() 1282 tg.run("test", "./testdata/testimport") 1283 } 1284 1285 func TestRelativeImportsGoTestDashI(t *testing.T) { 1286 tg := testgo(t) 1287 defer tg.cleanup() 1288 tg.run("test", "-i", "./testdata/testimport") 1289 } 1290 1291 func TestRelativeImportsInCommandLinePackage(t *testing.T) { 1292 tg := testgo(t) 1293 defer tg.cleanup() 1294 files, err := filepath.Glob("./testdata/testimport/*.go") 1295 tg.must(err) 1296 tg.run(append([]string{"test"}, files...)...) 1297 } 1298 1299 func TestNonCanonicalImportPaths(t *testing.T) { 1300 tg := testgo(t) 1301 defer tg.cleanup() 1302 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1303 tg.runFail("build", "canonical/d") 1304 tg.grepStderr("package canonical/d", "did not report canonical/d") 1305 tg.grepStderr("imports canonical/b", "did not report canonical/b") 1306 tg.grepStderr("imports canonical/a/: non-canonical", "did not report canonical/a/") 1307 } 1308 1309 func TestVersionControlErrorMessageIncludesCorrectDirectory(t *testing.T) { 1310 tg := testgo(t) 1311 defer tg.cleanup() 1312 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata/shadow/root1")) 1313 tg.runFail("get", "-u", "foo") 1314 1315 // TODO(iant): We should not have to use strconv.Quote here. 1316 // The code in vcs.go should be changed so that it is not required. 1317 quoted := strconv.Quote(filepath.Join("testdata", "shadow", "root1", "src", "foo")) 1318 quoted = quoted[1 : len(quoted)-1] 1319 1320 tg.grepStderr(regexp.QuoteMeta(quoted), "go get -u error does not mention shadow/root1/src/foo") 1321 } 1322 1323 func TestInstallFailsWithNoBuildableFiles(t *testing.T) { 1324 tg := testgo(t) 1325 defer tg.cleanup() 1326 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1327 tg.setenv("CGO_ENABLED", "0") 1328 tg.runFail("install", "cgotest") 1329 tg.grepStderr("no buildable Go source files", "go install cgotest did not report 'no buildable Go Source files'") 1330 } 1331 1332 func TestRelativeGOBINFail(t *testing.T) { 1333 tg := testgo(t) 1334 defer tg.cleanup() 1335 tg.tempFile("triv.go", `package main; func main() {}`) 1336 tg.setenv("GOBIN", ".") 1337 tg.runFail("install") 1338 tg.grepStderr("cannot install, GOBIN must be an absolute path", "go install must fail if $GOBIN is a relative path") 1339 } 1340 1341 // Test that without $GOBIN set, binaries get installed 1342 // into the GOPATH bin directory. 1343 func TestInstallIntoGOPATH(t *testing.T) { 1344 tg := testgo(t) 1345 defer tg.cleanup() 1346 tg.creatingTemp("testdata/bin/go-cmd-test" + exeSuffix) 1347 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1348 tg.run("install", "go-cmd-test") 1349 tg.wantExecutable("testdata/bin/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin/go-cmd-test") 1350 } 1351 1352 // Issue 12407 1353 func TestBuildOutputToDevNull(t *testing.T) { 1354 tg := testgo(t) 1355 defer tg.cleanup() 1356 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1357 tg.run("build", "-o", os.DevNull, "go-cmd-test") 1358 } 1359 1360 func TestPackageMainTestImportsArchiveNotBinary(t *testing.T) { 1361 tg := testgo(t) 1362 defer tg.cleanup() 1363 tg.parallel() 1364 gobin := filepath.Join(tg.pwd(), "testdata", "bin") 1365 tg.creatingTemp(gobin) 1366 tg.setenv("GOBIN", gobin) 1367 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1368 tg.must(os.Chtimes("./testdata/src/main_test/m.go", time.Now(), time.Now())) 1369 tg.sleep() 1370 tg.run("test", "main_test") 1371 tg.run("install", "main_test") 1372 tg.wantNotStale("main_test", "", "after go install, main listed as stale") 1373 tg.run("test", "main_test") 1374 } 1375 1376 // The runtime version string takes one of two forms: 1377 // "go1.X[.Y]" for Go releases, and "devel +hash" at tip. 1378 // Determine whether we are in a released copy by 1379 // inspecting the version. 1380 var isGoRelease = strings.HasPrefix(runtime.Version(), "go1") 1381 1382 // Issue 12690 1383 func TestPackageNotStaleWithTrailingSlash(t *testing.T) { 1384 tg := testgo(t) 1385 defer tg.cleanup() 1386 1387 // Make sure the packages below are not stale. 1388 tg.run("install", "runtime", "os", "io") 1389 1390 goroot := runtime.GOROOT() 1391 tg.setenv("GOROOT", goroot+"/") 1392 1393 want := "" 1394 if isGoRelease { 1395 want = "standard package in Go release distribution" 1396 } 1397 1398 tg.wantNotStale("runtime", want, "with trailing slash in GOROOT, runtime listed as stale") 1399 tg.wantNotStale("os", want, "with trailing slash in GOROOT, os listed as stale") 1400 tg.wantNotStale("io", want, "with trailing slash in GOROOT, io listed as stale") 1401 } 1402 1403 // With $GOBIN set, binaries get installed to $GOBIN. 1404 func TestInstallIntoGOBIN(t *testing.T) { 1405 tg := testgo(t) 1406 defer tg.cleanup() 1407 gobin := filepath.Join(tg.pwd(), "testdata", "bin1") 1408 tg.creatingTemp(gobin) 1409 tg.setenv("GOBIN", gobin) 1410 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1411 tg.run("install", "go-cmd-test") 1412 tg.wantExecutable("testdata/bin1/go-cmd-test"+exeSuffix, "go install go-cmd-test did not write to testdata/bin1/go-cmd-test") 1413 } 1414 1415 // Issue 11065 1416 func TestInstallToCurrentDirectoryCreatesExecutable(t *testing.T) { 1417 tg := testgo(t) 1418 defer tg.cleanup() 1419 pkg := filepath.Join(tg.pwd(), "testdata", "src", "go-cmd-test") 1420 tg.creatingTemp(filepath.Join(pkg, "go-cmd-test"+exeSuffix)) 1421 tg.setenv("GOBIN", pkg) 1422 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1423 tg.cd(pkg) 1424 tg.run("install") 1425 tg.wantExecutable("go-cmd-test"+exeSuffix, "go install did not write to current directory") 1426 } 1427 1428 // Without $GOBIN set, installing a program outside $GOPATH should fail 1429 // (there is nowhere to install it). 1430 func TestInstallWithoutDestinationFails(t *testing.T) { 1431 tg := testgo(t) 1432 defer tg.cleanup() 1433 tg.runFail("install", "testdata/src/go-cmd-test/helloworld.go") 1434 tg.grepStderr("no install location for .go files listed on command line", "wrong error") 1435 } 1436 1437 // With $GOBIN set, should install there. 1438 func TestInstallToGOBINCommandLinePackage(t *testing.T) { 1439 tg := testgo(t) 1440 defer tg.cleanup() 1441 gobin := filepath.Join(tg.pwd(), "testdata", "bin1") 1442 tg.creatingTemp(gobin) 1443 tg.setenv("GOBIN", gobin) 1444 tg.run("install", "testdata/src/go-cmd-test/helloworld.go") 1445 tg.wantExecutable("testdata/bin1/helloworld"+exeSuffix, "go install testdata/src/go-cmd-test/helloworld.go did not write testdata/bin1/helloworld") 1446 } 1447 1448 func TestGoGetNonPkg(t *testing.T) { 1449 testenv.MustHaveExternalNetwork(t) 1450 1451 tg := testgo(t) 1452 defer tg.cleanup() 1453 tg.tempDir("gobin") 1454 tg.setenv("GOPATH", tg.path(".")) 1455 tg.setenv("GOBIN", tg.path("gobin")) 1456 tg.runFail("get", "-d", "golang.org/x/tools") 1457 tg.grepStderr("golang.org/x/tools: no buildable Go source files", "missing error") 1458 tg.runFail("get", "-d", "-u", "golang.org/x/tools") 1459 tg.grepStderr("golang.org/x/tools: no buildable Go source files", "missing error") 1460 tg.runFail("get", "-d", "golang.org/x/tools") 1461 tg.grepStderr("golang.org/x/tools: no buildable Go source files", "missing error") 1462 } 1463 1464 func TestGoGetTestOnlyPkg(t *testing.T) { 1465 testenv.MustHaveExternalNetwork(t) 1466 1467 tg := testgo(t) 1468 defer tg.cleanup() 1469 tg.tempDir("gopath") 1470 tg.setenv("GOPATH", tg.path("gopath")) 1471 tg.run("get", "golang.org/x/tour/content") 1472 tg.run("get", "-t", "golang.org/x/tour/content") 1473 } 1474 1475 func TestInstalls(t *testing.T) { 1476 if testing.Short() { 1477 t.Skip("don't install into GOROOT in short mode") 1478 } 1479 1480 tg := testgo(t) 1481 defer tg.cleanup() 1482 tg.parallel() 1483 tg.tempDir("gobin") 1484 tg.setenv("GOPATH", tg.path(".")) 1485 goroot := runtime.GOROOT() 1486 tg.setenv("GOROOT", goroot) 1487 1488 // cmd/fix installs into tool 1489 tg.run("env", "GOOS") 1490 goos := strings.TrimSpace(tg.getStdout()) 1491 tg.setenv("GOOS", goos) 1492 tg.run("env", "GOARCH") 1493 goarch := strings.TrimSpace(tg.getStdout()) 1494 tg.setenv("GOARCH", goarch) 1495 fixbin := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch, "fix") + exeSuffix 1496 tg.must(os.RemoveAll(fixbin)) 1497 tg.run("install", "cmd/fix") 1498 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool") 1499 tg.must(os.Remove(fixbin)) 1500 tg.setenv("GOBIN", tg.path("gobin")) 1501 tg.run("install", "cmd/fix") 1502 tg.wantExecutable(fixbin, "did not install cmd/fix to $GOROOT/pkg/tool with $GOBIN set") 1503 tg.unsetenv("GOBIN") 1504 1505 // gopath program installs into GOBIN 1506 tg.tempFile("src/progname/p.go", `package main; func main() {}`) 1507 tg.setenv("GOBIN", tg.path("gobin")) 1508 tg.run("install", "progname") 1509 tg.unsetenv("GOBIN") 1510 tg.wantExecutable(tg.path("gobin/progname")+exeSuffix, "did not install progname to $GOBIN/progname") 1511 1512 // gopath program installs into GOPATH/bin 1513 tg.run("install", "progname") 1514 tg.wantExecutable(tg.path("bin/progname")+exeSuffix, "did not install progname to $GOPATH/bin/progname") 1515 } 1516 1517 func TestRejectRelativeDotPathInGOPATHCommandLinePackage(t *testing.T) { 1518 tg := testgo(t) 1519 defer tg.cleanup() 1520 tg.setenv("GOPATH", ".") 1521 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go") 1522 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries") 1523 } 1524 1525 func TestRejectRelativePathsInGOPATH(t *testing.T) { 1526 tg := testgo(t) 1527 defer tg.cleanup() 1528 sep := string(filepath.ListSeparator) 1529 tg.setenv("GOPATH", sep+filepath.Join(tg.pwd(), "testdata")+sep+".") 1530 tg.runFail("build", "go-cmd-test") 1531 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries") 1532 } 1533 1534 func TestRejectRelativePathsInGOPATHCommandLinePackage(t *testing.T) { 1535 tg := testgo(t) 1536 defer tg.cleanup() 1537 tg.setenv("GOPATH", "testdata") 1538 tg.runFail("build", "testdata/src/go-cmd-test/helloworld.go") 1539 tg.grepStderr("GOPATH entry is relative", "expected an error message rejecting relative GOPATH entries") 1540 } 1541 1542 // Issue 4104. 1543 func TestGoTestWithPackageListedMultipleTimes(t *testing.T) { 1544 tg := testgo(t) 1545 defer tg.cleanup() 1546 tg.parallel() 1547 tg.run("test", "errors", "errors", "errors", "errors", "errors") 1548 if strings.Contains(strings.TrimSpace(tg.getStdout()), "\n") { 1549 t.Error("go test errors errors errors errors errors tested the same package multiple times") 1550 } 1551 } 1552 1553 func TestGoListHasAConsistentOrder(t *testing.T) { 1554 tg := testgo(t) 1555 defer tg.cleanup() 1556 tg.run("list", "std") 1557 first := tg.getStdout() 1558 tg.run("list", "std") 1559 if first != tg.getStdout() { 1560 t.Error("go list std ordering is inconsistent") 1561 } 1562 } 1563 1564 func TestGoListStdDoesNotIncludeCommands(t *testing.T) { 1565 tg := testgo(t) 1566 defer tg.cleanup() 1567 tg.run("list", "std") 1568 tg.grepStdoutNot("cmd/", "go list std shows commands") 1569 } 1570 1571 func TestGoListCmdOnlyShowsCommands(t *testing.T) { 1572 tg := testgo(t) 1573 defer tg.cleanup() 1574 tg.run("list", "cmd") 1575 out := strings.TrimSpace(tg.getStdout()) 1576 for _, line := range strings.Split(out, "\n") { 1577 if !strings.Contains(line, "cmd/") { 1578 t.Error("go list cmd shows non-commands") 1579 break 1580 } 1581 } 1582 } 1583 1584 func TestGoListDedupsPackages(t *testing.T) { 1585 tg := testgo(t) 1586 defer tg.cleanup() 1587 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 1588 tg.run("list", "xtestonly", "./testdata/src/xtestonly/...") 1589 got := strings.TrimSpace(tg.getStdout()) 1590 const want = "xtestonly" 1591 if got != want { 1592 t.Errorf("got %q; want %q", got, want) 1593 } 1594 } 1595 1596 // Issue 4096. Validate the output of unsuccessful go install foo/quxx. 1597 func TestUnsuccessfulGoInstallShouldMentionMissingPackage(t *testing.T) { 1598 tg := testgo(t) 1599 defer tg.cleanup() 1600 tg.runFail("install", "foo/quxx") 1601 if tg.grepCountBoth(`cannot find package "foo/quxx" in any of`) != 1 { 1602 t.Error(`go install foo/quxx expected error: .*cannot find package "foo/quxx" in any of`) 1603 } 1604 } 1605 1606 func TestGOROOTSearchFailureReporting(t *testing.T) { 1607 tg := testgo(t) 1608 defer tg.cleanup() 1609 tg.runFail("install", "foo/quxx") 1610 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("foo", "quxx"))+` \(from \$GOROOT\)$`) != 1 { 1611 t.Error(`go install foo/quxx expected error: .*foo/quxx (from $GOROOT)`) 1612 } 1613 } 1614 1615 func TestMultipleGOPATHEntriesReportedSeparately(t *testing.T) { 1616 tg := testgo(t) 1617 defer tg.cleanup() 1618 sep := string(filepath.ListSeparator) 1619 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b")) 1620 tg.runFail("install", "foo/quxx") 1621 if tg.grepCountBoth(`testdata[/\\].[/\\]src[/\\]foo[/\\]quxx`) != 2 { 1622 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)\n.*testdata/b/src/foo/quxx`) 1623 } 1624 } 1625 1626 // Test (from $GOPATH) annotation is reported for the first GOPATH entry, 1627 func TestMentionGOPATHInFirstGOPATHEntry(t *testing.T) { 1628 tg := testgo(t) 1629 defer tg.cleanup() 1630 sep := string(filepath.ListSeparator) 1631 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b")) 1632 tg.runFail("install", "foo/quxx") 1633 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "a", "src", "foo", "quxx"))+` \(from \$GOPATH\)$`) != 1 { 1634 t.Error(`go install foo/quxx expected error: .*testdata/a/src/foo/quxx (from $GOPATH)`) 1635 } 1636 } 1637 1638 // but not on the second. 1639 func TestMentionGOPATHNotOnSecondEntry(t *testing.T) { 1640 tg := testgo(t) 1641 defer tg.cleanup() 1642 sep := string(filepath.ListSeparator) 1643 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata", "a")+sep+filepath.Join(tg.pwd(), "testdata", "b")) 1644 tg.runFail("install", "foo/quxx") 1645 if tg.grepCountBoth(regexp.QuoteMeta(filepath.Join("testdata", "b", "src", "foo", "quxx"))+`$`) != 1 { 1646 t.Error(`go install foo/quxx expected error: .*testdata/b/src/foo/quxx`) 1647 } 1648 } 1649 1650 // Test missing GOPATH is reported. 1651 func TestMissingGOPATHIsReported(t *testing.T) { 1652 tg := testgo(t) 1653 defer tg.cleanup() 1654 tg.setenv("GOPATH", "") 1655 tg.runFail("install", "foo/quxx") 1656 if tg.grepCountBoth(`\(\$GOPATH not set\. For more details see: 'go help gopath'\)$`) != 1 { 1657 t.Error(`go install foo/quxx expected error: ($GOPATH not set. For more details see: 'go help gopath')`) 1658 } 1659 } 1660 1661 // Issue 4186. go get cannot be used to download packages to $GOROOT. 1662 // Test that without GOPATH set, go get should fail. 1663 func TestWithoutGOPATHGoGetFails(t *testing.T) { 1664 testenv.MustHaveExternalNetwork(t) 1665 1666 tg := testgo(t) 1667 defer tg.cleanup() 1668 tg.parallel() 1669 tg.tempDir("src") 1670 tg.setenv("GOPATH", "") 1671 tg.setenv("GOROOT", tg.path(".")) 1672 tg.runFail("get", "-d", "golang.org/x/codereview/cmd/hgpatch") 1673 } 1674 1675 // Test that with GOPATH=$GOROOT, go get should fail. 1676 func TestWithGOPATHEqualsGOROOTGoGetFails(t *testing.T) { 1677 testenv.MustHaveExternalNetwork(t) 1678 1679 tg := testgo(t) 1680 defer tg.cleanup() 1681 tg.parallel() 1682 tg.tempDir("src") 1683 tg.setenv("GOPATH", tg.path(".")) 1684 tg.setenv("GOROOT", tg.path(".")) 1685 tg.runFail("get", "-d", "golang.org/x/codereview/cmd/hgpatch") 1686 } 1687 1688 func TestLdflagsArgumentsWithSpacesIssue3941(t *testing.T) { 1689 tg := testgo(t) 1690 defer tg.cleanup() 1691 tg.parallel() 1692 tg.tempFile("main.go", `package main 1693 var extern string 1694 func main() { 1695 println(extern) 1696 }`) 1697 tg.run("run", "-ldflags", `-X "main.extern=hello world"`, tg.path("main.go")) 1698 tg.grepStderr("^hello world", `ldflags -X "main.extern=hello world"' failed`) 1699 } 1700 1701 func TestGoTestCpuprofileLeavesBinaryBehind(t *testing.T) { 1702 tg := testgo(t) 1703 defer tg.cleanup() 1704 tg.makeTempdir() 1705 tg.cd(tg.path(".")) 1706 tg.run("test", "-cpuprofile", "errors.prof", "errors") 1707 tg.wantExecutable("errors.test"+exeSuffix, "go test -cpuprofile did not create errors.test") 1708 } 1709 1710 func TestGoTestCpuprofileDashOControlsBinaryLocation(t *testing.T) { 1711 tg := testgo(t) 1712 defer tg.cleanup() 1713 tg.makeTempdir() 1714 tg.cd(tg.path(".")) 1715 tg.run("test", "-cpuprofile", "errors.prof", "-o", "myerrors.test"+exeSuffix, "errors") 1716 tg.wantExecutable("myerrors.test"+exeSuffix, "go test -cpuprofile -o myerrors.test did not create myerrors.test") 1717 } 1718 1719 func TestGoTestDashCDashOControlsBinaryLocation(t *testing.T) { 1720 tg := testgo(t) 1721 defer tg.cleanup() 1722 tg.parallel() 1723 tg.makeTempdir() 1724 tg.run("test", "-c", "-o", tg.path("myerrors.test"+exeSuffix), "errors") 1725 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -c -o myerrors.test did not create myerrors.test") 1726 } 1727 1728 func TestGoTestDashOWritesBinary(t *testing.T) { 1729 tg := testgo(t) 1730 defer tg.cleanup() 1731 tg.parallel() 1732 tg.makeTempdir() 1733 tg.run("test", "-o", tg.path("myerrors.test"+exeSuffix), "errors") 1734 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test") 1735 } 1736 1737 func TestGoTestDashIDashOWritesBinary(t *testing.T) { 1738 tg := testgo(t) 1739 defer tg.cleanup() 1740 tg.parallel() 1741 tg.makeTempdir() 1742 tg.run("test", "-v", "-i", "-o", tg.path("myerrors.test"+exeSuffix), "errors") 1743 tg.grepBothNot("PASS|FAIL", "test should not have run") 1744 tg.wantExecutable(tg.path("myerrors.test"+exeSuffix), "go test -o myerrors.test did not create myerrors.test") 1745 } 1746 1747 // Issue 4568. 1748 func TestSymlinksList(t *testing.T) { 1749 switch runtime.GOOS { 1750 case "plan9", "windows": 1751 t.Skipf("skipping symlink test on %s", runtime.GOOS) 1752 } 1753 1754 tg := testgo(t) 1755 defer tg.cleanup() 1756 tg.tempDir("src") 1757 tg.must(os.Symlink(tg.path("."), tg.path("src/dir1"))) 1758 tg.tempFile("src/dir1/p.go", "package p") 1759 tg.setenv("GOPATH", tg.path(".")) 1760 tg.cd(tg.path("src")) 1761 tg.run("list", "-f", "{{.Root}}", "dir1") 1762 if strings.TrimSpace(tg.getStdout()) != tg.path(".") { 1763 t.Error("confused by symlinks") 1764 } 1765 } 1766 1767 // Issue 14054. 1768 func TestSymlinksVendor(t *testing.T) { 1769 switch runtime.GOOS { 1770 case "plan9", "windows": 1771 t.Skipf("skipping symlink test on %s", runtime.GOOS) 1772 } 1773 1774 tg := testgo(t) 1775 defer tg.cleanup() 1776 tg.tempDir("gopath/src/dir1/vendor/v") 1777 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `v`\nfunc main(){}") 1778 tg.tempFile("gopath/src/dir1/vendor/v/v.go", "package v") 1779 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1"))) 1780 tg.setenv("GOPATH", tg.path("gopath")) 1781 tg.cd(tg.path("symdir1")) 1782 tg.run("list", "-f", "{{.Root}}", ".") 1783 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") { 1784 t.Error("list confused by symlinks") 1785 } 1786 1787 // All of these should succeed, not die in vendor-handling code. 1788 tg.run("run", "p.go") 1789 tg.run("build") 1790 tg.run("install") 1791 } 1792 1793 // Issue 15201. 1794 func TestSymlinksVendor15201(t *testing.T) { 1795 switch runtime.GOOS { 1796 case "plan9", "windows": 1797 t.Skipf("skipping symlink test on %s", runtime.GOOS) 1798 } 1799 1800 tg := testgo(t) 1801 defer tg.cleanup() 1802 1803 tg.tempDir("gopath/src/x/y/_vendor/src/x") 1804 tg.must(os.Symlink("../../..", tg.path("gopath/src/x/y/_vendor/src/x/y"))) 1805 tg.tempFile("gopath/src/x/y/w/w.go", "package w\nimport \"x/y/z\"\n") 1806 tg.must(os.Symlink("../_vendor/src", tg.path("gopath/src/x/y/w/vendor"))) 1807 tg.tempFile("gopath/src/x/y/z/z.go", "package z\n") 1808 1809 tg.setenv("GOPATH", tg.path("gopath/src/x/y/_vendor")+string(filepath.ListSeparator)+tg.path("gopath")) 1810 tg.cd(tg.path("gopath/src")) 1811 tg.run("list", "./...") 1812 } 1813 1814 func TestSymlinksInternal(t *testing.T) { 1815 switch runtime.GOOS { 1816 case "plan9", "windows": 1817 t.Skipf("skipping symlink test on %s", runtime.GOOS) 1818 } 1819 1820 tg := testgo(t) 1821 defer tg.cleanup() 1822 tg.tempDir("gopath/src/dir1/internal/v") 1823 tg.tempFile("gopath/src/dir1/p.go", "package main\nimport _ `dir1/internal/v`\nfunc main(){}") 1824 tg.tempFile("gopath/src/dir1/internal/v/v.go", "package v") 1825 tg.must(os.Symlink(tg.path("gopath/src/dir1"), tg.path("symdir1"))) 1826 tg.setenv("GOPATH", tg.path("gopath")) 1827 tg.cd(tg.path("symdir1")) 1828 tg.run("list", "-f", "{{.Root}}", ".") 1829 if strings.TrimSpace(tg.getStdout()) != tg.path("gopath") { 1830 t.Error("list confused by symlinks") 1831 } 1832 1833 // All of these should succeed, not die in internal-handling code. 1834 tg.run("run", "p.go") 1835 tg.run("build") 1836 tg.run("install") 1837 } 1838 1839 // Issue 4515. 1840 func TestInstallWithTags(t *testing.T) { 1841 tg := testgo(t) 1842 defer tg.cleanup() 1843 tg.parallel() 1844 tg.tempDir("bin") 1845 tg.tempFile("src/example/a/main.go", `package main 1846 func main() {}`) 1847 tg.tempFile("src/example/b/main.go", `// +build mytag 1848 1849 package main 1850 func main() {}`) 1851 tg.setenv("GOPATH", tg.path(".")) 1852 tg.run("install", "-tags", "mytag", "example/a", "example/b") 1853 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/a example/b did not install binaries") 1854 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/a example/b did not install binaries") 1855 tg.must(os.Remove(tg.path("bin/a" + exeSuffix))) 1856 tg.must(os.Remove(tg.path("bin/b" + exeSuffix))) 1857 tg.run("install", "-tags", "mytag", "example/...") 1858 tg.wantExecutable(tg.path("bin/a"+exeSuffix), "go install example/... did not install binaries") 1859 tg.wantExecutable(tg.path("bin/b"+exeSuffix), "go install example/... did not install binaries") 1860 tg.run("list", "-tags", "mytag", "example/b...") 1861 if strings.TrimSpace(tg.getStdout()) != "example/b" { 1862 t.Error("go list example/b did not find example/b") 1863 } 1864 } 1865 1866 // Issue 4773 1867 func TestCaseCollisions(t *testing.T) { 1868 tg := testgo(t) 1869 defer tg.cleanup() 1870 tg.parallel() 1871 tg.tempDir("src/example/a/pkg") 1872 tg.tempDir("src/example/a/Pkg") 1873 tg.tempDir("src/example/b") 1874 tg.setenv("GOPATH", tg.path(".")) 1875 tg.tempFile("src/example/a/a.go", `package p 1876 import ( 1877 _ "example/a/pkg" 1878 _ "example/a/Pkg" 1879 )`) 1880 tg.tempFile("src/example/a/pkg/pkg.go", `package pkg`) 1881 tg.tempFile("src/example/a/Pkg/pkg.go", `package pkg`) 1882 tg.runFail("list", "example/a") 1883 tg.grepStderr("case-insensitive import collision", "go list example/a did not report import collision") 1884 tg.tempFile("src/example/b/file.go", `package b`) 1885 tg.tempFile("src/example/b/FILE.go", `package b`) 1886 f, err := os.Open(tg.path("src/example/b")) 1887 tg.must(err) 1888 names, err := f.Readdirnames(0) 1889 tg.must(err) 1890 tg.check(f.Close()) 1891 args := []string{"list"} 1892 if len(names) == 2 { 1893 // case-sensitive file system, let directory read find both files 1894 args = append(args, "example/b") 1895 } else { 1896 // case-insensitive file system, list files explicitly on command line 1897 args = append(args, tg.path("src/example/b/file.go"), tg.path("src/example/b/FILE.go")) 1898 } 1899 tg.runFail(args...) 1900 tg.grepStderr("case-insensitive file name collision", "go list example/b did not report file name collision") 1901 } 1902 1903 // Issue 8181. 1904 func TestGoGetDashTIssue8181(t *testing.T) { 1905 if testing.Short() { 1906 t.Skip("skipping test that uses network in short mode") 1907 } 1908 1909 tg := testgo(t) 1910 defer tg.cleanup() 1911 tg.parallel() 1912 tg.makeTempdir() 1913 tg.setenv("GOPATH", tg.path(".")) 1914 tg.run("get", "-v", "-t", "github.com/rsc/go-get-issue-8181/a", "github.com/rsc/go-get-issue-8181/b") 1915 tg.run("list", "...") 1916 tg.grepStdout("x/build/cmd/cl", "missing expected x/build/cmd/cl") 1917 } 1918 1919 func TestIssue11307(t *testing.T) { 1920 // go get -u was not working except in checkout directory 1921 if testing.Short() { 1922 t.Skip("skipping test that uses network in short mode") 1923 } 1924 1925 tg := testgo(t) 1926 defer tg.cleanup() 1927 tg.parallel() 1928 tg.makeTempdir() 1929 tg.setenv("GOPATH", tg.path(".")) 1930 tg.run("get", "github.com/rsc/go-get-issue-11307") 1931 tg.run("get", "-u", "github.com/rsc/go-get-issue-11307") // was failing 1932 } 1933 1934 func TestShadowingLogic(t *testing.T) { 1935 tg := testgo(t) 1936 defer tg.cleanup() 1937 pwd := tg.pwd() 1938 sep := string(filepath.ListSeparator) 1939 tg.setenv("GOPATH", filepath.Join(pwd, "testdata", "shadow", "root1")+sep+filepath.Join(pwd, "testdata", "shadow", "root2")) 1940 1941 // The math in root1 is not "math" because the standard math is. 1942 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/math") 1943 pwdForwardSlash := strings.Replace(pwd, string(os.PathSeparator), "/", -1) 1944 if !strings.HasPrefix(pwdForwardSlash, "/") { 1945 pwdForwardSlash = "/" + pwdForwardSlash 1946 } 1947 // The output will have makeImportValid applies, but we only 1948 // bother to deal with characters we might reasonably see. 1949 for _, r := range " :" { 1950 pwdForwardSlash = strings.Replace(pwdForwardSlash, string(r), "_", -1) 1951 } 1952 want := "(_" + pwdForwardSlash + "/testdata/shadow/root1/src/math) (" + filepath.Join(runtime.GOROOT(), "src", "math") + ")" 1953 if strings.TrimSpace(tg.getStdout()) != want { 1954 t.Error("shadowed math is not shadowed; looking for", want) 1955 } 1956 1957 // The foo in root1 is "foo". 1958 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root1/src/foo") 1959 if strings.TrimSpace(tg.getStdout()) != "(foo) ()" { 1960 t.Error("unshadowed foo is shadowed") 1961 } 1962 1963 // The foo in root2 is not "foo" because the foo in root1 got there first. 1964 tg.run("list", "-f", "({{.ImportPath}}) ({{.ConflictDir}})", "./testdata/shadow/root2/src/foo") 1965 want = "(_" + pwdForwardSlash + "/testdata/shadow/root2/src/foo) (" + filepath.Join(pwd, "testdata", "shadow", "root1", "src", "foo") + ")" 1966 if strings.TrimSpace(tg.getStdout()) != want { 1967 t.Error("shadowed foo is not shadowed; looking for", want) 1968 } 1969 1970 // The error for go install should mention the conflicting directory. 1971 tg.runFail("install", "./testdata/shadow/root2/src/foo") 1972 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") 1973 if strings.TrimSpace(tg.getStderr()) != want { 1974 t.Error("wrong shadowed install error; looking for", want) 1975 } 1976 } 1977 1978 // Only succeeds if source order is preserved. 1979 func TestSourceFileNameOrderPreserved(t *testing.T) { 1980 tg := testgo(t) 1981 defer tg.cleanup() 1982 tg.run("test", "testdata/example1_test.go", "testdata/example2_test.go") 1983 } 1984 1985 // Check that coverage analysis works at all. 1986 // Don't worry about the exact numbers but require not 0.0%. 1987 func checkCoverage(tg *testgoData, data string) { 1988 if regexp.MustCompile(`[^0-9]0\.0%`).MatchString(data) { 1989 tg.t.Error("some coverage results are 0.0%") 1990 } 1991 tg.t.Log(data) 1992 } 1993 1994 func TestCoverageRuns(t *testing.T) { 1995 if testing.Short() { 1996 t.Skip("don't build libraries for coverage in short mode") 1997 } 1998 tg := testgo(t) 1999 defer tg.cleanup() 2000 tg.run("test", "-short", "-coverpkg=strings", "strings", "regexp") 2001 data := tg.getStdout() + tg.getStderr() 2002 tg.run("test", "-short", "-cover", "strings", "math", "regexp") 2003 data += tg.getStdout() + tg.getStderr() 2004 checkCoverage(tg, data) 2005 } 2006 2007 // Check that coverage analysis uses set mode. 2008 func TestCoverageUsesSetMode(t *testing.T) { 2009 if testing.Short() { 2010 t.Skip("don't build libraries for coverage in short mode") 2011 } 2012 tg := testgo(t) 2013 defer tg.cleanup() 2014 tg.creatingTemp("testdata/cover.out") 2015 tg.run("test", "-short", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out") 2016 data := tg.getStdout() + tg.getStderr() 2017 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil { 2018 t.Error(err) 2019 } else { 2020 if !bytes.Contains(out, []byte("mode: set")) { 2021 t.Error("missing mode: set") 2022 } 2023 } 2024 checkCoverage(tg, data) 2025 } 2026 2027 func TestCoverageUsesAtomicModeForRace(t *testing.T) { 2028 if testing.Short() { 2029 t.Skip("don't build libraries for coverage in short mode") 2030 } 2031 if !canRace { 2032 t.Skip("skipping because race detector not supported") 2033 } 2034 2035 tg := testgo(t) 2036 defer tg.cleanup() 2037 tg.creatingTemp("testdata/cover.out") 2038 tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-coverprofile=testdata/cover.out") 2039 data := tg.getStdout() + tg.getStderr() 2040 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil { 2041 t.Error(err) 2042 } else { 2043 if !bytes.Contains(out, []byte("mode: atomic")) { 2044 t.Error("missing mode: atomic") 2045 } 2046 } 2047 checkCoverage(tg, data) 2048 } 2049 2050 func TestCoverageUsesActualSettingToOverrideEvenForRace(t *testing.T) { 2051 if testing.Short() { 2052 t.Skip("don't build libraries for coverage in short mode") 2053 } 2054 if !canRace { 2055 t.Skip("skipping because race detector not supported") 2056 } 2057 2058 tg := testgo(t) 2059 defer tg.cleanup() 2060 tg.creatingTemp("testdata/cover.out") 2061 tg.run("test", "-short", "-race", "-cover", "encoding/binary", "-covermode=count", "-coverprofile=testdata/cover.out") 2062 data := tg.getStdout() + tg.getStderr() 2063 if out, err := ioutil.ReadFile("testdata/cover.out"); err != nil { 2064 t.Error(err) 2065 } else { 2066 if !bytes.Contains(out, []byte("mode: count")) { 2067 t.Error("missing mode: count") 2068 } 2069 } 2070 checkCoverage(tg, data) 2071 } 2072 2073 func TestCoverageImportMainLoop(t *testing.T) { 2074 tg := testgo(t) 2075 defer tg.cleanup() 2076 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2077 tg.runFail("test", "importmain/test") 2078 tg.grepStderr("not an importable package", "did not detect import main") 2079 tg.runFail("test", "-cover", "importmain/test") 2080 tg.grepStderr("not an importable package", "did not detect import main") 2081 } 2082 2083 func TestBuildDryRunWithCgo(t *testing.T) { 2084 if !canCgo { 2085 t.Skip("skipping because cgo not enabled") 2086 } 2087 2088 tg := testgo(t) 2089 defer tg.cleanup() 2090 tg.tempFile("foo.go", `package main 2091 2092 /* 2093 #include <limits.h> 2094 */ 2095 import "C" 2096 2097 func main() { 2098 println(C.INT_MAX) 2099 }`) 2100 tg.run("build", "-n", tg.path("foo.go")) 2101 tg.grepStderrNot(`os.Stat .* no such file or directory`, "unexpected stat of archive file") 2102 } 2103 2104 func TestCoverageWithCgo(t *testing.T) { 2105 if !canCgo { 2106 t.Skip("skipping because cgo not enabled") 2107 } 2108 2109 tg := testgo(t) 2110 defer tg.cleanup() 2111 tg.run("test", "-short", "-cover", "./testdata/cgocover") 2112 data := tg.getStdout() + tg.getStderr() 2113 checkCoverage(tg, data) 2114 } 2115 2116 func TestCgoDependsOnSyscall(t *testing.T) { 2117 if testing.Short() { 2118 t.Skip("skipping test that removes $GOROOT/pkg/*_race in short mode") 2119 } 2120 if !canCgo { 2121 t.Skip("skipping because cgo not enabled") 2122 } 2123 if !canRace { 2124 t.Skip("skipping because race detector not supported") 2125 } 2126 2127 tg := testgo(t) 2128 defer tg.cleanup() 2129 files, err := filepath.Glob(filepath.Join(runtime.GOROOT(), "pkg", "*_race")) 2130 tg.must(err) 2131 for _, file := range files { 2132 tg.check(os.RemoveAll(file)) 2133 } 2134 tg.tempFile("src/foo/foo.go", ` 2135 package foo 2136 //#include <stdio.h> 2137 import "C"`) 2138 tg.setenv("GOPATH", tg.path(".")) 2139 tg.run("build", "-race", "foo") 2140 } 2141 2142 func TestCgoShowsFullPathNames(t *testing.T) { 2143 if !canCgo { 2144 t.Skip("skipping because cgo not enabled") 2145 } 2146 2147 tg := testgo(t) 2148 defer tg.cleanup() 2149 tg.parallel() 2150 tg.tempFile("src/x/y/dirname/foo.go", ` 2151 package foo 2152 import "C" 2153 func f() {`) 2154 tg.setenv("GOPATH", tg.path(".")) 2155 tg.runFail("build", "x/y/dirname") 2156 tg.grepBoth("x/y/dirname", "error did not use full path") 2157 } 2158 2159 func TestCgoHandlesWlORIGIN(t *testing.T) { 2160 if !canCgo { 2161 t.Skip("skipping because cgo not enabled") 2162 } 2163 2164 tg := testgo(t) 2165 defer tg.cleanup() 2166 tg.parallel() 2167 tg.tempFile("src/origin/origin.go", `package origin 2168 // #cgo !darwin LDFLAGS: -Wl,-rpath -Wl,$ORIGIN 2169 // void f(void) {} 2170 import "C" 2171 func f() { C.f() }`) 2172 tg.setenv("GOPATH", tg.path(".")) 2173 tg.run("build", "origin") 2174 } 2175 2176 // "go test -c -test.bench=XXX errors" should not hang 2177 func TestIssue6480(t *testing.T) { 2178 tg := testgo(t) 2179 defer tg.cleanup() 2180 tg.makeTempdir() 2181 tg.cd(tg.path(".")) 2182 tg.run("test", "-c", "-test.bench=XXX", "errors") 2183 } 2184 2185 // cmd/cgo: undefined reference when linking a C-library using gccgo 2186 func TestIssue7573(t *testing.T) { 2187 if !canCgo { 2188 t.Skip("skipping because cgo not enabled") 2189 } 2190 if _, err := exec.LookPath("gccgo"); err != nil { 2191 t.Skip("skipping because no gccgo compiler found") 2192 } 2193 2194 tg := testgo(t) 2195 defer tg.cleanup() 2196 tg.parallel() 2197 tg.tempFile("src/cgoref/cgoref.go", ` 2198 package main 2199 // #cgo LDFLAGS: -L alibpath -lalib 2200 // void f(void) {} 2201 import "C" 2202 2203 func main() { C.f() }`) 2204 tg.setenv("GOPATH", tg.path(".")) 2205 tg.run("build", "-n", "-compiler", "gccgo", "cgoref") 2206 tg.grepStderr(`gccgo.*\-L alibpath \-lalib`, `no Go-inline "#cgo LDFLAGS:" ("-L alibpath -lalib") passed to gccgo linking stage`) 2207 } 2208 2209 func TestListTemplateContextFunction(t *testing.T) { 2210 tg := testgo(t) 2211 defer tg.cleanup() 2212 for _, tt := range []struct { 2213 v string 2214 want string 2215 }{ 2216 {"GOARCH", runtime.GOARCH}, 2217 {"GOOS", runtime.GOOS}, 2218 {"GOROOT", filepath.Clean(runtime.GOROOT())}, 2219 {"GOPATH", os.Getenv("GOPATH")}, 2220 {"CgoEnabled", ""}, 2221 {"UseAllFiles", ""}, 2222 {"Compiler", ""}, 2223 {"BuildTags", ""}, 2224 {"ReleaseTags", ""}, 2225 {"InstallSuffix", ""}, 2226 } { 2227 tmpl := "{{context." + tt.v + "}}" 2228 tg.run("list", "-f", tmpl) 2229 if tt.want == "" { 2230 continue 2231 } 2232 if got := strings.TrimSpace(tg.getStdout()); got != tt.want { 2233 t.Errorf("go list -f %q: got %q; want %q", tmpl, got, tt.want) 2234 } 2235 } 2236 } 2237 2238 // cmd/go: "go test" should fail if package does not build 2239 func TestIssue7108(t *testing.T) { 2240 tg := testgo(t) 2241 defer tg.cleanup() 2242 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2243 tg.runFail("test", "notest") 2244 } 2245 2246 // cmd/go: go test -a foo does not rebuild regexp. 2247 func TestIssue6844(t *testing.T) { 2248 if testing.Short() { 2249 t.Skip("don't rebuild the standard library in short mode") 2250 } 2251 2252 tg := testgo(t) 2253 defer tg.cleanup() 2254 tg.creatingTemp("deps.test" + exeSuffix) 2255 tg.run("test", "-x", "-a", "-c", "testdata/dep_test.go") 2256 tg.grepStderr("regexp", "go test -x -a -c testdata/dep-test.go did not rebuild regexp") 2257 } 2258 2259 func TestBuildDashIInstallsDependencies(t *testing.T) { 2260 tg := testgo(t) 2261 defer tg.cleanup() 2262 tg.parallel() 2263 tg.tempFile("src/x/y/foo/foo.go", `package foo 2264 func F() {}`) 2265 tg.tempFile("src/x/y/bar/bar.go", `package bar 2266 import "x/y/foo" 2267 func F() { foo.F() }`) 2268 tg.setenv("GOPATH", tg.path(".")) 2269 2270 checkbar := func(desc string) { 2271 tg.sleep() 2272 tg.must(os.Chtimes(tg.path("src/x/y/foo/foo.go"), time.Now(), time.Now())) 2273 tg.sleep() 2274 tg.run("build", "-v", "-i", "x/y/bar") 2275 tg.grepBoth("x/y/foo", "first build -i "+desc+" did not build x/y/foo") 2276 tg.run("build", "-v", "-i", "x/y/bar") 2277 tg.grepBothNot("x/y/foo", "second build -i "+desc+" built x/y/foo") 2278 } 2279 checkbar("pkg") 2280 tg.creatingTemp("bar" + exeSuffix) 2281 tg.tempFile("src/x/y/bar/bar.go", `package main 2282 import "x/y/foo" 2283 func main() { foo.F() }`) 2284 checkbar("cmd") 2285 } 2286 2287 func TestGoBuildInTestOnlyDirectoryFailsWithAGoodError(t *testing.T) { 2288 tg := testgo(t) 2289 defer tg.cleanup() 2290 tg.runFail("build", "./testdata/testonly") 2291 tg.grepStderr("no buildable Go", "go build ./testdata/testonly produced unexpected error") 2292 } 2293 2294 func TestGoTestDetectsTestOnlyImportCycles(t *testing.T) { 2295 tg := testgo(t) 2296 defer tg.cleanup() 2297 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2298 tg.runFail("test", "-c", "testcycle/p3") 2299 tg.grepStderr("import cycle not allowed in test", "go test testcycle/p3 produced unexpected error") 2300 2301 tg.runFail("test", "-c", "testcycle/q1") 2302 tg.grepStderr("import cycle not allowed in test", "go test testcycle/q1 produced unexpected error") 2303 } 2304 2305 func TestGoTestFooTestWorks(t *testing.T) { 2306 tg := testgo(t) 2307 defer tg.cleanup() 2308 tg.run("test", "testdata/standalone_test.go") 2309 } 2310 2311 func TestGoTestFlagsAfterPackage(t *testing.T) { 2312 tg := testgo(t) 2313 defer tg.cleanup() 2314 tg.run("test", "testdata/flag_test.go", "-v", "-args", "-v=7") // Two distinct -v flags. 2315 tg.run("test", "-v", "testdata/flag_test.go", "-args", "-v=7") // Two distinct -v flags. 2316 } 2317 2318 func TestGoTestXtestonlyWorks(t *testing.T) { 2319 tg := testgo(t) 2320 defer tg.cleanup() 2321 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2322 tg.run("clean", "-i", "xtestonly") 2323 tg.run("test", "xtestonly") 2324 } 2325 2326 func TestGoTestBuildsAnXtestContainingOnlyNonRunnableExamples(t *testing.T) { 2327 tg := testgo(t) 2328 defer tg.cleanup() 2329 tg.run("test", "-v", "./testdata/norunexample") 2330 tg.grepStdout("File with non-runnable example was built.", "file with non-runnable example was not built") 2331 } 2332 2333 func TestGoGenerateHandlesSimpleCommand(t *testing.T) { 2334 if runtime.GOOS == "windows" { 2335 t.Skip("skipping because windows has no echo command") 2336 } 2337 2338 tg := testgo(t) 2339 defer tg.cleanup() 2340 tg.run("generate", "./testdata/generate/test1.go") 2341 tg.grepStdout("Success", "go generate ./testdata/generate/test1.go generated wrong output") 2342 } 2343 2344 func TestGoGenerateHandlesCommandAlias(t *testing.T) { 2345 if runtime.GOOS == "windows" { 2346 t.Skip("skipping because windows has no echo command") 2347 } 2348 2349 tg := testgo(t) 2350 defer tg.cleanup() 2351 tg.run("generate", "./testdata/generate/test2.go") 2352 tg.grepStdout("Now is the time for all good men", "go generate ./testdata/generate/test2.go generated wrong output") 2353 } 2354 2355 func TestGoGenerateVariableSubstitution(t *testing.T) { 2356 if runtime.GOOS == "windows" { 2357 t.Skip("skipping because windows has no echo command") 2358 } 2359 2360 tg := testgo(t) 2361 defer tg.cleanup() 2362 tg.run("generate", "./testdata/generate/test3.go") 2363 tg.grepStdout(runtime.GOARCH+" test3.go:7 pabc xyzp/test3.go/123", "go generate ./testdata/generate/test3.go generated wrong output") 2364 } 2365 2366 func TestGoGenerateRunFlag(t *testing.T) { 2367 if runtime.GOOS == "windows" { 2368 t.Skip("skipping because windows has no echo command") 2369 } 2370 2371 tg := testgo(t) 2372 defer tg.cleanup() 2373 tg.run("generate", "-run", "y.s", "./testdata/generate/test4.go") 2374 tg.grepStdout("yes", "go generate -run yes ./testdata/generate/test4.go did not select yes") 2375 tg.grepStdoutNot("no", "go generate -run yes ./testdata/generate/test4.go selected no") 2376 } 2377 2378 func TestGoGenerateEnv(t *testing.T) { 2379 switch runtime.GOOS { 2380 case "plan9", "windows": 2381 t.Skipf("skipping because %s does not have the env command", runtime.GOOS) 2382 } 2383 tg := testgo(t) 2384 defer tg.cleanup() 2385 tg.parallel() 2386 tg.tempFile("env.go", "package main\n\n//go:generate env") 2387 tg.run("generate", tg.path("env.go")) 2388 for _, v := range []string{"GOARCH", "GOOS", "GOFILE", "GOLINE", "GOPACKAGE", "DOLLAR"} { 2389 tg.grepStdout("^"+v+"=", "go generate environment missing "+v) 2390 } 2391 } 2392 2393 func TestGoGenerateBadImports(t *testing.T) { 2394 if runtime.GOOS == "windows" { 2395 t.Skip("skipping because windows has no echo command") 2396 } 2397 2398 // This package has an invalid import causing an import cycle, 2399 // but go generate is supposed to still run. 2400 tg := testgo(t) 2401 defer tg.cleanup() 2402 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2403 tg.run("generate", "gencycle") 2404 tg.grepStdout("hello world", "go generate gencycle did not run generator") 2405 } 2406 2407 func TestGoGetCustomDomainWildcard(t *testing.T) { 2408 testenv.MustHaveExternalNetwork(t) 2409 2410 tg := testgo(t) 2411 defer tg.cleanup() 2412 tg.makeTempdir() 2413 tg.setenv("GOPATH", tg.path(".")) 2414 tg.run("get", "-u", "rsc.io/pdf/...") 2415 tg.wantExecutable(tg.path("bin/pdfpasswd"+exeSuffix), "did not build rsc/io/pdf/pdfpasswd") 2416 } 2417 2418 func TestGoGetInternalWildcard(t *testing.T) { 2419 testenv.MustHaveExternalNetwork(t) 2420 2421 tg := testgo(t) 2422 defer tg.cleanup() 2423 tg.makeTempdir() 2424 tg.setenv("GOPATH", tg.path(".")) 2425 // used to fail with errors about internal packages 2426 tg.run("get", "github.com/rsc/go-get-issue-11960/...") 2427 } 2428 2429 func TestGoVetWithExternalTests(t *testing.T) { 2430 testenv.MustHaveExternalNetwork(t) 2431 2432 tg := testgo(t) 2433 defer tg.cleanup() 2434 tg.makeTempdir() 2435 tg.run("install", "cmd/vet") 2436 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2437 tg.runFail("vet", "vetpkg") 2438 tg.grepBoth("missing argument for Printf", "go vet vetpkg did not find missing argument for Printf") 2439 } 2440 2441 func TestGoVetWithTags(t *testing.T) { 2442 testenv.MustHaveExternalNetwork(t) 2443 2444 tg := testgo(t) 2445 defer tg.cleanup() 2446 tg.makeTempdir() 2447 tg.run("install", "cmd/vet") 2448 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2449 tg.runFail("vet", "-tags", "tagtest", "vetpkg") 2450 tg.grepBoth(`c\.go.*wrong number of args for format`, "go get vetpkg did not run scan tagged file") 2451 } 2452 2453 // Issue 9767. 2454 func TestGoGetRscIoToolstash(t *testing.T) { 2455 testenv.MustHaveExternalNetwork(t) 2456 2457 tg := testgo(t) 2458 defer tg.cleanup() 2459 tg.tempDir("src/rsc.io") 2460 tg.setenv("GOPATH", tg.path(".")) 2461 tg.cd(tg.path("src/rsc.io")) 2462 tg.run("get", "./toolstash") 2463 } 2464 2465 // Issue 13037: Was not parsing <meta> tags in 404 served over HTTPS 2466 func TestGoGetHTTPS404(t *testing.T) { 2467 testenv.MustHaveExternalNetwork(t) 2468 switch runtime.GOOS { 2469 case "darwin", "linux", "freebsd": 2470 default: 2471 t.Skipf("test case does not work on %s", runtime.GOOS) 2472 } 2473 2474 tg := testgo(t) 2475 defer tg.cleanup() 2476 tg.tempDir("src") 2477 tg.setenv("GOPATH", tg.path(".")) 2478 tg.run("get", "bazil.org/fuse/fs/fstestutil") 2479 } 2480 2481 // Test that you cannot import a main package. 2482 // See golang.org/issue/4210 and golang.org/issue/17475. 2483 func TestImportMain(t *testing.T) { 2484 tg := testgo(t) 2485 defer tg.cleanup() 2486 2487 // Importing package main from that package main's test should work. 2488 tg.tempFile("src/x/main.go", `package main 2489 var X int 2490 func main() {}`) 2491 tg.tempFile("src/x/main_test.go", `package main_test 2492 import xmain "x" 2493 import "testing" 2494 var _ = xmain.X 2495 func TestFoo(t *testing.T) {} 2496 `) 2497 tg.setenv("GOPATH", tg.path(".")) 2498 tg.run("build", "x") 2499 tg.run("test", "x") 2500 2501 // Importing package main from another package should fail. 2502 tg.tempFile("src/p1/p.go", `package p1 2503 import xmain "x" 2504 var _ = xmain.X 2505 `) 2506 tg.runFail("build", "p1") 2507 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main") 2508 2509 // ... even in that package's test. 2510 tg.tempFile("src/p2/p.go", `package p2 2511 `) 2512 tg.tempFile("src/p2/p_test.go", `package p2 2513 import xmain "x" 2514 import "testing" 2515 var _ = xmain.X 2516 func TestFoo(t *testing.T) {} 2517 `) 2518 tg.run("build", "p2") 2519 tg.runFail("test", "p2") 2520 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main") 2521 2522 // ... even if that package's test is an xtest. 2523 tg.tempFile("src/p3/p.go", `package p 2524 `) 2525 tg.tempFile("src/p3/p_test.go", `package p_test 2526 import xmain "x" 2527 import "testing" 2528 var _ = xmain.X 2529 func TestFoo(t *testing.T) {} 2530 `) 2531 tg.run("build", "p3") 2532 tg.runFail("test", "p3") 2533 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main") 2534 2535 // ... even if that package is a package main 2536 tg.tempFile("src/p4/p.go", `package main 2537 func main() {} 2538 `) 2539 tg.tempFile("src/p4/p_test.go", `package main 2540 import xmain "x" 2541 import "testing" 2542 var _ = xmain.X 2543 func TestFoo(t *testing.T) {} 2544 `) 2545 tg.creatingTemp("p4" + exeSuffix) 2546 tg.run("build", "p4") 2547 tg.runFail("test", "p4") 2548 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main") 2549 2550 // ... even if that package is a package main using an xtest. 2551 tg.tempFile("src/p5/p.go", `package main 2552 func main() {} 2553 `) 2554 tg.tempFile("src/p5/p_test.go", `package main_test 2555 import xmain "x" 2556 import "testing" 2557 var _ = xmain.X 2558 func TestFoo(t *testing.T) {} 2559 `) 2560 tg.creatingTemp("p5" + exeSuffix) 2561 tg.run("build", "p5") 2562 tg.runFail("test", "p5") 2563 tg.grepStderr("import \"x\" is a program, not an importable package", "did not diagnose package main") 2564 } 2565 2566 // Test that you cannot use a local import in a package 2567 // accessed by a non-local import (found in a GOPATH/GOROOT). 2568 // See golang.org/issue/17475. 2569 func TestImportLocal(t *testing.T) { 2570 tg := testgo(t) 2571 defer tg.cleanup() 2572 2573 tg.tempFile("src/dir/x/x.go", `package x 2574 var X int 2575 `) 2576 tg.setenv("GOPATH", tg.path(".")) 2577 tg.run("build", "dir/x") 2578 2579 // Ordinary import should work. 2580 tg.tempFile("src/dir/p0/p.go", `package p0 2581 import "dir/x" 2582 var _ = x.X 2583 `) 2584 tg.run("build", "dir/p0") 2585 2586 // Relative import should not. 2587 tg.tempFile("src/dir/p1/p.go", `package p1 2588 import "../x" 2589 var _ = x.X 2590 `) 2591 tg.runFail("build", "dir/p1") 2592 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2593 2594 // ... even in a test. 2595 tg.tempFile("src/dir/p2/p.go", `package p2 2596 `) 2597 tg.tempFile("src/dir/p2/p_test.go", `package p2 2598 import "../x" 2599 import "testing" 2600 var _ = x.X 2601 func TestFoo(t *testing.T) {} 2602 `) 2603 tg.run("build", "dir/p2") 2604 tg.runFail("test", "dir/p2") 2605 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2606 2607 // ... even in an xtest. 2608 tg.tempFile("src/dir/p2/p_test.go", `package p2_test 2609 import "../x" 2610 import "testing" 2611 var _ = x.X 2612 func TestFoo(t *testing.T) {} 2613 `) 2614 tg.run("build", "dir/p2") 2615 tg.runFail("test", "dir/p2") 2616 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2617 2618 // Relative import starting with ./ should not work either. 2619 tg.tempFile("src/dir/d.go", `package dir 2620 import "./x" 2621 var _ = x.X 2622 `) 2623 tg.runFail("build", "dir") 2624 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2625 2626 // ... even in a test. 2627 tg.tempFile("src/dir/d.go", `package dir 2628 `) 2629 tg.tempFile("src/dir/d_test.go", `package dir 2630 import "./x" 2631 import "testing" 2632 var _ = x.X 2633 func TestFoo(t *testing.T) {} 2634 `) 2635 tg.run("build", "dir") 2636 tg.runFail("test", "dir") 2637 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2638 2639 // ... even in an xtest. 2640 tg.tempFile("src/dir/d_test.go", `package dir_test 2641 import "./x" 2642 import "testing" 2643 var _ = x.X 2644 func TestFoo(t *testing.T) {} 2645 `) 2646 tg.run("build", "dir") 2647 tg.runFail("test", "dir") 2648 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2649 2650 // Relative import plain ".." should not work. 2651 tg.tempFile("src/dir/x/y/y.go", `package dir 2652 import ".." 2653 var _ = x.X 2654 `) 2655 tg.runFail("build", "dir/x/y") 2656 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2657 2658 // ... even in a test. 2659 tg.tempFile("src/dir/x/y/y.go", `package y 2660 `) 2661 tg.tempFile("src/dir/x/y/y_test.go", `package y 2662 import ".." 2663 import "testing" 2664 var _ = x.X 2665 func TestFoo(t *testing.T) {} 2666 `) 2667 tg.run("build", "dir/x/y") 2668 tg.runFail("test", "dir/x/y") 2669 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2670 2671 // ... even in an x test. 2672 tg.tempFile("src/dir/x/y/y_test.go", `package y_test 2673 import ".." 2674 import "testing" 2675 var _ = x.X 2676 func TestFoo(t *testing.T) {} 2677 `) 2678 tg.run("build", "dir/x/y") 2679 tg.runFail("test", "dir/x/y") 2680 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2681 2682 // Relative import "." should not work. 2683 tg.tempFile("src/dir/x/xx.go", `package x 2684 import "." 2685 var _ = x.X 2686 `) 2687 tg.runFail("build", "dir/x") 2688 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2689 2690 // ... even in a test. 2691 tg.tempFile("src/dir/x/xx.go", `package x 2692 `) 2693 tg.tempFile("src/dir/x/xx_test.go", `package x 2694 import "." 2695 import "testing" 2696 var _ = x.X 2697 func TestFoo(t *testing.T) {} 2698 `) 2699 tg.run("build", "dir/x") 2700 tg.runFail("test", "dir/x") 2701 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2702 2703 // ... even in an xtest. 2704 tg.tempFile("src/dir/x/xx.go", `package x 2705 `) 2706 tg.tempFile("src/dir/x/xx_test.go", `package x_test 2707 import "." 2708 import "testing" 2709 var _ = x.X 2710 func TestFoo(t *testing.T) {} 2711 `) 2712 tg.run("build", "dir/x") 2713 tg.runFail("test", "dir/x") 2714 tg.grepStderr("local import.*in non-local package", "did not diagnose local import") 2715 } 2716 2717 func TestGoGetInsecure(t *testing.T) { 2718 testenv.MustHaveExternalNetwork(t) 2719 2720 t.Skip("golang.org/issue/15410") 2721 2722 tg := testgo(t) 2723 defer tg.cleanup() 2724 tg.makeTempdir() 2725 tg.setenv("GOPATH", tg.path(".")) 2726 tg.failSSH() 2727 2728 const repo = "wh3rd.net/git.git" 2729 2730 // Try go get -d of HTTP-only repo (should fail). 2731 tg.runFail("get", "-d", repo) 2732 2733 // Try again with -insecure (should succeed). 2734 tg.run("get", "-d", "-insecure", repo) 2735 2736 // Try updating without -insecure (should fail). 2737 tg.runFail("get", "-d", "-u", "-f", repo) 2738 } 2739 2740 func TestGoGetUpdateInsecure(t *testing.T) { 2741 testenv.MustHaveExternalNetwork(t) 2742 2743 tg := testgo(t) 2744 defer tg.cleanup() 2745 tg.makeTempdir() 2746 tg.setenv("GOPATH", tg.path(".")) 2747 2748 const repo = "github.com/golang/example" 2749 2750 // Clone the repo via HTTP manually. 2751 cmd := exec.Command("git", "clone", "-q", "http://"+repo, tg.path("src/"+repo)) 2752 if out, err := cmd.CombinedOutput(); err != nil { 2753 t.Fatalf("cloning %v repo: %v\n%s", repo, err, out) 2754 } 2755 2756 // Update without -insecure should fail. 2757 // Update with -insecure should succeed. 2758 // We need -f to ignore import comments. 2759 const pkg = repo + "/hello" 2760 tg.runFail("get", "-d", "-u", "-f", pkg) 2761 tg.run("get", "-d", "-u", "-f", "-insecure", pkg) 2762 } 2763 2764 func TestGoGetInsecureCustomDomain(t *testing.T) { 2765 testenv.MustHaveExternalNetwork(t) 2766 2767 tg := testgo(t) 2768 defer tg.cleanup() 2769 tg.makeTempdir() 2770 tg.setenv("GOPATH", tg.path(".")) 2771 2772 const repo = "wh3rd.net/repo" 2773 tg.runFail("get", "-d", repo) 2774 tg.run("get", "-d", "-insecure", repo) 2775 } 2776 2777 func TestGoRunDirs(t *testing.T) { 2778 tg := testgo(t) 2779 defer tg.cleanup() 2780 tg.cd("testdata/rundir") 2781 tg.runFail("run", "x.go", "sub/sub.go") 2782 tg.grepStderr("named files must all be in one directory; have ./ and sub/", "wrong output") 2783 tg.runFail("run", "sub/sub.go", "x.go") 2784 tg.grepStderr("named files must all be in one directory; have sub/ and ./", "wrong output") 2785 } 2786 2787 func TestGoInstallPkgdir(t *testing.T) { 2788 tg := testgo(t) 2789 defer tg.cleanup() 2790 tg.makeTempdir() 2791 pkg := tg.path(".") 2792 tg.run("install", "-pkgdir", pkg, "errors") 2793 _, err := os.Stat(filepath.Join(pkg, "errors.a")) 2794 tg.must(err) 2795 _, err = os.Stat(filepath.Join(pkg, "runtime.a")) 2796 tg.must(err) 2797 } 2798 2799 func TestGoTestRaceInstallCgo(t *testing.T) { 2800 switch sys := runtime.GOOS + "/" + runtime.GOARCH; sys { 2801 case "darwin/amd64", "freebsd/amd64", "linux/amd64", "windows/amd64": 2802 // ok 2803 default: 2804 t.Skip("no race detector on %s", sys) 2805 } 2806 2807 if !build.Default.CgoEnabled { 2808 t.Skip("no race detector without cgo") 2809 } 2810 2811 // golang.org/issue/10500. 2812 // This used to install a race-enabled cgo. 2813 tg := testgo(t) 2814 defer tg.cleanup() 2815 tg.run("tool", "-n", "cgo") 2816 cgo := strings.TrimSpace(tg.stdout.String()) 2817 old, err := os.Stat(cgo) 2818 tg.must(err) 2819 tg.run("test", "-race", "-i", "runtime/race") 2820 new, err := os.Stat(cgo) 2821 tg.must(err) 2822 if new.ModTime() != old.ModTime() { 2823 t.Fatalf("go test -i runtime/race reinstalled cmd/cgo") 2824 } 2825 } 2826 2827 func TestGoTestImportErrorStack(t *testing.T) { 2828 const out = `package testdep/p1 (test) 2829 imports testdep/p2 2830 imports testdep/p3: no buildable Go source files` 2831 2832 tg := testgo(t) 2833 defer tg.cleanup() 2834 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 2835 tg.runFail("test", "testdep/p1") 2836 if !strings.Contains(tg.stderr.String(), out) { 2837 t.Fatalf("did not give full import stack:\n\n%s", tg.stderr.String()) 2838 } 2839 } 2840 2841 func TestGoGetUpdate(t *testing.T) { 2842 // golang.org/issue/9224. 2843 // The recursive updating was trying to walk to 2844 // former dependencies, not current ones. 2845 2846 testenv.MustHaveExternalNetwork(t) 2847 2848 tg := testgo(t) 2849 defer tg.cleanup() 2850 tg.makeTempdir() 2851 tg.setenv("GOPATH", tg.path(".")) 2852 2853 rewind := func() { 2854 tg.run("get", "github.com/rsc/go-get-issue-9224-cmd") 2855 cmd := exec.Command("git", "reset", "--hard", "HEAD~") 2856 cmd.Dir = tg.path("src/github.com/rsc/go-get-issue-9224-lib") 2857 out, err := cmd.CombinedOutput() 2858 if err != nil { 2859 t.Fatalf("git: %v\n%s", err, out) 2860 } 2861 } 2862 2863 rewind() 2864 tg.run("get", "-u", "github.com/rsc/go-get-issue-9224-cmd") 2865 2866 // Again with -d -u. 2867 rewind() 2868 tg.run("get", "-d", "-u", "github.com/rsc/go-get-issue-9224-cmd") 2869 } 2870 2871 func TestGoGetDomainRoot(t *testing.T) { 2872 // golang.org/issue/9357. 2873 // go get foo.io (not foo.io/subdir) was not working consistently. 2874 2875 testenv.MustHaveExternalNetwork(t) 2876 2877 tg := testgo(t) 2878 defer tg.cleanup() 2879 tg.makeTempdir() 2880 tg.setenv("GOPATH", tg.path(".")) 2881 2882 // go-get-issue-9357.appspot.com is running 2883 // the code at github.com/rsc/go-get-issue-9357, 2884 // a trivial Go on App Engine app that serves a 2885 // <meta> tag for the domain root. 2886 tg.run("get", "-d", "go-get-issue-9357.appspot.com") 2887 tg.run("get", "go-get-issue-9357.appspot.com") 2888 tg.run("get", "-u", "go-get-issue-9357.appspot.com") 2889 2890 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com"))) 2891 tg.run("get", "go-get-issue-9357.appspot.com") 2892 2893 tg.must(os.RemoveAll(tg.path("src/go-get-issue-9357.appspot.com"))) 2894 tg.run("get", "-u", "go-get-issue-9357.appspot.com") 2895 } 2896 2897 func TestGoInstallShadowedGOPATH(t *testing.T) { 2898 // golang.org/issue/3652. 2899 // go get foo.io (not foo.io/subdir) was not working consistently. 2900 2901 testenv.MustHaveExternalNetwork(t) 2902 2903 tg := testgo(t) 2904 defer tg.cleanup() 2905 tg.makeTempdir() 2906 tg.setenv("GOPATH", tg.path("gopath1")+string(filepath.ListSeparator)+tg.path("gopath2")) 2907 2908 tg.tempDir("gopath1/src/test") 2909 tg.tempDir("gopath2/src/test") 2910 tg.tempFile("gopath2/src/test/main.go", "package main\nfunc main(){}\n") 2911 2912 tg.cd(tg.path("gopath2/src/test")) 2913 tg.runFail("install") 2914 tg.grepStderr("no install location for.*gopath2.src.test: hidden by .*gopath1.src.test", "missing error") 2915 } 2916 2917 func TestGoBuildGOPATHOrder(t *testing.T) { 2918 // golang.org/issue/14176#issuecomment-179895769 2919 // golang.org/issue/14192 2920 // -I arguments to compiler could end up not in GOPATH order, 2921 // leading to unexpected import resolution in the compiler. 2922 // This is still not a complete fix (see golang.org/issue/14271 and next test) 2923 // but it is clearly OK and enough to fix both of the two reported 2924 // instances of the underlying problem. It will have to do for now. 2925 2926 tg := testgo(t) 2927 defer tg.cleanup() 2928 tg.makeTempdir() 2929 tg.setenv("GOPATH", tg.path("p1")+string(filepath.ListSeparator)+tg.path("p2")) 2930 2931 tg.tempFile("p1/src/foo/foo.go", "package foo\n") 2932 tg.tempFile("p2/src/baz/baz.go", "package baz\n") 2933 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n") 2934 tg.tempFile("p1/src/bar/bar.go", ` 2935 package bar 2936 import _ "baz" 2937 import _ "foo" 2938 `) 2939 2940 tg.run("install", "-x", "bar") 2941 } 2942 2943 func TestGoBuildGOPATHOrderBroken(t *testing.T) { 2944 // This test is known not to work. 2945 // See golang.org/issue/14271. 2946 t.Skip("golang.org/issue/14271") 2947 2948 tg := testgo(t) 2949 defer tg.cleanup() 2950 tg.makeTempdir() 2951 2952 tg.tempFile("p1/src/foo/foo.go", "package foo\n") 2953 tg.tempFile("p2/src/baz/baz.go", "package baz\n") 2954 tg.tempFile("p1/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/baz.a", "bad\n") 2955 tg.tempFile("p2/pkg/"+runtime.GOOS+"_"+runtime.GOARCH+"/foo.a", "bad\n") 2956 tg.tempFile("p1/src/bar/bar.go", ` 2957 package bar 2958 import _ "baz" 2959 import _ "foo" 2960 `) 2961 2962 colon := string(filepath.ListSeparator) 2963 tg.setenv("GOPATH", tg.path("p1")+colon+tg.path("p2")) 2964 tg.run("install", "-x", "bar") 2965 2966 tg.setenv("GOPATH", tg.path("p2")+colon+tg.path("p1")) 2967 tg.run("install", "-x", "bar") 2968 } 2969 2970 func TestIssue11709(t *testing.T) { 2971 tg := testgo(t) 2972 defer tg.cleanup() 2973 tg.tempFile("run.go", ` 2974 package main 2975 import "os" 2976 func main() { 2977 if os.Getenv("TERM") != "" { 2978 os.Exit(1) 2979 } 2980 }`) 2981 tg.unsetenv("TERM") 2982 tg.run("run", tg.path("run.go")) 2983 } 2984 2985 func TestIssue12096(t *testing.T) { 2986 tg := testgo(t) 2987 defer tg.cleanup() 2988 tg.tempFile("test_test.go", ` 2989 package main 2990 import ("os"; "testing") 2991 func TestEnv(t *testing.T) { 2992 if os.Getenv("TERM") != "" { 2993 t.Fatal("TERM is set") 2994 } 2995 }`) 2996 tg.unsetenv("TERM") 2997 tg.run("test", tg.path("test_test.go")) 2998 } 2999 3000 func TestGoBuildOutput(t *testing.T) { 3001 tg := testgo(t) 3002 defer tg.cleanup() 3003 3004 tg.makeTempdir() 3005 tg.cd(tg.path(".")) 3006 3007 nonExeSuffix := ".exe" 3008 if exeSuffix == ".exe" { 3009 nonExeSuffix = "" 3010 } 3011 3012 tg.tempFile("x.go", "package main\nfunc main(){}\n") 3013 tg.run("build", "x.go") 3014 tg.wantExecutable("x"+exeSuffix, "go build x.go did not write x"+exeSuffix) 3015 tg.must(os.Remove(tg.path("x" + exeSuffix))) 3016 tg.mustNotExist("x" + nonExeSuffix) 3017 3018 tg.run("build", "-o", "myprog", "x.go") 3019 tg.mustNotExist("x") 3020 tg.mustNotExist("x.exe") 3021 tg.wantExecutable("myprog", "go build -o myprog x.go did not write myprog") 3022 tg.mustNotExist("myprog.exe") 3023 3024 tg.tempFile("p.go", "package p\n") 3025 tg.run("build", "p.go") 3026 tg.mustNotExist("p") 3027 tg.mustNotExist("p.a") 3028 tg.mustNotExist("p.o") 3029 tg.mustNotExist("p.exe") 3030 3031 tg.run("build", "-o", "p.a", "p.go") 3032 tg.wantArchive("p.a") 3033 3034 tg.run("build", "cmd/gofmt") 3035 tg.wantExecutable("gofmt"+exeSuffix, "go build cmd/gofmt did not write gofmt"+exeSuffix) 3036 tg.must(os.Remove(tg.path("gofmt" + exeSuffix))) 3037 tg.mustNotExist("gofmt" + nonExeSuffix) 3038 3039 tg.run("build", "-o", "mygofmt", "cmd/gofmt") 3040 tg.wantExecutable("mygofmt", "go build -o mygofmt cmd/gofmt did not write mygofmt") 3041 tg.mustNotExist("mygofmt.exe") 3042 tg.mustNotExist("gofmt") 3043 tg.mustNotExist("gofmt.exe") 3044 3045 tg.run("build", "sync/atomic") 3046 tg.mustNotExist("atomic") 3047 tg.mustNotExist("atomic.exe") 3048 3049 tg.run("build", "-o", "myatomic.a", "sync/atomic") 3050 tg.wantArchive("myatomic.a") 3051 tg.mustNotExist("atomic") 3052 tg.mustNotExist("atomic.a") 3053 tg.mustNotExist("atomic.exe") 3054 3055 tg.runFail("build", "-o", "whatever", "cmd/gofmt", "sync/atomic") 3056 tg.grepStderr("multiple packages", "did not reject -o with multiple packages") 3057 } 3058 3059 func TestGoBuildARM(t *testing.T) { 3060 if testing.Short() { 3061 t.Skip("skipping cross-compile in short mode") 3062 } 3063 3064 tg := testgo(t) 3065 defer tg.cleanup() 3066 3067 tg.makeTempdir() 3068 tg.cd(tg.path(".")) 3069 3070 tg.setenv("GOARCH", "arm") 3071 tg.setenv("GOOS", "linux") 3072 tg.setenv("GOARM", "5") 3073 tg.tempFile("hello.go", `package main 3074 func main() {}`) 3075 tg.run("build", "hello.go") 3076 tg.grepStderrNot("unable to find math.a", "did not build math.a correctly") 3077 } 3078 3079 func TestIssue13655(t *testing.T) { 3080 tg := testgo(t) 3081 defer tg.cleanup() 3082 for _, pkg := range []string{"runtime", "runtime/internal/atomic"} { 3083 tg.run("list", "-f", "{{.Deps}}", pkg) 3084 tg.grepStdout("runtime/internal/sys", "did not find required dependency of "+pkg+" on runtime/internal/sys") 3085 } 3086 } 3087 3088 // For issue 14337. 3089 func TestParallelTest(t *testing.T) { 3090 tg := testgo(t) 3091 defer tg.cleanup() 3092 tg.makeTempdir() 3093 const testSrc = `package package_test 3094 import ( 3095 "testing" 3096 ) 3097 func TestTest(t *testing.T) { 3098 }` 3099 tg.tempFile("src/p1/p1_test.go", strings.Replace(testSrc, "package_test", "p1_test", 1)) 3100 tg.tempFile("src/p2/p2_test.go", strings.Replace(testSrc, "package_test", "p2_test", 1)) 3101 tg.tempFile("src/p3/p3_test.go", strings.Replace(testSrc, "package_test", "p3_test", 1)) 3102 tg.tempFile("src/p4/p4_test.go", strings.Replace(testSrc, "package_test", "p4_test", 1)) 3103 tg.setenv("GOPATH", tg.path(".")) 3104 tg.run("test", "-p=4", "p1", "p2", "p3", "p4") 3105 } 3106 3107 func TestCgoConsistentResults(t *testing.T) { 3108 if !canCgo { 3109 t.Skip("skipping because cgo not enabled") 3110 } 3111 if runtime.GOOS == "solaris" { 3112 // See https://golang.org/issue/13247 3113 t.Skip("skipping because Solaris builds are known to be inconsistent; see #13247") 3114 } 3115 3116 tg := testgo(t) 3117 defer tg.cleanup() 3118 tg.parallel() 3119 tg.makeTempdir() 3120 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 3121 exe1 := tg.path("cgotest1" + exeSuffix) 3122 exe2 := tg.path("cgotest2" + exeSuffix) 3123 tg.run("build", "-o", exe1, "cgotest") 3124 tg.run("build", "-x", "-o", exe2, "cgotest") 3125 b1, err := ioutil.ReadFile(exe1) 3126 tg.must(err) 3127 b2, err := ioutil.ReadFile(exe2) 3128 tg.must(err) 3129 3130 if !tg.doGrepMatch(`-fdebug-prefix-map=\$WORK`, &tg.stderr) { 3131 t.Skip("skipping because C compiler does not support -fdebug-prefix-map") 3132 } 3133 if !bytes.Equal(b1, b2) { 3134 t.Error("building cgotest twice did not produce the same output") 3135 } 3136 } 3137 3138 // Issue 14444: go get -u .../ duplicate loads errors 3139 func TestGoGetUpdateAllDoesNotTryToLoadDuplicates(t *testing.T) { 3140 testenv.MustHaveExternalNetwork(t) 3141 3142 tg := testgo(t) 3143 defer tg.cleanup() 3144 tg.makeTempdir() 3145 tg.setenv("GOPATH", tg.path(".")) 3146 tg.run("get", "-u", ".../") 3147 tg.grepStderrNot("duplicate loads of", "did not remove old packages from cache") 3148 } 3149 3150 // Issue 17119 more duplicate load errors 3151 func TestIssue17119(t *testing.T) { 3152 testenv.MustHaveExternalNetwork(t) 3153 3154 tg := testgo(t) 3155 defer tg.cleanup() 3156 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 3157 tg.runFail("build", "dupload") 3158 tg.grepBothNot("duplicate load|internal error", "internal error") 3159 } 3160 3161 func TestFatalInBenchmarkCauseNonZeroExitStatus(t *testing.T) { 3162 tg := testgo(t) 3163 defer tg.cleanup() 3164 tg.runFail("test", "-bench", ".", "./testdata/src/benchfatal") 3165 tg.grepBothNot("^ok", "test passed unexpectedly") 3166 tg.grepBoth("FAIL.*benchfatal", "test did not run everything") 3167 } 3168 3169 func TestBinaryOnlyPackages(t *testing.T) { 3170 tg := testgo(t) 3171 defer tg.cleanup() 3172 tg.makeTempdir() 3173 tg.setenv("GOPATH", tg.path(".")) 3174 3175 tg.tempFile("src/p1/p1.go", `//go:binary-only-package 3176 3177 package p1 3178 `) 3179 tg.wantStale("p1", "cannot access install target", "p1 is binary-only but has no binary, should be stale") 3180 tg.runFail("install", "p1") 3181 tg.grepStderr("missing or invalid package binary", "did not report attempt to compile binary-only package") 3182 3183 tg.tempFile("src/p1/p1.go", ` 3184 package p1 3185 import "fmt" 3186 func F(b bool) { fmt.Printf("hello from p1\n"); if b { F(false) } } 3187 `) 3188 tg.run("install", "p1") 3189 os.Remove(tg.path("src/p1/p1.go")) 3190 tg.mustNotExist(tg.path("src/p1/p1.go")) 3191 3192 tg.tempFile("src/p2/p2.go", `//go:binary-only-packages-are-not-great 3193 3194 package p2 3195 import "p1" 3196 func F() { p1.F(true) } 3197 `) 3198 tg.runFail("install", "p2") 3199 tg.grepStderr("no buildable Go source files", "did not complain about missing sources") 3200 3201 tg.tempFile("src/p1/missing.go", `//go:binary-only-package 3202 3203 package p1 3204 func G() 3205 `) 3206 tg.wantNotStale("p1", "no source code", "should NOT want to rebuild p1 (first)") 3207 tg.run("install", "-x", "p1") // no-op, up to date 3208 tg.grepBothNot("/compile", "should not have run compiler") 3209 tg.run("install", "p2") // does not rebuild p1 (or else p2 will fail) 3210 tg.wantNotStale("p2", "", "should NOT want to rebuild p2") 3211 3212 // changes to the non-source-code do not matter, 3213 // and only one file needs the special comment. 3214 tg.tempFile("src/p1/missing2.go", ` 3215 package p1 3216 func H() 3217 `) 3218 tg.wantNotStale("p1", "no source code", "should NOT want to rebuild p1 (second)") 3219 tg.wantNotStale("p2", "", "should NOT want to rebuild p2") 3220 3221 tg.tempFile("src/p3/p3.go", ` 3222 package main 3223 import ( 3224 "p1" 3225 "p2" 3226 ) 3227 func main() { 3228 p1.F(false) 3229 p2.F() 3230 } 3231 `) 3232 tg.run("install", "p3") 3233 3234 tg.run("run", tg.path("src/p3/p3.go")) 3235 tg.grepStdout("hello from p1", "did not see message from p1") 3236 3237 tg.tempFile("src/p4/p4.go", `package main`) 3238 tg.tempFile("src/p4/p4not.go", `//go:binary-only-package 3239 3240 // +build asdf 3241 3242 package main 3243 `) 3244 tg.run("list", "-f", "{{.BinaryOnly}}", "p4") 3245 tg.grepStdout("false", "did not see BinaryOnly=false for p4") 3246 } 3247 3248 // Issue 16050. 3249 func TestAlwaysLinkSysoFiles(t *testing.T) { 3250 tg := testgo(t) 3251 defer tg.cleanup() 3252 tg.parallel() 3253 tg.tempDir("src/syso") 3254 tg.tempFile("src/syso/a.syso", ``) 3255 tg.tempFile("src/syso/b.go", `package syso`) 3256 tg.setenv("GOPATH", tg.path(".")) 3257 3258 // We should see the .syso file regardless of the setting of 3259 // CGO_ENABLED. 3260 3261 tg.setenv("CGO_ENABLED", "1") 3262 tg.run("list", "-f", "{{.SysoFiles}}", "syso") 3263 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=1") 3264 3265 tg.setenv("CGO_ENABLED", "0") 3266 tg.run("list", "-f", "{{.SysoFiles}}", "syso") 3267 tg.grepStdout("a.syso", "missing syso file with CGO_ENABLED=0") 3268 } 3269 3270 // Issue 16120. 3271 func TestGenerateUsesBuildContext(t *testing.T) { 3272 if runtime.GOOS == "windows" { 3273 t.Skip("this test won't run under Windows") 3274 } 3275 3276 tg := testgo(t) 3277 defer tg.cleanup() 3278 tg.parallel() 3279 tg.tempDir("src/gen") 3280 tg.tempFile("src/gen/gen.go", "package gen\n//go:generate echo $GOOS $GOARCH\n") 3281 tg.setenv("GOPATH", tg.path(".")) 3282 3283 tg.setenv("GOOS", "linux") 3284 tg.setenv("GOARCH", "amd64") 3285 tg.run("generate", "gen") 3286 tg.grepStdout("linux amd64", "unexpected GOOS/GOARCH combination") 3287 3288 tg.setenv("GOOS", "darwin") 3289 tg.setenv("GOARCH", "386") 3290 tg.run("generate", "gen") 3291 tg.grepStdout("darwin 386", "unexpected GOOS/GOARCH combination") 3292 } 3293 3294 // Issue 14450: go get -u .../ tried to import not downloaded package 3295 func TestGoGetUpdateWithWildcard(t *testing.T) { 3296 testenv.MustHaveExternalNetwork(t) 3297 3298 tg := testgo(t) 3299 defer tg.cleanup() 3300 tg.makeTempdir() 3301 tg.setenv("GOPATH", tg.path(".")) 3302 const aPkgImportPath = "github.com/tmwh/go-get-issue-14450/a" 3303 tg.run("get", aPkgImportPath) 3304 tg.run("get", "-u", ".../") 3305 tg.grepStderrNot("cannot find package", "did not update packages given wildcard path") 3306 3307 var expectedPkgPaths = []string{ 3308 "src/github.com/tmwh/go-get-issue-14450/b", 3309 "src/github.com/tmwh/go-get-issue-14450-b-dependency/c", 3310 "src/github.com/tmwh/go-get-issue-14450-b-dependency/d", 3311 } 3312 3313 for _, importPath := range expectedPkgPaths { 3314 _, err := os.Stat(tg.path(importPath)) 3315 tg.must(err) 3316 } 3317 const notExpectedPkgPath = "src/github.com/tmwh/go-get-issue-14450-c-dependency/e" 3318 tg.mustNotExist(tg.path(notExpectedPkgPath)) 3319 } 3320 3321 func TestGoEnv(t *testing.T) { 3322 tg := testgo(t) 3323 defer tg.cleanup() 3324 tg.setenv("GOARCH", "arm") 3325 tg.run("env", "GOARCH") 3326 tg.grepStdout("^arm$", "GOARCH not honored") 3327 3328 tg.run("env", "GCCGO") 3329 tg.grepStdout(".", "GCCGO unexpectedly empty") 3330 3331 tg.run("env", "CGO_CFLAGS") 3332 tg.grepStdout(".", "default CGO_CFLAGS unexpectedly empty") 3333 3334 tg.setenv("CGO_CFLAGS", "-foobar") 3335 tg.run("env", "CGO_CFLAGS") 3336 tg.grepStdout("^-foobar$", "CGO_CFLAGS not honored") 3337 } 3338 3339 const ( 3340 noMatchesPattern = `(?m)^ok.*\[no tests to run\]` 3341 okPattern = `(?m)^ok` 3342 ) 3343 3344 func TestMatchesNoTests(t *testing.T) { 3345 tg := testgo(t) 3346 defer tg.cleanup() 3347 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_test.go") 3348 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]") 3349 } 3350 3351 func TestMatchesNoTestsDoesNotOverrideBuildFailure(t *testing.T) { 3352 tg := testgo(t) 3353 defer tg.cleanup() 3354 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 3355 tg.runFail("test", "-run", "ThisWillNotMatch", "syntaxerror") 3356 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3357 tg.grepBoth("FAIL", "go test did not say FAIL") 3358 } 3359 3360 func TestMatchesNoBenchmarks(t *testing.T) { 3361 tg := testgo(t) 3362 defer tg.cleanup() 3363 tg.run("test", "-bench", "ThisWillNotMatch", "testdata/standalone_benchmark_test.go") 3364 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]") 3365 } 3366 3367 func TestMatchesOnlyExampleIsOK(t *testing.T) { 3368 tg := testgo(t) 3369 defer tg.cleanup() 3370 tg.run("test", "-run", "Example", "testdata/example1_test.go") 3371 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3372 tg.grepBoth(okPattern, "go test did not say ok") 3373 } 3374 3375 func TestMatchesOnlyBenchmarkIsOK(t *testing.T) { 3376 tg := testgo(t) 3377 defer tg.cleanup() 3378 tg.run("test", "-bench", ".", "testdata/standalone_test.go") 3379 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3380 tg.grepBoth(okPattern, "go test did not say ok") 3381 } 3382 3383 func TestMatchesOnlyTestIsOK(t *testing.T) { 3384 tg := testgo(t) 3385 defer tg.cleanup() 3386 tg.run("test", "-run", "Test", "testdata/standalone_test.go") 3387 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3388 tg.grepBoth(okPattern, "go test did not say ok") 3389 } 3390 3391 func TestMatchesNoTestsWithSubtests(t *testing.T) { 3392 tg := testgo(t) 3393 defer tg.cleanup() 3394 tg.run("test", "-run", "ThisWillNotMatch", "testdata/standalone_sub_test.go") 3395 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]") 3396 } 3397 3398 func TestMatchesNoSubtestsMatch(t *testing.T) { 3399 tg := testgo(t) 3400 defer tg.cleanup() 3401 tg.run("test", "-run", "Test/ThisWillNotMatch", "testdata/standalone_sub_test.go") 3402 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]") 3403 } 3404 3405 func TestMatchesNoSubtestsDoesNotOverrideFailure(t *testing.T) { 3406 tg := testgo(t) 3407 defer tg.cleanup() 3408 tg.runFail("test", "-run", "TestThatFails/ThisWillNotMatch", "testdata/standalone_fail_sub_test.go") 3409 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3410 tg.grepBoth("FAIL", "go test did not say FAIL") 3411 } 3412 3413 func TestMatchesOnlySubtestIsOK(t *testing.T) { 3414 tg := testgo(t) 3415 defer tg.cleanup() 3416 tg.run("test", "-run", "Test/Sub", "testdata/standalone_sub_test.go") 3417 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3418 tg.grepBoth(okPattern, "go test did not say ok") 3419 } 3420 3421 func TestMatchesNoSubtestsParallel(t *testing.T) { 3422 tg := testgo(t) 3423 defer tg.cleanup() 3424 tg.run("test", "-run", "Test/Sub/ThisWillNotMatch", "testdata/standalone_parallel_sub_test.go") 3425 tg.grepBoth(noMatchesPattern, "go test did not say [no tests to run]") 3426 } 3427 3428 func TestMatchesOnlySubtestParallelIsOK(t *testing.T) { 3429 tg := testgo(t) 3430 defer tg.cleanup() 3431 tg.run("test", "-run", "Test/Sub/Nested", "testdata/standalone_parallel_sub_test.go") 3432 tg.grepBothNot(noMatchesPattern, "go test did say [no tests to run]") 3433 tg.grepBoth(okPattern, "go test did not say ok") 3434 } 3435 3436 func TestLinkXImportPathEscape(t *testing.T) { 3437 // golang.org/issue/16710 3438 tg := testgo(t) 3439 defer tg.cleanup() 3440 tg.setenv("GOPATH", filepath.Join(tg.pwd(), "testdata")) 3441 exe := "./linkx" + exeSuffix 3442 tg.creatingTemp(exe) 3443 tg.run("build", "-o", exe, "-ldflags", "-X=my.pkg.Text=linkXworked", "my.pkg/main") 3444 out, err := exec.Command(exe).CombinedOutput() 3445 if err != nil { 3446 tg.t.Fatal(err) 3447 } 3448 if string(out) != "linkXworked\n" { 3449 tg.t.Log(string(out)) 3450 tg.t.Fatal(`incorrect output: expected "linkXworked\n"`) 3451 } 3452 }